Java Reference
In-Depth Information
In Java 7, the compiler attempts to infer the type in the object creation expression, new ArrayList<>() . The
expression does not have any constructor argument. It does not include a left-hand side expression. Therefore, the
compiler uses the fourth step in its inference process. It infers the type as Object . It replaces the call to the process()
method by the following call, which results in the argument type mismatch for the method call. Note that the compiler
does not look at the method's signature ( process() method in your case) to infer the type in the object-creation
expression.
process(new ArrayList<Object>());
In Java 8, the compiler looks at the type of the formal parameter of the process() method and it finds
List<String> and it infers the type as String .
Using the diamond operator saves some typing. Use it when the type inference is obvious. however, it is better,
for readability, to specify the type, instead of the diamond operator, in a complex object-creation expression. always
prefer readability over brevity.
Tip
No Generic Exception Classes
Exceptions are thrown at runtime. The compiler cannot ensure the type-safety of exceptions at runtime if you use a
generic exception class in a catch clause to catch an exception, because the erasure process erases the mention of
any type parameter during compilation. This is the reason that it is a compile-time error to attempt to define a generic
class, which is a direct or indirect subclass of java.lang.Throwable .
No Generic Anonymous Classes
An anonymous class is a one-time class. You need a class name to specify the actual type parameter. An anonymous
class does not have a name. Therefore, you cannot have a generic anonymous class. However, you can have generic
methods inside an anonymous class. Your anonymous class can inherit a generic class. An anonymous class can
implement a generic interface. Any class, except an exception type, enums, and anonymous inner classes, can have
type parameters.
Generics and Arrays
Let's look at the following code for a class called GenericArrayTest :
public class GenericArrayTest<T> {
private T[] elements;
public GenericArrayTest(int howMany) {
elements = new T[howMany]; // A compile-time error
}
// More code goes here
}
 
 
Search WWH ::




Custom Search