Presentation is loading. Please wait.

Presentation is loading. Please wait.

Generic types for ArrayList Old Java (1.4 and older): ArrayList strings = new ArrayList(); strings.enqueue(“hello”); String word = (String) strings.get(0);

Similar presentations


Presentation on theme: "Generic types for ArrayList Old Java (1.4 and older): ArrayList strings = new ArrayList(); strings.enqueue(“hello”); String word = (String) strings.get(0);"— Presentation transcript:

1 Generic types for ArrayList Old Java (1.4 and older): ArrayList strings = new ArrayList(); strings.enqueue(“hello”); String word = (String) strings.get(0); New (since 1.5): ArrayList strings = new ArrayList (); strings.add(“hello”); String word = strings.get(0);

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

3 Writing your own generic code Formal type parameter public class Stack { … } –convention: Short (single-char) uppercase –can be used wherever a Type is needed –will be replaced with actual Type

4 Writing your own generic code public class Stack { 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 ArrayList contents = new ArrayList (); }

5 Problems with sub-types class Student extends Person {.. } Stack students = new Stack (); Stack people = students; // should this be possible?

6 No, because Person sam = new Person(); people.push(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 to accept stacks of sub-types of Person?

7 Comparable’s compareTo() Java 1.4 –Interface Comparable int compareTo(Object o) Java 1.5 –Interface Comparable int compareTo(T o)

8 Wildcards void printArrayList(ArrayList al) { for(Object o: al) { 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 c) { for(Shape shape: c) { shape.draw(); } // again, only read access, allows collections of Shape or any sub type of Shape


Download ppt "Generic types for ArrayList Old Java (1.4 and older): ArrayList strings = new ArrayList(); strings.enqueue(“hello”); String word = (String) strings.get(0);"

Similar presentations


Ads by Google