L17cs211sp07-6up - Generic Types in Java 5 Generic Types...

Info icon This preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
Generic Types and the Java Collections Framework Lecture 17 CS211 – Spring 2007 2 Generic Types in Java 5 y When using a collection (e.g., LinkedList , HashSet , HashMap ), we generally have a single type T of elements that we store in it (e.g., Integer, String ) y Before 1.5, when extracting an element, had to cast it to T before we could invoke T's methods y Compiler could not check that the cast was correct at compile-time , since it didn't know what T was y Inconvenient and unsafe, could fail at runtime y Generics in Java 1.5 provide a way to communicate T, the type of elements in a collection, to the compiler Compiler can check that you have used the collection consistently Result: safer and more-efficient code 3 Example //removes 4-letter words from c //elements must be Strings static void purge(Collection c) { Iterator i = c.iterator(); while (i.hasNext()) { if (( (String) i.next()).length() == 4) i.remove(); }} //removes 4-letter words from c static void purge(Collection <String> c) { Iterator <String> i = c.iterator(); while (i.hasNext()) { if (i.next().length() == 4) i.remove(); }} old new 4 Another Example Map grades = new HashMap(); grades.put("John",new Integer(67)); grades.put("Jane",new Integer(88)); grades.put("Fred",new Integer(72)); Integer x = (Integer) grades.get("John"); sum = sum + x.intValue(); Map <String,Integer> grades = new HashMap <String,Integer> (); grades.put("John",new Integer(67)); grades.put("Jane",new Integer(88)); grades.put("Fred",new Integer(72)); Integer x = grades.get("John"); sum = sum + x.intValue(); old new 5 Type Casting y In effect, Java inserts the correct cast automatically, based on the declared type y In this example, grades.get("John") is automatically cast to Integer Map <String,Integer> grades = new HashMap <String,Integer> (); grades.put("John",new Integer(67)); grades.put("Jane",new Integer(88)); grades.put("Fred",new Integer(72)); Integer x = grades.get("John"); sum = sum + x.intValue(); 6 An Aside: Autoboxing y Java 5 also has autoboxing and auto-unboxing of primitive types, so the example can be further simplified Map <String,Integer> grades = new HashMap <String,Integer> (); grades.put("John",new Integer(67)); grades.put("Jane",new Integer(88)); grades.put("Fred",new Integer(72)); Integer x = grades.get("John"); sum = sum + x.intValue()); Map <String,Integer> grades = new HashMap <String,Integer> (); grades.put("John", 67); grades.put("Jane", 88); grades.put("Fred", 72); sum = sum + grades.get("John");
Image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon