Download presentation
Presentation is loading. Please wait.
Published byEmil Carter Modified over 9 years ago
1
CSC 243 – Java Programming, Spring 2013 March 12, 2013 Week 7, Generics
2
Generic Interfaces / Classes We have been using generic interfaces and classes from the library. java.util.Set, java.util.HashSet java.util.Map, java.util.HashMap They allow containers to contain different types (classes) of objects. Generic parameters such as E (element type), K (key type) and V (value type) above are types bound by client code at compile time.
3
Using Generic Classes Client code supplies a binding for each generic parameter that must be an interface or class name. It cannot be a primitive type. A generic parameter may constrain the type of class or interface that client code can bind using a wildcard. ?, ? extends T, ? super T – details follow.
4
Building Generics A class or interface specifies its generic type. HashSet, HashMap, etc. ? extends T is a bounded wildcard, T or a subclass ? super T is a lower-bounded wildcard, T or a superclass ? is an unbounded wildcard, same as ? Extends Object The bound constrains client code type binding. The writer of a generic class must ensure type consistency within the class. The user can safely assume type compatibility if the compiler does not flag an error.
5
Erasure and Restrictions Unlike C++ template classes, the compiler generates only 1 copy of the class code for a generic class, erasing the generic type T information at run time. Every generic type T is treated as a java.lang.Object at run time. Writers of generic classes may need to cast to generic type T, E, K, V etc. in places. Writers of generic classes must ensure that those casts are valid. The compiler cannot ensure this.
6
Restrictions 1. No constructor – no “new T()” for generic T. 2. No “new T[]” – you must cast an “Object []” to a “T []” within the generic class code. This cast often fails at run time with a wildcard T. Make sure to test if you use arrays of wildcard generic types. 3. No generic T in a static field, static method or static initialization block of code. 4. Exception classes cannot be generic.
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.