lecture13

lecture13 - PIC 20A Lecture 13 Generics What is"Generics...

Info iconThis preview shows pages 1–7. Sign up to view the full content.

View Full Document Right Arrow Icon
PIC 20A Lecture 13: Generics
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
What is "Generics"? Generics is • a new capability of Java which allows you to abstract over types • introduced in version 1.5.0 • (Java's answer to C++ templates)
Background image of page 2
What is Generics good for? Generics • forces compile-time type checking (for example, of container data) • avoids run-time logic errors resulting from improper casts (which generate a ClassCastException ) • improves readability • makes code more robust (program crashes less)
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
Motivating Example • Suppose I define a class which holds an Object public class Holder { private Object _data; public void hold(Object o) { _data = o; } public Object release() { Object o = _data; _data = null; return o; } }
Background image of page 4
Motivating Example Continued • Now suppose we use our Holder class public class HolderTest { public static void main(String[] args) { Holder h = new Holder(); h.hold("123456.789"); // later someone else writes legally. .. Double data = (Double) h.release(); System.exit(0); } The Object released by the Holder is not a Double , but a String . This cast results in a run-time ClassCastException which terminates your program.
Background image of page 5

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
If only there was a way to prevent this run-time error at compile time. .. • But wait. ..there is! Make the Holder class generic by introducing a formal type parameter T which you can use anywhere in the class definition as a placeholder for a non-primitive data type to be specified at a Holder object instantiation public class Holder <T> { private T _data; public void hold( T t) { _data = t; } public T release() { T t = _data; _data = null; return t; } }
Background image of page 6
Image of page 7
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

Page1 / 18

lecture13 - PIC 20A Lecture 13 Generics What is"Generics...

This preview shows document pages 1 - 7. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online