java - 复制数组列表 [英] java - copying array list

查看:25
本文介绍了java - 复制数组列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我知道下面的方法会导致两个变量指向同一个对象,但是如果我确实想找到最简单的方法使 ArrayList s2 与 s1 完全相同,我该怎么做?

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;

    }

推荐答案

您应该以 s1 作为参数创建 s2.

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);

}

这篇关于java - 复制数组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆