generics ch14 Flashcards
what is generics
java allows class and method definitions that include parameters for types - these definitions are called generics
Generic programming with a type parameter enables code to be written that applies to any class
copies of arrayList
deep copy is needed - clone method not good enough - it produces a shallow copy
In order to make a deep copy, it must be possible to make a deep copy of objects of the base type
Then a deep copy of each element in the ArrayList can be created and placed into a new ArrayList object
the arraylist class is a parameterized class - what does this mean
It has a parameter, denoted by Base_Type, that can be replaced by any reference type to obtain a class for ArrayLists with the specified base type
class that needs another class as a parameter - is like a cookie cutter class - have type parameters - e.g. type Employee is the parameter
generic constructors
public Class()
A constructor can use the type parameter as the type for a parameter of the constructor, but in this case, the angular brackets are not used public Pair(T first, T second)
instantiated generic class
Pair pair = new Pair(“Happy”, “Day”);
can you use primitive types in generic class parameters
no - The type plugged in for a type parameter must always be a reference type
reference types include arrays
but now that Java has auto boxing - not a big restriction
what are the places where an ordinary class name would be allowed but the type parameter wouldnt be allowed
In particular, the type parameter cannot be used in simple expressions using new to create a new object For instance, the type parameter cannot be used as a constructor name or like a constructor: T object = new T(); T[] a = new T[10];
is the instantiation of a generic class be an array base type?
no
Arrays such as the following are illegal:
Pair[] a = new Pair[10];
generic class with multiple type parameters
TwoTypePair
what are the bounds for type parameters
- may be on a class name rather than an interface name
- Then only descendent classes of the bounding class may be plugged in for the type parameters
public class Two
declaring generic methods
public static T genMethod(T[] a)
invoking generic methods
String s = NonG.genMethod(c);
inheritance with generic classes
Given two classes: A and B, and given G: a generic class, there is no relationship between G<a> and G<b></b></a>
This is true regardless of the relationship between class A and B, e.g., if class B is a subclass of class A </b></a>