'Arrays.asList()' and 'ArrayList' are both related to the Java Collections Framework
and are used to store and manipulate collections of objects.
However, there are some key differences between them.
1. Type of Collection :
- 'Arrays.asList()' : It returns a fixed-size 'List' backed by an array. They underlying array cannot be resized, and any attempt to modify the size of the list will result in an 'UnsupportedOperationException'.
- 'ArrayList' : It is an implementation of the 'List' interface that uses an underlying array to store elements. 'ArrayList' provides dynamic resizing, allowing you to add or remove elements freely.
2. Modifiability :
- 'Arrays.asList()' : The resulting list is a view of the original array. If you modify the original array, the list will reflect the changes, and vice versa. However, the size of the list cannot be modified, so attempts to add or remove elements will result in an exception.
- 'ArrayList' : It allows you to freely add, remove, and modify elements. The size of the 'ArrayList' can dynamically grow or shrink based on the operations performed.
3. Memory Efficiency :
- 'Arrays.asList()' : It provides a memory-efficient way to create a fixed-size list since it uses the original array as its backing structure.
- 'ArrayList' : It dynamically resizes its internal array to accommodate the number of elements, which can result in some memory overhead due to resizing operations.
4. Creation and Initialization :
- 'Arrays.asList()' : It is a static method provided by the 'Arrays' class and is typically used to convert an array to a list. For example: 'List<Integer> list = Arrays.asList(1, 2, 3);'
- 'ArrayList' : It is a class that needs to be instantiated using the 'new' keyword. For example : 'ArrayList<Integer> list = new ArrayList<>();'
Here's an example to illustrate the differences :
String[] array = { "apple", "banana", "cherry" };
// Using Arrays.asList()
List<String> asList = Arrays.asList(array);
System.out.println(asList); // Output: [apple, banana, cherry]
asList.set(0, "orange");
System.out.println(asList); // Output: [orange, banana, cherry]
System.out.println(Arrays.toString(array)); // Output: [orange, banana, cherry]
// Using ArrayList
ArrayList<String> arrayList = new ArrayList<>(Arrays.asList(array));
System.out.println(arrayList); // Output: [apple, banana, cherry]
arrayList.add("durian");
System.out.println(arrayList); // Output: [apple, banana, cherry, durian]
System.out.println(Arrays.toString(array)); // Output: [apple, banana, cherry]
In summary, 'Arrays.asList()' is useful for quickly converting an array to a fixed-size 'List', while 'ArrayList' provides a resizable collection that allows you to add, remove, and modify elements.
'Language > Java' 카테고리의 다른 글
Lambda expressions (0) | 2023.06.16 |
---|---|
Anonymous class (0) | 2023.06.14 |
Array and ArrayList (0) | 2023.05.30 |
Generics (0) | 2023.05.29 |
replace, replaceAll (0) | 2023.05.25 |