






Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
An introduction to generic programming in java, focusing on inheritance and type variables as means to define constructs that can be used with different data types. The implementation of generic programming through examples of inheritance and type variables, as well as the rules for defining and using generic classes and arrays. It also discusses the concept of subtyping in the context of generics and the use of wildcards.
Typology: Study notes
1 / 10
This page cannot be seen from the preview
Don't miss anything!







Append type variable(s) to class name Use angle brackets ClassName Can use any name for type variable But typically single uppercase letter E, K, V, etc… Use the type variable to define Type of variables Type of method parameters Method return type Object allocation Arrays Type of an array object may not be a type variable or a parameterized type, unless it is an unbounded wildcard type How to define arrays? T[] data = (T[]) new Object [size];
In general if B is a subtype of A, and GT is a generic type declaration it is not the case that GT is a subtype of GT Example ArrayList strL = new ArrayList(); ArrayList objL = strL; // Illegal!
8
class A { … } class B extends A { … } // B is subtype of A List bL = new ArrayList(); List aL = bL; aL.add(new A()); B b = bL.get(0); // runtime exception
ArrayList sL = new ArrayList(); ArrayList oL = sL ; // Illegal, but let’s assume is valid oL.add(new Integer(10)); String entry = sL.get(0); // Problem!!
? (unknown) Collection Collection whose element type matches anything Bounded Wildcard Example: ArrayList Unknown type that is Shape or subtype of Shape Summary unknown type unknown type that is typeExpression or a subtype of typeExpression unknown type that is typeExpression or a supertype of typeExpression. typeExpression can involve further occurrences of wildcard type expressions Example (WildCard class in code distribution)