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>();
1

1 Answer 1

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) { ... }
Sign up to request clarification or add additional context in comments.

2 Comments

Can you explain more about wild cards in generics or provide a useful link that I can refer to?
Maybe start with the official tutorial: docs.oracle.com/javase/tutorial/java/generics/wildcards.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.