Cannot add an object of type T to the list in Java

I've been learning generics in Java Although I understand the concepts of type inference, parameterized classes and methods, I encountered a strange scene in the experiment

I have implemented a @ R_ 680_ 2419 @ class, which can be used to save items of type T I use list as the internal data structure of this abstraction Here is my code:

public class @R_680_2419@<T> {

    private List<T> items;

    public @R_680_2419@(){
        items = new ArrayList<>();
    }

    public <T> void addItemTo@R_680_2419@(T t){
        items.add(t);
    }
}

I'm at items Add (T) gets a compile time error saying that add (T) in the list cannot be applied to (T) I can't figure out the cause of the mistake In addition, I don't understand why I can't add items of type T to the list parameterized by T

Solution

You have redeclared the generic type variable < T > locally In your way addItemTo@R_680_2419 @It hides the class @ R_ 680_ 2419 @ < T > >

< T > your method is a different item on the list < T >;

Your current code is 100% equivalent to:

public class @R_680_2419@<T> {

    private List<T> items;

    public @R_680_2419@(){
        items = new ArrayList<>();
    }

    public <T2> void addItemTo@R_680_2419@(T2 t){
        items.add(t);
    }
}

If you look at this, you should know why your code cannot be compiled

Solution: delete < T > before the method declaration

public void addItemTo@R_680_2419@(T t)
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>