Arrays.asList() and new ArrayList<>() both return lists, but they do not behave the same way.
Transcribed from the original LinkedIn image post.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
| import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
class Day28 {
public static void main(String[] args) {
List<String> filePathsFromList = new ArrayList<>();
filePathsFromList.add("/home/mohibulhasan/Downloads");
filePathsFromList.add("/home/mohibulhasan/Pictures");
String[] paths = new String[]{
"/home/mohibulhasan/Downloads",
"/home/mohibulhasan/Pictures"
};
List<String> filePathsFormArray = Arrays.asList(paths);
// Calling add on a list created from Arrays.asList()
// will throw UnsupportedOperationException.
filePathsFormArray.add("/home/mohibulhasan/Applications");
filePathsFromList.add("/home/mohibulhasan/Applications");
System.out.println("Arrays.asList() returns ArrayList? "
+ (filePathsFormArray instanceof ArrayList));
System.out.println("new ArrayList<>() returns ArrayList? "
+ (filePathsFromList instanceof ArrayList));
}
}
|
The original LinkedIn graphic is preserved below.
