Restrictions on Generics :





Cannot Instantiate Generic Types with Primitive Types:

Consider the following parameterized type:
class Pair<K, V> {
private K key;
private V value;
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
// ...
}



Pair<int, char> p = new Pair<>(8, 'a'); // compile-time error
Pair<Integer, Character> p = new Pair<>(8, 'a');
Pair<Integer, Character> p = new Pair<>(Integer.valueOf(8), new Character('a'));
When creating a Pair object, you cannot subsitute a primitive type for the type parameter K or V:
You can substitute only non-primitive types for the type parameters K and V:
Note that the Java compiler autoboxes 8 to Integer.valueOf(8) and 'a' to Character('a').







Cannot Declare Static Fields Whose Types are Type Parameters

public class MobileDevice<T> {

private static T os;

// ...
}
MobileDevice<Smartphone> phone = new MobileDevice<>();
MobileDevice<Pager> pager = new MobileDevice<>();
MobileDevice<TabletPC> pc = new MobileDevice<>();


A class's static field is a class-level variable shared by all non-static objects of the class. Hence, static fields of type parameters are not allowed. Consider the following class:
If static fields of type parameters were allowed, then the following code would be confused:
Because the static field os is shared by phonepager, and pc, what is the actual type of os? It cannot be SmartphonePager, and TabletPC at the same time. You cannot, therefore, create static fields of type parameters.






Cannot Create Arrays of Parameterized Types:

You cannot create arrays of parameterized types. For example, the following code does not compile:
List<Integer>[] arrayOfLists = new List<Integer>[2];  // compile-time error





Cannot Create, Catch, or Throw Objects of Parameterized Types :

A generic class cannot extend the Throwable class directly or indirectly. For example, the following classes will not compile:
// Extends Throwable indirectly
class MathException<T> extends Exception { /* ... */ }    // compile-time error

// Extends Throwable directly
class QueueFullException<T> extends Throwable { /* ... */ // compile-time error

A method cannot catch an instance of a type parameter:




public static <T extends Exception, J> void execute(List<J> jobs) {
    try {
        for (J job : jobs)
            // ...
    } catch (T e) {   // compile-time error
        // ...
    }
}


You can, however, use a type parameter in a throws clause:
class Parser<T extends Exception> {
    public void parse(File file) throws T {     // OK
        // ...
    }
}











0 comments:

Post a Comment

 
Copyright (c) 2013 Java Discovery.