Daily Archives: September 10, 2016

Arrays.asList(), Array to List

This is a summary for Arrays.asList() and transformation from Array to List. See below examples and comments.

public static void test1() {
    boolean[] b = new boolean[10];

    // wrong, Arrays.asList doesn't accept array of primitive type
    List<Boolean> list = Arrays.asList(b);
}

public static void test2() {
    Boolean[] b = new Boolean[10];

    // correct, because it is not primitive type
    List<Boolean> list1 = Arrays.asList(b);

    // correct, a second way for creating List for Arrays.asList()
    List<Boolean> list2 = Arrays.asList(true, true, true);
}

public static void test3() {
    Boolean[] b = new Boolean[10];
    List<Boolean> list = Arrays.asList(b);

    // exception, Arrays.asList doesn't support add element.
    list.add(true);
}

public static void test4() {
    Boolean[] b1 = new Boolean[10];
    List<Boolean> list = new ArrayList<>(Arrays.asList(b1));

    // correct, because it is a normal List
    list.add(true);
}

Check my code on github.