Differences between List.of and Arrays.asList
-
List.of
can be best used when data set is less and unchanged, whileArrays.asList
can be used best in case of large and dynamic data set. -
List.of
take very less overhead space because it has field-based implementation and consume less heap space, both in terms of fixed overhead and on a per-element basis. whileArrays.asList
take more overhead space because while initialization it creates more objects in heap. -
Collection returned by
List.of
is immutable and hence thread-safe while Collection returned byArrays.asList
is mutable and not thread safe. (Immutable collection instances generally consume much less memory than their mutable counterparts.) -
List.of
doesn't allow null elements whileArrays.asList
allows null elements. List.of()
introduced in Java 9
import java.util.*;
public class GFG1 {
public static void main(String[] argv) throws Exception
{
try {
String a[] = new String[] { "A", "B", "C", "D" };
for (String as : a) {
System.out.println("The Arrays is: " +as );
}
List list = Arrays.asList(a);
System.out.println("The Arrays.asList is: " + list);
List list1 = List.of(a);
System.out.println("The List.of is: " + list1);
}
catch (NullPointerException e) {
System.out.println("Exception thrown : " + e);
}
}
}
/* The Result is As follows*/
The Arrays is: A
The Arrays is: B
The Arrays is: C
The Arrays is: D
The Arrays.asList is: [A, B, C, D]
The List.of is: [A, B, C, D]
No Comments Yet!!