简体   繁体   中英

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

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 .

在此处输入图片说明

see more Generics, Inheritance, and Subtypes

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 ...

/**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);

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM