Create ArrayList from array

后端 未结 30 1809
遇见更好的自我
遇见更好的自我 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 22:51

    Below code seems nice way of doing this.

    new ArrayList<T>(Arrays.asList(myArray));
    
    0 讨论(0)
  • 2020-11-21 22:52

    Another way (although essentially equivalent to the new ArrayList(Arrays.asList(array)) solution performance-wise:

    Collections.addAll(arraylist, array);
    
    0 讨论(0)
  • 2020-11-21 22:55

    (old thread, but just 2 cents as none mention Guava or other libs and some other details)

    If You Can, Use Guava

    It's worth pointing out the Guava way, which greatly simplifies these shenanigans:

    Usage

    For an Immutable List

    Use the ImmutableList class and its of() and copyOf() factory methods (elements can't be null):

    List<String> il = ImmutableList.of("string", "elements");  // from varargs
    List<String> il = ImmutableList.copyOf(aStringArray);      // from array
    

    For A Mutable List

    Use the Lists class and its newArrayList() factory methods:

    List<String> l1 = Lists.newArrayList(anotherListOrCollection);    // from collection
    List<String> l2 = Lists.newArrayList(aStringArray);               // from array
    List<String> l3 = Lists.newArrayList("or", "string", "elements"); // from varargs
    

    Please also note the similar methods for other data structures in other classes, for instance in Sets.

    Why Guava?

    The main attraction could be to reduce the clutter due to generics for type-safety, as the use of the Guava factory methods allow the types to be inferred most of the time. However, this argument holds less water since Java 7 arrived with the new diamond operator.

    But it's not the only reason (and Java 7 isn't everywhere yet): the shorthand syntax is also very handy, and the methods initializers, as seen above, allow to write more expressive code. You do in one Guava call what takes 2 with the current Java Collections.


    If You Can't...

    For an Immutable List

    Use the JDK's Arrays class and its asList() factory method, wrapped with a Collections.unmodifiableList():

    List<String> l1 = Collections.unmodifiableList(Arrays.asList(anArrayOfElements));
    List<String> l2 = Collections.unmodifiableList(Arrays.asList("element1", "element2"));
    

    Note that the returned type for asList() is a List using a concrete ArrayList implementation, but it is NOT java.util.ArrayList. It's an inner type, which emulates an ArrayList but actually directly references the passed array and makes it "write through" (modifications are reflected in the array).

    It forbids modifications through some of the List API's methods by way of simply extending an AbstractList (so, adding or removing elements is unsupported), however it allows calls to set() to override elements. Thus this list isn't truly immutable and a call to asList() should be wrapped with Collections.unmodifiableList().

    See the next step if you need a mutable list.

    For a Mutable List

    Same as above, but wrapped with an actual java.util.ArrayList:

    List<String> l1  = new ArrayList<String>(Arrays.asList(array));    // Java 1.5 to 1.6
    List<String> l1b = new ArrayList<>(Arrays.asList(array));          // Java 1.7+
    List<String> l2  = new ArrayList<String>(Arrays.asList("a", "b")); // Java 1.5 to 1.6
    List<String> l2b = new ArrayList<>(Arrays.asList("a", "b"));       // Java 1.7+
    

    For Educational Purposes: The Good ol' Manual Way

    // for Java 1.5+
    static <T> List<T> arrayToList(final T[] array) {
      final List<T> l = new ArrayList<T>(array.length);
    
      for (final T s : array) {
        l.add(s);
      }
      return (l);
    }
    
    // for Java < 1.5 (no generics, no compile-time type-safety, boo!)
    static List arrayToList(final Object[] array) {
      final List l = new ArrayList(array.length);
    
      for (int i = 0; i < array.length; i++) {
        l.add(array[i]);
      }
      return (l);
    }
    
    0 讨论(0)
  • 2020-11-21 22:55

    Simplest way to do so is by adding following code. Tried and Tested.

    String[] Array1={"one","two","three"};
    ArrayList<String> s1= new ArrayList<String>(Arrays.asList(Array1));
    
    0 讨论(0)
  • 2020-11-21 22:56

    Another simple way is to add all elements from the array to a new ArrayList using a for-each loop.

    ArrayList<Element> list = new ArrayList<>();
    
    for(Element e : array)
        list.add(e);
    
    0 讨论(0)
  • 2020-11-21 22:58
    new ArrayList<T>(Arrays.asList(myArray));
    

    Make sure that myArray is the same type as T. You'll get a compiler error if you try to create a List<Integer> from an array of int, for example.

    0 讨论(0)
提交回复
热议问题