n00b
n00b

Reputation: 214

What's wrong with the following assignment in Java Generics

I am just starting with Java Generics and the following code does not make any sense to me.

List<? extends Number> lint = new ArrayList<Integer>();
// following throws error
List<Number> lint2 = lint;

[Extra Details]

I know that List<Interger> != List<Number> but what's the use of '?' operator then? I created an arraylist of integers which I passed to some List which can accept lists containing doubles,floats or integers. Why can't I assign this to List. Can all of this be attributed to Strict type safety?

I am using this as a reference: http://docs.oracle.com/javase/tutorial/java/generics/upperBounded.html

Upvotes: 0

Views: 595

Answers (6)

Serge Ballesta
Serge Ballesta

Reputation: 148975

The reason is simple : lint is an ArraysList<Integer> that is lint.add(10) is right, lint.add(2.5) is wrong.

But if Java compiler accepted List<Number> lint2 = lint;, lint2.add(2.5) should be acceptable because 2.5 is a Number and would allow to put a Double in a list of Integer.

Hope it is more clear now ...

Upvotes: 2

Joop Eggen
Joop Eggen

Reputation: 109577

In lint2 one can add any child of Number. In lint no such thing; as one does not know the specific ?.

    lint.add(new Integer(3000)); // Error too

Hence read "? extends T" as a specific (unknown) type. Only for reading a Number, not writing.

Upvotes: 0

Prasanta samal
Prasanta samal

Reputation: 26

/**The abstract class Number is the superclass of classes BigDecimal, BigInteger, Byte, Double, Float, Integer, Long, and Short. */

/**Subclasses of Number must provide methods to convert the represented numeric value to byte, double, float, int, long, and short.

So you have to Type cast */

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

    List<Number> lint2 =  (List<Number>) lint;
    lint2.add(123);
    lint2.add(1234);
    System.out.println(lint2);

Upvotes: 1

Mariusz Nosiński
Mariusz Nosiński

Reputation: 1288

List<Number> and List<? extends Number>. Hence you cannot directly assign lint to lint2, You should cast it to List<Number> type.

Upvotes: 0

Pratik Shah
Pratik Shah

Reputation: 1852

lint is of type ArrayList() and lint2 is type of List() Here you can say that ArrayList is subclass of List so

List l1 = new ArrayList();

and like that Integer is subclass of Number ,so

Number i = new Integer(5);

But List<Number> != List<Integer> That's why it is giving error. They are different.

Upvotes: 0

Farvardin
Farvardin

Reputation: 5424

easy,

List<Integer> is not a subtype of List<Number> even though Integer is a subtype of Number.

for any subclass of Number(? extends Number) as Integer.

enter image description here

see more Generics, Inheritance, and Subtypes

Upvotes: 6

Related Questions