Close

Java Collections - Arrays.asList() Examples

Java Collections Java Java API 


Class:

java.util.Arrays

java.lang.Objectjava.lang.Objectjava.util.Arraysjava.util.ArraysLogicBig

Method:

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

This method returns a fixed-size list backed by the specified array.


Examples


package com.logicbig.example.arrays;

import java.util.Arrays;
import java.util.List;

public class AsListExample {

public static void main(String... args) {
String[] stringArray = {"one", "two", "three"};
List<String> list = Arrays.asList(stringArray);
System.out.println(list);
}
}

Output

[one, two, three]




package com.logicbig.example.arrays;

import java.util.Arrays;
import java.util.List;

public class AsListExample2 {

public static void main(String... args) {
List<String> list = Arrays.asList("one", "two", "three");
System.out.println(list);
}
}

Output

[one, two, three]




Changes to the source array reflect to the List and changes to the List reflect to the source array.

package com.logicbig.example.arrays;

import java.util.Arrays;
import java.util.List;

public class AsListExample3 {

public static void main(String... args) {
String[] stringArray = {"one", "two", "three"};
List<String> list = Arrays.asList(stringArray);
System.out.println(list);

stringArray[0] = null;
System.out.println(list);

list.set(2, "last");
System.out.println(Arrays.toString(stringArray));
}
}

Output

[one, two, three]
[null, two, three]
[null, two, last]




Cannot add more elements to the List as it is fixed size.

package com.logicbig.example.arrays;

import java.util.Arrays;
import java.util.List;

public class AsListExample4 {

public static void main(String... args) {
String[] stringArray = {"one", "two", "three"};
List<String> list = Arrays.asList(stringArray);
list.add("four");
}
}

Output

Caused by: java.lang.UnsupportedOperationException
at java.util.AbstractList.add(AbstractList.java:148)
at java.util.AbstractList.add(AbstractList.java:108)
at com.logicbig.example.arrays.AsListExample4.main(AsListExample4.java:17)
... 6 more




See Also