another java generic question

前端 未结 6 773
别跟我提以往
别跟我提以往 2020-12-08 17:39

I have the following class:

interface Able{/* ... */}
class A implements Able{/* ... */}

and I have

Map

        
6条回答
  •  有刺的猬
    2020-12-08 18:35

    From http://download.oracle.com/javase/tutorial/extra/generics/wildcards.html:

    There is, as usual, a price to be paid for the flexibility of using wildcards. That price is that it is now illegal to write into [a wildcard-based container]. For instance, this is not allowed:

    public void addRectangle(List shapes) {
        shapes.add(0, new Rectangle()); // Compile-time error!
    }
    

    You should be able to figure out why the code above is disallowed. The type of the second parameter to shapes.add() is ? extends Shape-- an unknown subtype of Shape. Since we don't know what type it is, we don't know if it is a supertype of Rectangle; it might or might not be such a supertype, so it isn't safe to pass a Rectangle there.

提交回复
热议问题