Create ArrayList from array

后端 未结 30 1838
遇见更好的自我
遇见更好的自我 2020-11-21 22:29

I have an array that is initialized like:

Element[] array = {new Element(1), new Element(2), new Element(3)};

I would like to convert this

30条回答
  •  悲哀的现实
    2020-11-21 23:04

    1. If we see the definition of Arrays.asList() method you will get something like this:

       public static  List asList(T... a) //varargs are of T type. 
      

      So, you might initialize arraylist like this:

       List arraylist = Arrays.asList(new Element(1), new Element(2), new Element(3));
      

      Note : each new Element(int args) will be treated as Individual Object and can be passed as a var-args.

    2. There might be another answer for this question too.
      If you see declaration for java.util.Collections.addAll() method you will get something like this:

      public static  boolean addAll(Collection c, T... a);
      

      So, this code is also useful to do so

      Collections.addAll(arraylist, array);
      

提交回复
热议问题