java - copying array list

眉间皱痕 提交于 2020-01-03 15:33:24

问题


So the below method I'm aware causes both variables to point to the same object, but if I did want to find the simplest method to has ArrayList s2 exactly the same as s1, how would I do this?

public static void main(String[] args) {

        ArrayList<String> s1 = new ArrayList<String>();
        for (int i = 1; i <= 3; i++) {
            s1.add(""+i);
        }
        ArrayList<String> s2 = s1;

    }

回答1:


You should create s2 with s1 as parameter.

public static void main(String[] args) {

    ArrayList<String> s1 = new ArrayList<String>();
    for (int i = 1; i <= 3; i++) {
        s1.add(""+i);
    }
    ArrayList<String> s2 = new ArrayList<String>(s1);

}


来源:https://stackoverflow.com/questions/10457302/java-copying-array-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!