Java Generics - PowerPoint PPT Presentation

About This Presentation
Title:

Java Generics

Description:

... (E element) { contents.add(element); public E ... Problems with sub-types. class ... only read access, allows collections of Shape or any sub type of Shape ... – PowerPoint PPT presentation

Number of Views:24
Avg rating:3.0/5.0
Slides: 10
Provided by: csscmswaik
Category:

less

Transcript and Presenter's Notes

Title: Java Generics


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)
  • ListltStringgt strings new ArrayListltStringgt()
  • 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 StackltEgt
  • 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 ListltEgt contents new ArrayListltEgt()

5
Formal type parameter
  • public class StackltEgt
  • 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 ..
  • ListltStudentgt students new ArrayListltStudentgt()
  • ListltPersongt people students
  • // should this be possible? -gt 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(Collectionlt?gt 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(Collectionlt? extends Shapegt
    c)
  • for(Shape shape c)
  • shape.draw()
  • // again, only read access, allows collections of
    Shape or any sub type of Shape
Write a Comment
User Comments (0)
About PowerShow.com