Presentation is loading. Please wait.

Presentation is loading. Please wait.

COMP204 Bernhard Pfahringer (with input from Robi Malik)

Similar presentations


Presentation on theme: "COMP204 Bernhard Pfahringer (with input from Robi Malik)"— Presentation transcript:

1 COMP204 Bernhard Pfahringer (with input from Robi Malik)
Java Generics COMP204 Bernhard Pfahringer (with input from Robi Malik)

2 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>(); String word = strings.get(0);

3 Advantages Better readability
Better type-safety: no casts (runtime checks), compiler can already catch problems

4 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>();

5 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

6 Problems with sub-types
class Student extends Person { .. } List<Student> students = new ArrayList<Student>(); List<Person> people = students; // should this be possible? -> no

7 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 ???

8 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)

9 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


Download ppt "COMP204 Bernhard Pfahringer (with input from Robi Malik)"

Similar presentations


Ads by Google