Java 1.5Versions of JavaReason for changesNew featuresNew methods in java.util.ArraysGenericsGeneric IteratorsWriting generic methodsType wildcardsWriting your own generic typesNew for statementAuto boxing and unboxingEnumerationsenums are classesAdvantages of the new enumEnums really are classesOther features of enumsvarargsStatic import facilityjava.util.Scannerjava.util.FormatterAdditional featuresClosing commentsThe EndJan 13, 2019Java 1.52Versions of JavaJava 1Java 2Java 5.0Oak: Designed for embedded devicesJava 1.1: Adds inner classes and a completely new event-handling modelJava 1.2: Includes “Swing” but no new syntaxJava 1.3: Additional methods and packages, but no new syntaxJava 1.4: More additions and the assert statementJava 1.5: Generics, enums, new for loop, and other new syntaxJava: Original, not very good version (but it had applets)3Reason for changes“The new language features all have one thing in common: they take some common idiom and provide linguistic support for it. In other words, they shift the responsibility for writing the boilerplate code from the programmer to the compiler.” --Joshua Bloch, senior staff engineer, Sun Microsystems4New featuresGenericsCompile-time type safety for collections without castingEnhanced for loopSyntactic sugar to support the Iterator interfaceAutoboxing/unboxingAutomatic wrapping and unwrapping of primitivesTypesafe enumsProvides all the well-known benefits of the Typesafe Enum patternStatic importLets you avoid qualifying static members with class namesScanner and FormatterFinally, simplified input and formatted output5New methods in java.util.ArraysJava now has convenient methods for printing arrays:Arrays.toString(myArray) for 1-dimensional arraysArrays.deepToString(myArray) for multidimensional arraysJava now has convenient methods for comparing arrays:Arrays.equals(myArray, myOtherArray) for 1-dimensional arraysArrays.deepEquals(myArray, myOtherArray) for multidimensional arraysIt is important to note that these methods do not override the public String toString() and public boolean equals(Object) instance methods inherited from ObjectThe new methods are static methods of the java.util.Arrays class6GenericsA generic is a method that is recompiled with different types as the need arisesThe bad news:Instead of saying: List words = new ArrayList();You'll have to say: List<String> words = new ArrayList<String>();The good news:Replaces runtime type checks with compile-time checksNo casting; instead of String title = (String) words.get(i);you use String title = words.get(i);Some classes and interfaces that have been “genericized” are: Vector, ArrayList, LinkedList, Hashtable, HashMap, Stack, Queue, PriorityQueue, Dictionary, TreeMap and TreeSet7Generic IteratorsTo iterate over generic collections, it’s a good idea to use a generic iteratorList<String> listOfStrings = new LinkedList<String>();...for (Iterator<String> i = listOfStrings.iterator(); i.hasNext(); ) { String s = i.next(); System.out.println(s);}8Writing generic methodsprivate void printListOfStrings(List<String> list) { for (Iterator<String> i = list.iterator(); i.hasNext(); ) { System.out.println(i.next()); }}This method should be called with a parameter of type List<String>, but it can be called with a parameter of type ListThe disadvantage is that the compiler won’t catch errors; instead, errors will cause a ClassCastExceptionThis is necessary for backward compatibilitySimilarly, the Iterator need not be an Iterator<String>9Type wildcardsHere’s a simple (no generics) method to print out any list:private void printList(List list) { for (Iterator i = list.iterator(); i.hasNext(); ) { System.out.println(i.next()); }}The above still works in Java 1.5, but now it generates warning messagesJava 1.5 incorporates lint (like C lint) to look for possible problemsYou should eliminate all errors and warnings in your final code, so you need to tell Java that any type is acceptable:private void printListOfStrings(List<?> list) { for (Iterator<?> i = list.iterator(); i.hasNext(); ) { System.out.println(i.next()); }}10Writing your own generic typespublic class Box<T> { private List<T> contents; public Box() { contents = new ArrayList<T>(); } public void add(T thing) { contents.add(thing); } public T grab() { if (contents.size() > 0) return contents.remove(0); else return null;}Sun’s recommendation is to use single capital letters (such as T) for typesMany people, including myself, don’t think much of this recommendation11New for statementThe syntax of the new statement is for(type var : array) {...}or for(type var : collection) {...}Example: for(float x : myRealArray) { myRealSum += x; }For a collection class that has an Iterator, instead of for (Iterator iter = c.iterator(); iter.hasNext(); ) ((TimerTask) iter.next()).cancel();you can now say for (TimerTask task : c) task.cancel();12Auto boxing and unboxingJava won’t let you use a primitive value where an object is required--you need a “wrapper”myVector.add(new Integer(5));Similarly, you can’t use an object where a primitive is required--you need to “unwrap” itint n = ((Integer)myVector.lastElement()).intValue();Java 1.5 makes this automatic:Vector<Integer> myVector = new Vector<Integer>();myVector.add(5);int n = myVector.lastElement();Other extensions make this as transparent as possibleFor example, control statements that previously required a boolean (if, while, do-while) can now take a BooleanThere are some subtle issues with equality tests, though13EnumerationsAn enumeration, or “enum,” is simply a set of constants to represent various valuesHere’s the old way of doing itpublic final int SPRING = 0;public final int SUMMER = 1;public final int FALL = 2;public final int WINTER = 3;This is a nuisance, and is error prone as wellHere’s the new way of doing it:enum Season { WINTER, SPRING, SUMMER, FALL }14enums are classesAn enum is actually a new type of classYou can declare them as inner classes or outer classesYou can declare variables of an enum type and get type safety and compile time checkingEach declared value is an instance
View Full Document