Paco Kwon
Paco Kwon

Reputation: 27

Java: Different Generic type declaration and instance

I see that you have to use a generic form both when declaring the variable and assigning the instance. The question I want to ask is this: Is there any case the type of variable and instance can be different? Like

List<Object> list = new ArrayList<Integer>();

Upvotes: 1

Views: 70

Answers (1)

Thilo
Thilo

Reputation: 262534

First of all, you can use the diamond operator to infer the type on the right:

List<Object> list = new ArrayList<>();

Is there any case the type of variable and instance can be different?

Generic types in Java are erased at runtime. That means that the instance has no generic type. The type only exists at compile-time, on the variable.

The generic types on the left and the right do not have to be exactly the same, but then you have to use wild-cards:

List<?> list = new ArrayList<Integer>();
List<? extends Number> list = new ArrayList<Integer>();

With these wild-cards, you are then quite limited in what you can still do with the objects. For example, you can only get a Number out of a List<? extends Number>, but you cannot add a new Integer to it (because it might have been a List<Double> for all you know).

This is still useful if you want to write methods that can accept lists of some interface type:

boolean areAllPositive(List<? extends Number> numbers) { ... }

Upvotes: 1

Related Questions