1 / 9

Java Generics

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

shiloh
Download Presentation

Java Generics

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 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>(); strings.add(“hello”); 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

More Related