的ArrayList,在一个ArrayList的设置值改变另一个值 [英] ArrayLists, setting a value on one ArrayList changes a value on another

查看:506
本文介绍了的ArrayList,在一个ArrayList的设置值改变另一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所说,我有两个的ArrayList。奇怪的是,在一个ArrayList的设置值改变时的另一个。

一些信息:这些类型的条目,每个持有量和一个值(这是您在括号中看到的)的的ArrayList。我试图把这个数组:
[(5,2)(2,5)(3,2)]

到这些[(1,2)]和[(4,2)(2,5)(3,2)]。我== 1在这种情况下,和remainingAmt == 1

 的ArrayList<钥匙进入GT; firstHalf =新的ArrayList<钥匙进入GT;();
    ArrayList的<钥匙进入GT; secondHalf =新的ArrayList<钥匙进入GT;();    对于(INT J = 0; J< = I; J ++){
        firstHalf.add(rleAL.get(J));
    }
    对于(INT K = 1; K< rleAL.size(); K ++){
        secondHalf.add(rleAL.get(K));
    }
    的System.out.println(firstHalf); //使(5,2)
    firstHalf.get(ⅰ).setAmount(remainingAmt);
    的System.out.println(firstHalf); //使(1,2)*正确*
    secondHalf.get(0).setAmount(rleAL.get(ⅰ).getAmount() - remainingAmt);
    的System.out.println(firstHalf); //使(0,2)*错*


解决方案

没有什么不寻常存在 - 如果基础对象列表之间共享,在一个对象的变化将反映在其他。如果您需要的名单是独立的,需要通过创建从头开始新的对象,或复制初始对象到一个新的对象列表2#每个列表中使用不同的对象。

As the title says, I have two ArrayLists. Strangely, setting a value on one arraylist changes that of another.

Some information: these are ArrayLists of type Entry, each of which holds an amount and a value (which is what you see in the parentheses). I'm trying to turn this array: [(5,2)(2,5)(3,2)]

into these [(1,2)] and [(4,2)(2,5)(3,2)]. i == 1 in this case, and remainingAmt == 1.

ArrayList<Entry> firstHalf = new ArrayList<Entry>();
    ArrayList<Entry> secondHalf = new ArrayList<Entry>();

    for(int j = 0; j<=i;j++){
        firstHalf.add(rleAL.get(j));
    }
    for(int k = i; k<rleAL.size(); k++){
        secondHalf.add(rleAL.get(k));
    }
    System.out.println(firstHalf);//gives (5,2)
    firstHalf.get(i).setAmount(remainingAmt);
    System.out.println(firstHalf);//gives (1,2) *CORRECT*
    secondHalf.get(0).setAmount(rleAL.get(i).getAmount() - remainingAmt);
    System.out.println(firstHalf);//gives (0,2) *WRONG*

解决方案

Nothing unusual there--if the underlying objects are shared between lists, a change in one object will be reflected in the other. If you need the lists to be independent, you need to use different objects in each list by either creating new objects from scratch, or copying the initial object to a new object in list #2.

这篇关于的ArrayList,在一个ArrayList的设置值改变另一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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