How to copy ArrayList in Java

2 Answers

0 votes
import java.util.ArrayList;
import java.util.Arrays;

public class MyClass {
    public static void main(String args[]) {
        ArrayList al = new ArrayList(Arrays.asList("c#", "c++", "c", "java"));
        
        ArrayList<String> copyAL = (ArrayList<String>) al.clone();
 
        for (Object element : copyAL) {
            if (element instanceof String) {
                System.out.println(element);
            }
        }
    }
}





/*
run:

c#
c++
c
java

*/

 



answered Oct 9, 2023 by avibootz
0 votes
import java.util.ArrayList;
import java.util.Arrays;

public class MyClass {
    public static void main(String args[]) {
        ArrayList al = new ArrayList(Arrays.asList("c#", "c++", "c", "java"));
        
        ArrayList<String> copyAL = new ArrayList<>(al);
 
        for (String element : copyAL) {
            System.out.println(element);
        }
    }
}





/*
run:

c#
c++
c
java

*/

 



answered Oct 9, 2023 by avibootz
...