Java Generics - 8. Target Types
This is part 8 of the 9 part series on Java Generics
Prev Topic
|
Topics
1. Introduction
2. Bounding
8. Target Types
|
|
Java Generics - Target Types
As per java specification – A target type of an expression
is the data type that the compiler expects when it is being used. Consider the
method createList in the class TypeInference below, that creates the list of 2
elements which are passed in its parameter.
public class TypeInference {
public static <E> List<E>
createList(E e1, E e2){
List<E>
list = new ArrayList<>();
list.add(e1);
list.add(e2);
return list;
}
public static <E> List<E>
newList(){
return new ArrayList<>();
}
}
|
We can pass any type of parameter here, they could be
Integer or maybe String. In this case the compiler understands what we are
trying to infer. The compiler understands that you are trying to create the
list of String for the first variable, and a list of Integer
for the second one.
List<String> strList1
= TypeInference.createList("Hello", "World");
List<Integer>
intList1 =
TypeInference.createList(1, 2); //
auto-boxing
|
This saves you the pain of declaring the type at the right
side. Consider the code below. In fact this strange looking code is valid and
will compile well. Notice the type declaration within the diamond in the code
below.
List<String> strList2
= TypeInference.<String>createList("Hello", "World");
List<Integer>
intList2 =
TypeInference.<Integer>createList(1, 2);
|
Similarly when using the method newList( ), you needn’t
declare the type while using it. The compiler would infer it to the correct
type.
List<String> sList1 = TypeInference.newList();
List<String>
sList2 =
TypeInference.<String>newList();
|
The compiler not only infers the assignment but also the
method parameters (from Java 8 onwards). Go ahead and try it yourself. Java has
made things simpler for you.
Prev Topic
|
Topics
1. Introduction
2. Bounding
8. Target Types
9. Type Erasure
|
|
Comments
Post a Comment