1. 程式人生 > >Arrays.asList() 的使用註意

Arrays.asList() 的使用註意

med thread strac () array passing mod have div

Sometimes it is needed to convert a Java array to List or Collection because the latter is a more powerful data structure - A java.util.List have many functionality that ordinary array do not support. For example, we can easily check if a List contains a specific value with just one built-in method call. Below are some examples on how to convert an array to List.

Convert Array To List using java.util.Arrays.asList()

The class java.util.Arrays has a convenient method named asList that can help with the task of conversion. Here is the syntax:

public static <T> List<T> asList(T... a)

Notice that the parameter does not necessarily receive an array but varargs. It means we can create a List using this code:

public class Test {
   public static void main(String[] args) {
      List<String> myList = Arrays.asList("Apple");
   }
}

Which creates a List with one item - the String "Apple". We could also do this:

public class Test {
   public static void main(String[] args) {
      List<String> myList = Arrays.asList("Apple", "Orange");
   }
}

This will create a List with two items - the Strings "Apple" and "Orange".

Since this is varargs, we can pass an Array and the items are treated as the arguments. Here is an example code:

public class Test {
   public static void main(String[] args) {
      String[] myArray = { "Apple", "Banana", "Orange" };
      List<String> myList = Arrays.asList(myArray);
      for (String str : myList) {
         System.out.println(str);
      }
   }
}

Here, a List of String was created and the contents of the Array "myArray" was added to it. The List "myList" will have the size of 3. Here is the output of the code:

Apple
Banana
Orange

Pitfalls

This approach however has some problems:

  • The Array passed must be an array of Objects and not of primitive type

    If we will pass an array of primitive type, for example:

    public class Test {
       public static void main(String[] args) {
          int[] myArray = { 1, 2, 3 };
          List myList = Arrays.asList(myArray);
          System.out.println(myList.size());
       }
    }
    
    The output of the code will be:
    1
    
    Why? Because the asList method is expecting a varargs of Objects and the parameters passed is an Array of primitive, what it did was it created a List of Array! And the only element of the List is "myArray". Hence, this code
    myList.get(0)
    
    will return the same object as "myArray".
  • The List created by asList is fixed-size

    The returned list by the asList method is fixed sized and it can not accommodate more items. For example:

    public class Test {
       public static void main(String[] args) {
          String[] myArray = { "Apple", "Banana", "Orange" };
          List<String> myList = Arrays.asList(myArray);
          myList.add("Guava");
       }
    }
    
    Will have the output:
    Exception in thread "main" java.lang.UnsupportedOperationException
    	at java.util.AbstractList.add(AbstractList.java:148)
    	at java.util.AbstractList.add(AbstractList.java:108)
    	at Test.main(Test.java:8)
    
    Because myList is fixed-sized an can‘t add more items to it.

Convert Primitive Array To List

As mentioned above, passing a primitive array to Arrays.asList() will not work. A workaround without introducing a third party library is through Java 8‘s stream. Here is an example:

public class Test {
   public static void main(String[] args) {
      int[] intArray = { 5, 10, 21 };
      List myList = Arrays.stream(intArray).boxed()
            .collect(Collectors.toList());
   }
}

And the individual array items will be converted from int to Integer (boxing), and converted to a List.

Convert Array To List That Allows Adding More Items

As mentioned in pitfalls above, the result of Arrays.asList() does not support adding or removing items. If you don‘t want this behavior, here is an alternative solution:

public class Test {
   public static void main(String[] args) {
      String[] myArray = { "Apple", "Banana", "Orange" };
      List<String> myList = new ArrayList<String>(Arrays.asList(myArray));
      myList.add("Guava");
   }
}

What this code do is create a new ArrayList explicitly and then add the items from the result of Arrays.asList(). And since it is our code that created the ArrayList, there is no restriction in adding or removing items. The code above will have 4 items in it right before the program ends. No exception will be thrown when the code is executed.

Convert Array To List Using Own Implementation

There are times when it is better to use our own implementation when solving a problem. Here is a simple implementation of converting a Java array to List:

public class Test {
   public static void main(String[] args) {
      String[] myArray = { "Apple", "Banana", "Orange" };
      List<String> myList = new ArrayList<String>();
      for (String str : myArray) {
         myList.add(str);
      }
      System.out.println(myList.size());
   }
}

The expected output of the code is that it should display "3", because there are 3 items in the List after the logic is executed.

The downside of this is that our code is longer and we are reinventing the wheel. The pros is that we can accommodate customization if our requirement changes. For example, here is the code where each item in the array is added twice to the List.

public class Test {
   public static void main(String[] args) {
      String[] myArray = { "Apple", "Banana", "Orange" };
      List<String> myList = new ArrayList<String>();
      for (String str : myArray) {
         myList.add(str);
         myList.add(str);
      }
      System.out.println(myList.size());
   }
}

Here the output becomes 6 because each String in the array was added twice. Here is another example that converts an array of String to a List of Integer:

public class Test {
   public static void main(String[] args) {
      String[] myArray = { "5", "6", "7" };
      List<Integer> myList = new ArrayList<Integer>();
      for (String str : myArray) {
         myList.add(Integer.valueOf(str));
      }
   }
}

Each String in the array is parsed and converted to corresponding Integer. The resulting List will contain all converted Integers.

Arrays.asList() 的使用註意