150 likes | 298 Views
Java Generics. COMP204 Bernhard Pfahringer (with input from Robi Malik). Generic types for collections. Old Java (1.4 and older): List strings = new ArrayList(); strings.add(“hello”); String word = (String) strings.get(0); New (since 1.5): List<String> strings = new ArrayList<String>();
E N D
Java Generics COMP204 Bernhard Pfahringer (with input from Robi Malik)
Generic types for collections • Old Java (1.4 and older): List strings = new ArrayList(); strings.add(“hello”); String word = (String) strings.get(0); • New (since 1.5): List<String> strings = new ArrayList<String>(); strings.add(“hello”); String word = strings.get(0);
Advantages • Better readability • Better type-safety: no casts (runtime checks), compiler can already catch problems
Writing your own generic code public class Stack<E> { public void push(E element) { contents.add(element); } public E pop() { int top = contents.size()-1; E result = contents.get(top); contents.remove(top); return result; } private List<E> contents = new ArrayList<E>(); }
Formal type parameter public class Stack<E> { … } • convention: Short (single-char) uppercase • can be used wherever a Type is needed • will be replaced with actual Type
Problems with sub-types class Student extends Person { .. } List<Student> students = new ArrayList<Student>(); List<Person> people = students; // should this be possible? -> no
No, because Person sam = new Person(); people.add(sam); // if this was legal, we would have just sneaked a non-student onto the students list on the other hand, how do you write generic code then accepting lists of sub-types of Persons ???
Wildcards void printCollection(Collection<?> c) { for(Object o: c) { System.out.println(o); } } // only read access (everything is an Object), but cannot add, because do not know correct type (except null, which is any type)
Bounded wildcards public void drawAll(Collection<? extends Shape> c) { for(Shape shape: c) { shape.draw(); } } // again, only read access, allows collections of Shape or any sub type of Shape