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

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

问题描述

正如标题所说,我有两个 ArrayList.奇怪的是,在一个数组列表上设置一个值会改变另一个.

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

一些信息:这些是 Entry 类型的 ArrayLists,每个数组包含一个数量和一个值(这是你在括号中看到的).我正在尝试转动这个数组:[(5,2)(2,5)(3,2)]

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

进入这些 [(1,2)] 和 [(4,2)(2,5)(3,2)].在这种情况下,i == 1,而剩余的Amt == 1.

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*

推荐答案

没有什么不寻常的地方——如果底层对象在列表之间共享,一个对象的变化将反映在另一个对象中.如果您需要列表独立,则需要通过从头开始创建新对象或将初始对象复制到列表 #2 中的新对象来使用每个列表中的不同对象.

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.

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

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