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

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

问题描述

所以,下面的方法,我知道原因,这两个变量指向同一个对象,但如果我想找到已ArrayList的S2完全一样,S1最简单的方法,我会怎么做呢?

 公共静态无效的主要(字串[] args){        ArrayList的<串GT; S1 =新的ArrayList<串GT;();
        的for(int i = 1; I< = 3;我++){
            s1.add(+ I);
        }
        ArrayList的<串GT; S2 = S1;    }


解决方案

您应该创建S2与S1作为参数。<​​/ P>

 公共静态无效的主要(字串[] args){    ArrayList的&LT;串GT; S1 =新的ArrayList&LT;串GT;();
    的for(int i = 1; I&LT; = 3;我++){
        s1.add(+ I);
    }
    ArrayList的&LT;串GT; S2 =新的ArrayList&LT;串GT;(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;

    }

解决方案

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

}

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

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