0008: BufferedReader tKeyboard = 0009: new BufferedReader(new InputStreamReader(System.in)); 0010: System.out.print("Type in your first number: "); 0011: String tFirstString = tKeyboard.readLine(); 0012: double tFirst = Double.parseDouble(tFirstString);Note the use of both instance methods and class methods and the need to use the wrapper classes of the primitive types.’
0026: Scanner tScanner = new Scanner(System.in); 0027: System.out.print("Type in your first number: "); 0028: double tFirst = tScanner.nextDouble();
0021: import java.util.Scanner; // SumProgNew.java 0022: public class SumProgNew 0023: { 0024: public static void main(String[] pArgs) 0025: { 0026: Scanner tScanner = new Scanner(System.in); 0027: System.out.print("Type in your first number: "); 0028: double tFirst = tScanner.nextDouble(); 0029: System.out.print("Type in your second number: "); 0030: double tSecond = tScanner.nextDouble(); 0031: double tSum = tFirst + tSecond; 0032: System.out.println("The sum of " + tFirst + 0033: " and " + tSecond + " is " + tSum); 0034: } 0035: }
0036: Type in your first number: 27 0037: Type in your second number: 42 0038: The sum of 27.0 and 42.0 is 69.0
The class Scanner allows you easily to associate a variable with one of a number of different input streams such as the keyboard, a file or a string:
0047: Scanner tScannerKeyboard = new Scanner(System.in); 0048: Scanner tScannerInputFile = new Scanner(new File("input.txt")); 0049: Scanner tScannerSomeString = new Scanner(tSomeString);
You can then apply methods such as nextInt to read a value from the input stream. Here, an unchecked exception java.util.InputMisMatchException will be thrown if the next token is not an int.
To avoid the possibility of this exception occurring, a method like hasNextInt can be used to determine if the next value is an int, as shown in this program:
0067: import java.util.Scanner; // Analyse.java 0068: public class Analyse 0069: { 0070: public static void main(String[] pArgs) 0071: { 0072: Scanner tScanner = new Scanner(System.in); 0073: System.out.print("Type in a value: "); 0074: if (tScanner.hasNextInt()) { 0075: int tFirst = tScanner.nextInt(); 0076: System.out.println("Got an int: " + tFirst); 0077: } 0078: else if (tScanner.hasNextDouble()) { 0079: double tFirst = tScanner.nextDouble(); 0080: System.out.println("Got a double: " + tFirst); 0081: } 0082: else { 0083: String tFirst = tScanner.nextLine(); 0084: System.out.println("Got a string: " + tFirst); 0085: } 0086: } 0087: }
The Scanner class also helps when you want the user to be able to type more than one value on a line. Suppose we want to read in an age, a height and the number of children. So the data might be something like:
42 1.85 2Before Java 5, you would need to use something like StringTokenizer to break apart a line into separate items (often called tokens):
0100: String tLine = tKeyboard.readLine(); 0101: StringTokenizer tTokens = new StringTokenizer(tLine); 0102: String tAgeString = tTokens.nextToken(); 0103: int tAge = Integer.parseInt(tAgeString); 0104: String tHeightString = tTokens.nextToken(); 0105: double tHeight = Double.parseDouble(tHeightString); 0106: String tNumberOfChildrenString = tTokens.nextToken(); 0107: int tNumberOfChildren = Integer.parseInt(tNumberOfChildrenString);
However, the nextXXX methods of the Scanner class can cope with several items being on the same line. So the data:
42 1.85 2can be read by the following code:
0120: int tAge = tScanner.nextInt(); 0121: double tHeight = tScanner.nextDouble(); 0122: int tNumberOfChildren = tScanner.nextInt();
By default, tokens are assumed to be separated by whitespace. However, you can easily arrange for the scanner to use delimiters other than whitespace.
0132: int[ ] tMonthStarts = 0133: { 1,32,60,91,121,152,182,213,244,274,305,335 }; 0134: System.out.println(Arrays.toString(tMonthStarts));
0136: for (int tMonthNumber = 0; 0137: tMonthNumber<tMonthStarts.length; tMonthNumber++) 0138: { 0139: System.out.println(tMonthStarts[tMonthNumber]); 0140: }
for ( decl : expr )
0148: package java.lang; // Iterable.java 0149: import java.util.Iterator; 0150: public interface Iterable 0151: { 0152: public Iterator iterator(); 0153: }
0161: List tList = new ArrayList(); 0162: tList.add("Hello world");
0163: String tNewString = (String)tList.get(0); 0164: System.out.println(tNewString.substring(0, 5));
0165: Date tDate = new Date(); 0166: tList.add(tDate);
0169: int tNumber = 123; 0170: Integer tWrapper = new Integer(tNumber); 0171: tList.add(tWrapper);
0172: Integer tNewWrapper = (Integer)tList.get(2); 0173: int tNewNumber = tNewWrapper.intValue(); 0174: System.out.println(tNewNumber);
0175: int tValue = 123; 0176: tList.add(tValue); 0177: int tNewValue = (Integer)tList.get(3); 0178: System.out.println(tNewValue);
0182: public class Integers // Integers.java 0183: { 0184: public static void main(String[] pArgs) 0185: { 0186: Integer tWrapper = 127; 0187: Integer tNewWrapper = tWrapper + tWrapper; 0188: System.out.println(tNewWrapper); 0189: if (tWrapper<tNewWrapper) 0190: { 0191: System.out.println(tWrapper + " is less than " + tNewWrapper); 0192: } 0193: tNewWrapper = 127; 0194: if (tWrapper==tNewWrapper) 0195: System.out.println(tWrapper + " is equal to " + tNewWrapper); 0196: else 0197: System.out.println(tWrapper + " differs from " + tNewWrapper); 0198: tWrapper = 128; 0199: tNewWrapper = 128; 0200: if (tWrapper==tNewWrapper) 0201: System.out.println(tWrapper + " is equal to " + tNewWrapper); 0202: else 0203: System.out.println(tWrapper + " differs from " + tNewWrapper); 0204: } 0205: }
0206: 254 0207: 127 is less than 254 0208: 127 is equal to 127 0209: 128 differs from 128
Suppose there is a method called iEvaluate that expects as arguments a double and any number of ints. Here are some examples of a call of this method:
0214: double tResult = iEvaluate(2.7, 25, 2, -5, 42, -10); 0215: System.out.println(tResult); 0216: tResult = iEvaluate(4.2, 42); 0217: System.out.println(tResult); 0218: tResult = iEvaluate(4.2); 0219: System.out.println(tResult);
And here is a possible iEvaluate method:
0221: private static double iEvaluate(double pFactor, int... pValues) 0222: { 0223: int tSum = 0; 0224: for (int tValue : pValues) 0225: tSum += tValue; 0226: return tSum/pFactor; 0227: }
The int... signifies that the remaining arguments are ints. Within the method, this parameter behaves like an array and so the method can use a foreach loop.
Java 5 introduces a new class called java.util.Formatter. The API documentation for this class is at [31]. It says: ‘Formatted printing for the Java language is heavily inspired by C's printf. Although the format strings are similar to C, some customizations have been made to accommodate the Java language and exploit some of its features. Also, Java formatting is more strict than C's; for example, if a conversion is incompatible with a flag, an exception will be thrown. In C inapplicable flags are silently ignored. The format strings are thus intended to be recognizable to C programmers but not necessarily completely compatible with those in C.’
Here are some examples of the use of printf:
0242: System.out.printf("%3d %1.2f%n%d%n", 0243: tAge, tHeight, tNumberOfChildren); 0244: String tFormat = 0245: "Age is %d, height is %f%nNo. of children is %d%n"; 0246: System.out.printf(tFormat, tAge, tHeight, tNumberOfChildren); 0247: Calendar tNow = Calendar.getInstance(); 0248: System.out.printf("%tT%n", tNow); 0249: System.out.printf("%tY-%tm-%td%n", tNow, tNow, tNow); 0250: System.out.printf("%tH:%<tM:%<tS%n", tNow);
The above code produces output like the following:
0253: 42 1.85 0254: 2 0255: Age is 42, height is 1.850000 0256: No. of children is 2 0257: 08:03:39 0258: 2004-08-12 0259: 08:03:39
The printf method used above is from the java.io.PrintStream package.
0260: public class Shape // Shape.java 0261: { 0262: private int iX, iY; 0263: public Shape(int pX, int pY) 0264: { 0265: iX = pX; iY = pY; 0266: } 0267: public int getX() 0268: { 0269: return iX; 0270: } 0271: public int getY() 0272: { 0273: return iY; 0274: } 0275: public Shape translate(int pX, int pY) 0276: { 0277: return new Shape(iX + pX, iY + pY); 0278: } 0279: public boolean equals(Object pObject) 0280: { 0281: return iX==((Shape)pObject).iX && iY==((Shape)pObject).iY; 0282: } 0283: public String toString() 0284: { 0285: return iX + ":" + iY; 0286: } 0287: }
Shape tShape = new Shape(100, 200); Shape tNewShape = tShape.translate(1, 2); System.out.println(tNewShape);
0288: public class Circle extends Shape // Circle.java 0289: { 0290: private int iRadius; 0291: public Circle(int pX, int pY, int pRadius) { 0292: super(pX, pY); 0293: iRadius = pRadius; 0294: } 0295: public int getRadius() 0296: { 0297: return iRadius; 0298: } 0299: public Shape translate(int pX, int pY) 0300: { 0301: return new Circle(getX() + pX, getY() + pY, iRadius); 0302: } 0303: public boolean equals(Object pObject) 0304: { 0305: return super.equals(pObject) && 0306: iRadius==((Circle)pObject).iRadius; 0307: } 0308: public String toString() 0309: { 0310: return super.toString() + ":" + iRadius; 0311: } 0312: }
0299: public Shape translate(int pX, int pY)
0331: Circle tCircle = new Circle(x, y, radius); 0332: Circle tNewCircle = (Circle)tCircle.translate(1, 2); 0333: System.out.println(tNewCircle.getRadius());
0367: public Circle translate(int pX, int pY)
0381: Circle.java:12: translate(int,int) in Circle cannot 0382: override translate(int,int) in Shape; attempting to use 0383: incompatible return type 0384: found : Circle 0385: required: Shape 0386: public Circle translate(int pX, int pY) 0387: ^
0367: public Circle translate(int pX, int pY)
0406: Circle tCircle = new Circle(x, y, radius); 0407: Circle tNewCircle = tCircle.translate(1, 2); 0408: System.out.println(tNewCircle.getRadius());
Shape tShape = new Shape(100, 200); Shape tShapeSame = tShape;then both Shape variables point to the same object.
public Object clone() { ... }
Shape tShape = new Shape(100, 200); Shape tShapeCopy = (Shape)tShape.clone();
public Shape clone() { ... }
Shape tShape = new Shape(100, 200); Shape tShapeCopy = tShape.clone();
0432: private enum Day 0433: { 0434: Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday 0435: }
0430: public class SimpleDayProg // SimpleDayProg.java 0431: { 0432: private enum Day 0433: { 0434: Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday 0435: } 0436: public static void main(String[] pArgs) 0437: { 0438: Day tToday = Day.Wednesday; System.out.println(tToday); 0439: } 0440: }
0441: Wednesday
0452: Scanner tScanner = new Scanner(System.in); 0453: String tInputString = tScanner.next(); 0454: Day tInputDay = Day.valueOf(tInputString); 0455: switch (tInputDay) 0456: { 0457: case Sunday: System.out.println("wash car"); break; 0458: case Saturday: System.out.println("do nothing"); break; 0459: default: System.out.println("go to work"); break; 0460: } 0461: for (Day tDay : Day.values()) 0462: { 0463: System.out.println(tDay + " " + tDay.ordinal()); 0464: }
0500: Sunday 0501: wash car 0502: Sunday 0 0503: Monday 1 0504: Tuesday 2 0505: Wednesday 3 0506: Thursday 4 0507: Friday 5 0508: Saturday 6
You can use the new class java.util.EnumSet to create a set of enums and the new class java.util.EnumMap to create a map that uses enums as keys.
Here is some code illustrating two uses of EnumSet:
0472: Day tToday = Day.Wednesday; 0473: Day[] tDayValues = Day.values(); 0474: for (int tDayNumber = Day.Tuesday.ordinal(); 0475: tDayNumber<=Day.Thursday.ordinal(); tDayNumber++) 0476: { 0477: Day tDay = tDayValues[tDayNumber]; 0478: System.out.println(tDay + " " + tDay.compareTo(tToday)); 0479: } 0480: for (Day tDay : EnumSet.range(Day.Tuesday, Day.Thursday)) 0481: { 0482: System.out.println(tDay + " " + tDay.compareTo(tToday)); 0483: } 0484: for (Day tDay : Day.values()) 0485: { 0486: if (tDay.toString().length()==6) 0487: { 0488: System.out.println(tDay + " is a 6 letter day"); 0489: } 0490: } 0491: for (Day tDay : Day.values()) 0492: { 0493: if (EnumSet.of(Day.Sunday, Day.Monday, Day.Friday).contains(tDay)) 0494: { 0495: System.out.println(tDay + " is a 6 letter day"); 0496: } 0497: }
The above code produces the output:
0511: Tuesday -1 0512: Wednesday 0 0513: Thursday 1 0514: Tuesday -1 0515: Wednesday 0 0516: Thursday 1 0517: Sunday is a 6 letter day 0518: Monday is a 6 letter day 0519: Friday is a 6 letter day 0520: Sunday is a 6 letter day 0521: Monday is a 6 letter day 0522: Friday is a 6 letter day
0523: public enum Day // Day.java 0524: { 0525: Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday; 0526: public String toString() 0527: { 0528: return super.toString().substring(0, 3); 0529: } 0530: private static Day[] iDayValues = Day.values(); 0531: public static Day getFirst() 0532: { 0533: return iDayValues[0]; 0534: } 0535: public boolean isLast() 0536: { 0537: return this==iDayValues[iDayValues.length - 1]; 0538: } 0539: public Day getNext() 0540: { 0541: int tNewPos = ordinal() + 1; 0542: if (tNewPos==iDayValues.length) 0543: return iDayValues[0]; 0544: else 0545: return iDayValues[tNewPos]; 0546: } 0547: }
0548: public class DayProg // DayProg.java 0549: { 0550: public static void main(String[] pArgs) 0551: { 0552: System.out.println("getFirst: " + Day.getFirst()); 0553: Day tToday = Day.Wednesday; 0554: System.out.println("tToday.isLast: " + tToday.isLast()); 0555: System.out.println("Day.Saturday.isLast: " + Day.Saturday.isLast()); 0556: for (Day tDay : Day.values()) 0557: { 0558: System.out.print(tDay.getNext() + " "); 0559: } 0560: System.out.println(); 0561: } 0562: }
0563: getFirst: Sun 0564: tToday.isLast: false 0565: Day.Saturday.isLast: true 0566: Mon Tue Wed Thu Fri Sat Sun
0567: public enum ShopDay // ShopDay.java 0568: { 0569: Sunday (new Time("10:00"), new Time("16:00")), 0570: Monday (new Time("08:00"), new Time("17:30")), 0571: Tuesday (new Time("08:00"), new Time("17:30")), 0572: Wednesday(new Time("08:00"), new Time("17:30")), 0573: Thursday (new Time("08:00"), new Time("17:30")), 0574: Friday (new Time("08:00"), new Time("17:30")), 0575: Saturday (new Time("09:00"), new Time("12:30")); 0576: private Time iStartTime; 0577: private Time iFinishTime; 0578: private ShopDay(Time pStartTime, Time pFinishTime) 0579: { 0580: iStartTime = pStartTime; 0581: iFinishTime = pFinishTime; 0582: } 0583: public Time getStartTime() 0584: { 0585: return iStartTime; 0586: } 0587: public Time getFinishTime() 0588: { 0589: return iFinishTime; 0590: } 0591: }
0592: public class Time // Time.java 0593: { 0594: private String iString; 0595: public Time(String pString) 0596: { 0597: iString = pString; 0598: } 0599: public String toString() 0600: { 0601: return iString; 0602: } 0603: }
0604: public class ShopDayProg // ShopDayProg.java 0605: { 0606: public static void main(String[] pArgs) 0607: { 0608: for (ShopDay tShopDay : ShopDay.values()) 0609: { 0610: System.out.println(tShopDay + " " + tShopDay.getStartTime() + 0611: " " + tShopDay.getFinishTime()); 0612: } 0613: } 0614: }
0615: Sunday 10:00 16:00 0616: Monday 08:00 17:30 0617: Tuesday 08:00 17:30 0618: Wednesday 08:00 17:30 0619: Thursday 08:00 17:30 0620: Friday 08:00 17:30 0621: Saturday 09:00 12:30
0633: @NeedsFurtherTesting 0634: private static double iGetDouble(String pLabel) 0635: { 0636: System.out.print("Type in your " + pLabel + " number: "); 0637: Scanner tScanner = new Scanner(System.in); 0638: return tScanner.nextDouble(); 0639: } 0640: @NeedsFurtherTesting 0641: @ToDo(programmer="Barry Cornelius", 0642: importance=ToDo.Importance.High, 0643: deadline="2004-08-31") 0644: private static double iFindSum(double pLHS, double pRHS) 0645: { 0646: return pLHS + pRHS; 0647: }
0649: public @interface NeedsFurtherTesting // NeedsFurtherTesting.java 0650: { 0651: }
0652: public @interface ToDo // ToDo.java 0653: { 0654: public enum Importance {VeryHigh, High, Medium, Low}; 0655: public String programmer(); 0656: public Importance importance(); 0657: public String deadline(); 0658: }
java.lang Annotation Type Override @Target(value=METHOD) @Retention(value=SOURCE) public @interface Override Indicates that a method declaration is intended to override a method declaration in a superclass. If a method is annotated with this annotation type but does not override a superclass method, compilers are required to generate an error message.
0682: public int hashcode() 0683: { 0684: return 0; 0685: } 0686: public String toString(String pString) 0687: { 0688: return iX + ":" + iY; 0689: }
0725: Shape tShape = shapes[shapeNumber]; 0726: System.out.println(tShape);will use the toString method from the class Object.
0753: @Override 0754: public int hashcode() 0755: { 0756: return 0; 0757: } 0758: @Override 0759: public String toString(String pString) 0760: { 0761: return iX + ":" + iY; 0762: }
method does not override a method from its superclass
0764: import javax.jws.WebMethod; // HelloWorldService.java 0765: import javax.jws.WebService; 0766: @WebService 0767: public class HelloWorldService 0768: { 0769: @WebMethod 0770: public String helloWorld() 0771: { 0772: return "Hello World!"; 0773: } 0774: }
The Java Community Process (JSR 250) has also produced ‘annotations for common semantic concepts in the J2SE and J2EE platforms that apply across a variety of individual technologies. With the addition of JSR 175 ... we envision that various JSRs will use annotations to enable a declarative style of programming’. See [34] for more details of JSR 250.
0781: List tList = new ArrayList();in which we are storing Shapes, i.e., we normally do something like:
0782: Shape tShape = new Shape(100, 200); 0783: tList.add(tShape);or:
0784: Circle tCircle = new Circle(100, 200, 10); 0785: tList.add(tCircle);
0786: Shape tShapeGet0 = (Shape)tList.get(0); 0787: System.out.println(tShapeGet0); 0788: Shape tShapeGet1 = (Shape)tList.get(1); 0789: System.out.println(tShapeGet1);and this code produces the output:
0795: 100:200 0796: 100:200:10
0790: tList.add("hello world");
0791: Shape tShapeGet2 = (Shape)tList.get(2); 0792: System.out.println(tShapeGet2);our program will collapse with a ClassCastException:
0797: Exception in thread "main" java.lang.ClassCastException 0798: at ListShape.main(ListShape.java:17)
Class ArrayList<E>
Interface List<E>
0805: List<Shape> tList = new ArrayList<Shape>();
public boolean add(Object o)the add method is now documented as:
public boolean add(E o)
0806: Shape tShape = new Shape(100, 200); 0807: tList.add(tShape); 0808: Circle tCircle = new Circle(100, 200, 10); 0809: tList.add(tCircle);
0814: tList.add("hello world");
0819: ListShape.java:16: cannot find symbol 0820: symbol : method add(java.lang.String) 0821: location: interface java.util.List<Shape> 0822: tList.add("hello world"); 0823: ^
public Object get(int index)to:
public E get(int index)
0810: Shape tShapeGet0 = tList.get(0); 0811: System.out.println(tShapeGet0); 0812: Shape tShapeGet1 = tList.get(1); 0813: System.out.println(tShapeGet1);
0805: List<Shape> tList = new ArrayList<Shape>(); 0806: Shape tShape = new Shape(100, 200); 0807: tList.add(tShape); 0808: Circle tCircle = new Circle(100, 200, 10); 0809: tList.add(tCircle); 0810: Shape tShapeGet0 = tList.get(0); 0811: System.out.println(tShapeGet0); 0812: Shape tShapeGet1 = tList.get(1); 0813: System.out.println(tShapeGet1);
0781: List tList = new ArrayList(); 0782: Shape tShape = new Shape(100, 200); 0783: tList.add(tShape); 0784: Circle tCircle = new Circle(100, 200, 10); 0785: tList.add(tCircle); 0786: Shape tShapeGet0 = (Shape)tList.get(0); 0787: System.out.println(tShapeGet0); 0788: Shape tShapeGet1 = (Shape)tList.get(1); 0789: System.out.println(tShapeGet1);
The type List<Shape> can be used just like any other type. So we can produce methods that have this as their return type, or a method that has this as the type of one of its parameters:
0860: private static void printList1(List<Shape> pList) 0861: { 0862: Iterator<Shape> tIterator = pList.iterator(); 0863: while (tIterator.hasNext()) 0864: { 0865: Shape tShape = tIterator.next(); 0866: System.out.println("X is " + tShape.getX()); 0867: } 0868: }
However, with Java 5, many of the uses of Iterator should be replaced by a foreach statement. So the above can be simplified to:
0869: private static void printList2(List<Shape> pList) 0870: { 0871: for (Shape tShape : pList) 0872: { 0873: System.out.println("X is " + tShape.getX()); 0874: } 0875: }
Things get interesting when you want to write a method that works for any homogeneous list: a list of shapes, a list of strings, and so on. The new notation:
List<?>has to be used: it means a List where each element is of some unknown type. Here it is in action:
0876: private static void printList3(List<?> pList) 0877: { 0878: Iterator<?> tIterator = pList.iterator(); 0879: while (tIterator.hasNext()) 0880: { 0881: Object tObject = tIterator.next(); 0882: System.out.println(tObject); 0883: } 0884: }
Once again, this can be simplified to:
0885: private static void printList4(List<?> pList) 0886: { 0887: for (Object tObject : pList) 0888: { 0889: System.out.println(tObject); 0890: } 0891: }
Suppose instead you want to provide a method that works only for a List where the element type is the type Shape or any of its subclasses. You may be tempted to use one of the methods given earlier, a method that has a parameter of type List<Shape>. However, a class that implements the interface List<Circle> cannot be used as an argument to this method. Instead we can use:
0892: private static void printList5(List<? extends Shape> pList) 0893: { 0894: for (Shape tShape : pList) 0895: { 0896: System.out.println("X is " + tShape.getX()); 0897: } 0898: }This can be used with an object of a class that implements List<Shape>, an object of a class that implements List<Circle>, and so on.
Besides parameterized interface types and parameterized class types, Java 5 also permits parameterized methods. So the last two examples can be rewritten as:
0899: private static <GType> void printList6(List<GType> pList) 0900: { 0901: for (GType tGType : pList) 0902: { 0903: System.out.println(tGType); 0904: } 0905: } 0906: private static <GShape extends Shape> void printList7(List<GShape> pList) 0907: { 0908: for (GShape tGShape : pList) 0909: { 0910: System.out.println("X is " + tGShape.getX()); 0911: } 0912: }
Besides using the parameterized types that are in the APIs, we could define our own parameterized type. Suppose we want a collection object that remembers seven things: as soon as you add more than seven items, it forgets about something that has already been stored. Below there is a class called LimitedMemory that can be used to represent such an object.
It is assumed that all the objects that are to be stored in a LimitedMemory object are all of the same type. For this reason, it is written as a parameterized class type. Rather than use E, I have chosen to use the name GType.
One other thing: it is also assumed that each object has a value, and so each object is of a class that implements the Valuable interface. The code below introduces one type that meets these constraints; it is the type Name.
0914: public interface Valuable // Valuable.java 0915: { 0916: public int value(); 0917: }
0918: public class Name implements Valuable // Name.java 0919: { 0920: private String iString; 0921: public Name(String pString) 0922: { 0923: iString = pString; 0924: } 0925: public String toString() 0926: { 0927: return iString; 0928: } 0929: public int value() 0930: { 0931: return iString.length(); 0932: } 0933: }
0934: import java.util.ArrayList; // LimitedMemory.java 0935: import java.util.Iterator; 0936: import java.util.Random; 0937: public class LimitedMemory <GType extends Valuable> 0938: implements Iterable<GType> 0939: { 0940: private static final int iCapacity = 7; 0941: private ArrayList<GType> iArrayList; 0942: private Random iRandom; 0943: public LimitedMemory() 0944: { 0945: iArrayList = new ArrayList<GType>(iCapacity); 0946: iRandom = new Random(); 0947: } 0948: public void add(GType pGType) 0949: { 0950: if (iArrayList.size()<iCapacity) 0951: iArrayList.add(pGType); 0952: else 0953: iArrayList.set(iRandom.nextInt(iCapacity), pGType); 0954: } 0955: public String toString() 0956: { 0957: return iArrayList.toString(); 0958: } 0959: public int value() 0960: { 0961: int tSum = 0; 0962: for (GType tGType : iArrayList) 0963: { 0964: tSum += tGType.value(); 0965: } 0966: return tSum; 0967: } 0968: public Iterator<GType> iterator() 0969: { 0970: return iArrayList.iterator(); 0971: } 0972: }
Here are two fragments of code that use a LimitedMemory object:
0978: LimitedMemory<Name> tLimitedMemory = new LimitedMemory<Name>(); 0979: tLimitedMemory.add(new Name("jim")); 0980: tLimitedMemory.add(new Name("bert"));
1031: iMyPrintln(tLimitedMemory); 1032: System.out.println(" " + tLimitedMemory.value()); 1033: LimitedMemory<Name> tLimitedMemory2 = new LimitedMemory<Name>(); 1034: tLimitedMemory2.add(new Name("jim")); 1035: tLimitedMemory2.add(new Name("bert")); 1036: tLimitedMemory2.add(new Name("jill")); 1037: System.out.println(iBiggestCost(tLimitedMemory, tLimitedMemory2));
The above code uses the following subsidiary methods:
1039: private static void iMyPrintln(LimitedMemory<Name> pLimitedMemory) 1040: { 1041: System.out.print("+"); 1042: for (Name tName : pLimitedMemory) 1043: { 1044: System.out.print(tName + "+"); 1045: } 1046: System.out.println(); 1047: } 1048: private static 1049: <GType1 extends Valuable, GType2 extends Valuable> 1050: int iBiggestCost( 1051: LimitedMemory<GType1> pLimitedMemory1, 1052: LimitedMemory<GType2> pLimitedMemory2) 1053: { 1054: return Math.max(pLimitedMemory1.value(), pLimitedMemory2.value()); 1055: }