Using and declaring generic List

前端 未结 3 1641
离开以前
离开以前 2020-12-10 11:50

So I\'m working in Java and I want to declare a generic List.

So what I\'m doing so far is List list = new ArrayList();

But no

相关标签:
3条回答
  • 2020-12-10 12:14

    You should either have a generic class or a generic method like below:

    public class Test<T>  {
        List<T> list = new ArrayList<T>();
        public Test(){
    
        }
        public void populate(T t){
            list.add(t);
        }
        public static  void main(String[] args) {
            new Test<String>().populate("abc");
        }
    }
    
    0 讨论(0)
  • 2020-12-10 12:16

    The T is the type of the objects that your list will contain. You can write List<String> and use it in a function which needs List<T>, it shouldn't be a problem since the T is used to say that it can be anything.

    0 讨论(0)
  • 2020-12-10 12:36

    You cannot add the "X"(String) into the list having type of directly so that you need to write a function which accept T as a parameter and add into the List, like

    List<T> myList = new ArrayList<T>(0);
    public void addValue(T t){
      myList.add(t);
    }
    

    and while calling this function you can pass string.

     object.addValue("X");
    
    0 讨论(0)
提交回复
热议问题