–
Using a Copy Constructor
ArrayList cloned = new ArrayList(collection c);
1 2 3 4 5 6
| ArrayList<Integer> nums = new ArrayList<>(Arrays.asList(1, 2, 3, 4)); ArrayList<Integer> nums2 = new ArrayList<>(nums); nums2.add(5);
System.out.println(nums); System.out.println(nums2);
|
Using the addAll() method
boolean addAll(Collection c);
1 2 3 4
| ArrayList<Integer> nums = new ArrayList<>(Arrays.asList(1, 2, 3, 4)); ArrayList<Integer> nums2 = new ArrayList<>();
nums2.addAll(nums);
|
Using streams in Java 8
1 2
| ArrayList<Integer> nums = new ArrayList<>(Arrays.asList(1, 2, 3, 4)); List<Integer> nums2 = nums.stream().collect(Collectors.toList());
|
Using the clone() method
1 2 3
| ArrayList<Integer> nums = new ArrayList<>(Arrays.asList(1, 2, 3, 4)); List<Integer> nums2 = (List<Integer>) nums.clone();
|