3. 12/5/19
Introduction to Genetics
Generics was added in Java 5 to provide compile-time type checking and
removing risk of ClassCastException that was common while working with
collection classes.
3
List list = new ArrayList();
list.add("abc");
list.add(new Integer(10));
for(Object obj : list){
String str=(String) obj;
}
Before Java 5
List<String> list1 = new ArrayList<String>();
// java 7 ? List<String> list1 = new ArrayList<>();
list1.add("abc");
//list1.add(new Integer(10)); //compiler error
for(String str : list1){
String s = str;
}
After Java 5
4. 12/5/19
Type erasure
Regarding generics, this means that parameterized types are not stored in the
Bytecode.
4
List objects = new ArrayList();
List<String> strings = new ArrayList<String>();
List<Long> longs = new ArrayList<Long>();
Code:
0: new #2 // class java/util/ArrayList
3: dup
4: invokespecial #3 // Method java/util/ArrayList."<init>":()V
7: astore_1
8: new #2 // class java/util/ArrayList
11: dup
12: invokespecial #3 // Method java/util/ArrayList."<init>":()V
15: astore_2
16: new #2 // class java/util/ArrayList
19: dup
20: invokespecial #3 // Method java/util/ArrayList."<init>":()V
23: astore_3
24: return
5. 12/5/19
Java-Bridge Method
Sometimes, the compiler will need to add a bridge method to a class to handle
situations in which the type erasure of an overriding method in a subclass does
not produce the same erasure as the method in the superclass.
5
class Bridge<T>
{
T t1;
Bridge(T t) {
t1 = t;
}
T getT() {
return t1;
}
}
class BridgeGen extends Bridge<Integer>
{
BridgeGen(Integer i) {
super(i);
}
Integer getT() {
return t1;
}
}
class Bridge
{
Object t1;
Bridge(Object t) {
t1 = t;
}
Object getT() {
return t1;
}
}
class BridgeGen extends Bridge
{
BridgeGen(Integer i) {
super(i);
}
Integer getT() {
return (Integer)t1;
}
Object getT() {
return getT();
}
}
6. 12/5/19
How to use Generics
1. Generic Class
A generic class is defined with the following format:
The type parameter section, delimited by angle brackets (<>), follows the class name. It specifies the
type parameters (also called type variables) T1, T2, ..., and Tn.
2. Generic Interface
●
type-param-list is a comma-separated list of type parameters.
●
when a generic interface is implemented, you must specify the type arguments
6
class name<T1, T2, ..., Tn> { /* ... */ }
interface interfaceName<type-param-list> { // ...
}
class className<type-param-list> implements interfaceName<type-param-list> {
// ....
}
7. 12/5/19
How to use Generics
3.Generic Method
The syntax for a generic method includes a list of type parameters, inside angle brackets, which
appears before the method's return type.
4. Generics Multiple Type Parameters
7
<type-Parameters> return_type method_name(parameter list)
{
// ..
}
public interface Map<K, V> {
...
}
8. 12/5/19
Benefits of Generic
1. Stronger type checks at compile time:
- A Java compiler applies strong type checking to generic code and issues errors if the code
violates type safety.
- Fixing compile-time errors is easier than fixing runtime errors, which can be difficult to find.
8
List<String> list = new ArrayList<String>();
list.add("Bulgaria");
List holds only a String type of objects in generics.
It doesn’t allow to store other objects
2. Elimination of casts
List list = new ArrayList();
list.add("Bulgaria");
String s = (String) list.get(0);
List<String> list = new ArrayList<String>();
list.add("Bulgaria");
String s = list.get(0); // no cast
9. 12/5/19
Bounded Types
There may be times when you want to restrict the types that can be used as
type arguments in a parameterized type
9
<T extends SuperClass>
This specifies that ‘T’ can only be replaced by ‘SuperClass’ or it subclasses.
Remember that extends clause is an inclusive bound. That means bound
includes ‘SuperClass’ also.
The type parameter can have multiple bounds:
<T extends B1 & B2 & B3>
10. 12/5/19
Java Generics PECS
What is Wildcard?
The question mark (?), called the wildcard, represents an unknown type. The
wildcard is never used as a type argument for a generic method invocation, a
generic class instance creation, or a supertype.
10
boolean addAll(Collection<? extends E> c);
https://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/util/Collections.java#l2104
public static <T> boolean addAll(Collection<? super T> c, T... elements);
https://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/util/Collections.java#l5457
11. 12/5/19
Java Generics PECS
1. Upper Bounded Wildcards
This is the first part of PECS i.e. PE (Producer extends).
11
GenericType<? extends SuperClass>
2. Lower Bounded Wildcards
GenericType<? super SubClass>
This is the second part of PECS i.e. PE (Consumer extends).
12. 12/5/19
Java Generics PECS
Summary
1. Use the <? extends T> wildcard if you need to retrieve object of type T from a
collection.
2. Use the <? super T> wildcard if you need to put objects of type T in a
collection.
3. If you need to satisfy both things, well, don’t use any wildcard. As simple as it
is.
4. In short, remember the term PECS. Producer extends Consumer super.
Really easy to remember.
12
13. 12/5/19
Questions
1. There is a girl named Maria. She loves books and she has many books.
Create a liberally application that will manege will the all books. There are
different types of books. You have to create appropriate generic interface,
classes and methods.
2. Create school application:
- managing students(insert, delete and update)
-managing teachers(insert, delete and update)
You have to write above tasks within good practices. Make your code easy for
extend and generic.
13