GenericsArrays and collectionsMaking a collection type safeGenerics for type safety in Java 5What generics are and aren’tGenerics in CIT594Using an existing collectionMethods with genericsBad newsWriting your own generic classesIteratorsThe “enhanced for loop”Subclassing a generic classSummaryThe EndJan 13, 2019GenericsArrays and collectionsIn Java, array elements must all be of the same type:int[] counts = new int[10];String[] names = { "Tom", "Dick", "Harry" };Hence, arrays are type safe: The compiler will not let you put the wrong kind of thing into an arrayA collection, such as a Vector or ArrayList, cannot hold primitives, but will accept any type of Object:Stack someStuff = new Stack();someStuff.push("A String is an Object");someStuff.push(Color.BLUE);We can make an array that, like a collection, holds any Objects:Object[ ] whatever = new Object[100];Prior to Java 5, there was no easy way to make a collection type safeMaking a collection type safeHere’s how to create a type-safe Stack that holds only Strings (in Java 1.4 and earlier):class StackOfStrings { private Stack internalStack = new Stack(); public boolean isEmpty() { return internalStack.isEmpty(); } public String push(String s) { internalStack.push(s); return s; } public String pop() { return (String)internalStack.pop(); } etc.Generics for type safety in Java 5In Java 5, you can easily make any collection type safeFor example, you can create a Stack that holds only Strings as follows:Stack<String> names = new Stack<String>();You can write methods that require a type-safe collection as follows:void printNames(Stack<String> names) {String nextName = names.pop(); // no casting needed!names.push("Hello"); // works just the same as beforenames.push(Color.RED); // compile-time error!What generics are and aren’tYou can almost think of generics as defining new types--for example a Stack<String> is a stack of stringsIn Java 1.4,String s = myStack.pop(); will not compileString s = (String)myStack.pop(); compiles, with runtime checkmyStack.push(Color.RED); compiles with no complaint In Java 5, String s = myStack.pop(); Compiles with no runtime check if myStack was declared as Stack<String>Does not compile if myStack was declared any other waymyStack.push(Color.RED); is a compiler error (= syntax error)However, generics are instructions to the compiler only You can still say: if (thing instanceof Stack) ...but you cannot say: if (thing instanceof Stack<String>) ...This is called erasure--the type information is “erased” at runtimeGenerics in CIT594Generics are important in studying data structures because:We make heavy use of Sun’s collections, all of which have been genericized, so we need to know how to use themHowever, non-genericized collections continue to workGenericized collections include: LinkedList, ArrayList, Vector, HashSet, TreeSet, Stack, HashMap, TreeMap, PriorityQueue, and othersWhen we create new data structures,In Java 5, it is almost always a good idea to genericize themHowever, Java 5 programs will only work for users who have upgraded their Java systems--so we may wish to compile for older versionsGenerics are not important in data structures because:Generics are only a convenient way to get type safetyThe data structures themselves have not changed in any wayUsing an existing collectionCreation:Stack plainStack = new Stack(); // the old wayStack s1 = new Stack<Integer>(); // s1 is still just a plain stackStack<Integer> integerStack = new Stack<Integer>(); // correctStack<Integer> s2 = new Stack(); // works with a warningAssignments:plainStack = integerStack; // no problem with thisintegerStack = plainStack; // works but is not type safeUse of integerStack:integerStack.push(new Integer(5));Integer xxx = integerStack.pop(); // no cast necessaryintegerStack.push(5); // works, because of autoboxingint x =integerStack.pop(); // works, because of auto unboxingMethods with genericsprivate static void fiddle(Stack<Integer> ints) { ints.push(5); }fiddle(integerStack); // good callfiddle(plainStack); // legal but not type safefiddle(new Stack<String>()); // not legalstatic Stack<Integer> myMethod(Stack<Integer> stk) { Stack<Integer> result = new Stack<Integer>(); return result;}Stack<Integer> newStack = myMethod(integerStack); // good callStack<Integer> newStack1 = myMethod(plainStack); // not safeBad newsType safe? Only sort of...Stack<Integer> stack1 = new Stack<Integer>();Stack stack2 = stack1; // stack2 is alias of stack1stack2.push(Color.RED);// legal--stack2 is a plain stackInteger xxx = stack1.pop(); // ClassCastException!A little more explanation...Java 5 is upwardly compatible with Java 1.4--that is, old programs must continue to workHence you can have non-generic stacks (and stack assignment)When you use a generic collection, you should make it generic everywhere, not just in the places that Java would otherwise report an errorEclipse will provide warnings for many unsafe cases, so pay close attention to those warnings!Writing your own generic classespublic class MyClass<T> { T value; // in this class, use T just like any other type public MyClass(T value) this.value = value; } public void print(T anotherValue) { System.out.println(value + " " + anotherValue); }}IteratorsAn iterator gives you every element of a collection, one at a timeThe collection has a type iterator(); factory method to return a new iterator to return objects of the given typeThe method boolean hasNext() tells you if there are more objectsThe method type next() returns the next objectThe method void remove() deletes the last object gottenExample:Iterator iter = integerStack.iterator();while (iter.hasNext()) { System.out.println(iter.next());}The “enhanced for loop”Java 5’s new for loop does the iterator work for youfor (int n : integerStack) { System.out.println(n);}is the same (except for the int declaration) asIterator iter = integerStack.iterator();while (iter.hasNext()) { System.out.println(iter.next());}The enhanced for loop can also be used for arrays, and for any class you write that implements the Iterator interfaceThe enhanced for loop is convenient but less powerful than the old-style for loop, since it just
View Full Document