Lecture 8A Flashcards
A generic class name should always be noted together with…
…the ie MyClass
Java compiler can show you error with generics, when?
Before runtime.
What are benefits of using generics?
Increase type safety. Avoid type casts and code duplication. Also many runtime errors become compile time errors, checked statically.
What are type bounds?
They restrict range of type parameters. Ie class myGen… This means any type T must extend OR implement type Sup.
What is type erasure?
When the Java compiler translates generics into ordinary code after type checking.
In generics what is a wildcard?
? Is a wildcard. Used in generics in methods: void myMethod(MyGenericClass> arg)
It stands for unknown type.
Can also use bounds: extends, super. Can also be used for return values.
What is convariance?
Convariant arrays would be where Employee is a subclass of Person, Person[] array = new Employee[5]
Why are Java generics not convariant?
To avoid runtime issues, ie Person[] array = new Emp[5]; array[0] = new Student(); compiles fine but error at runtime.
Java generics are invariant?
Yes, ArrayList is NOT a subclass of ArrayList.
What are generic static methods?
They use the static keyword and type parameters (not the wildcard ?): static void methodName(T[ ] a, Collection c){…}
How can generic static methods be used?
Regardless of whether the class in which it’s declared is generic. Also, when a generic method is used it is NOT required to provide a concrete type for type parameter.
What is the type parameter? And type argument? And type variable?
class MyClass {}
When making object from class: MyClass myO = new MyClass(); String here is type argument. Inside class typeparameter is a type variable.