1

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>();
Paco Kwon
  • 27
  • 1
  • 7
  • Possible duplicate of [Downcasting in Java](https://stackoverflow.com/questions/380813/downcasting-in-java) – yassadi Apr 15 '18 at 07:11

1 Answers1

1

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) { ... }
Thilo
  • 257,207
  • 101
  • 511
  • 656
  • Can you explain more about wild cards in generics or provide a useful link that I can refer to? – Paco Kwon Apr 16 '18 at 02:27
  • Maybe start with the official tutorial: https://docs.oracle.com/javase/tutorial/java/generics/wildcards.html – Thilo Apr 16 '18 at 07:30