本文介绍了更新另一个Java列表时Java列表已更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有:

public class Test {

    private List<String> mWorkList;
    private List<String> mOriginalList;

    public Test(List<String> list) {
        mWorkList = list;
        mOriginalList = list;
    }

    public void updateData(List<String> newList) {
        mWorkList.clear();
        mWorkList.addAll(newList);
    }
}

我只想更改 mWorkList ,但是当我调用 updateData(List< String>)时, mOriginalList 也被更改了.那么如何使 mOriginalList 保持最初在构造函数中分配的状态?

I want to change only mWorkList but mOriginalList is changed too when I call updateData(List<String>). So how should I do it to keep mOriginalList as initially assigned in constructor?

推荐答案

在Java中,您可以按变量的引用传递变量.这意味着每当您执行 mWorkList = list 之类的赋值时,变量 mWorkList 都将指向相同在内存中的位置,其中 list 当前指向.如果您执行 mOriginalList = list ,则 mOriginalList 也将指向该位置.IE.此时,所有三个列表指的是同一对象.

In Java you pass variables by their reference. This means that whenever you do an assignment like mWorkList = list the variable mWorkList will point to the same place in memory where list is currently pointing. If you do mOriginalList = list, then mOriginalList will also point to that position. I.e. all three lists refer the same object at that point.

如果要独立列表,则需要将列表中的所有值复制新列表,如下所示:

If you want independent lists you need to copy all values from the list to a new list like this:

List<String> myList = new ArrayList<>(otherList);

ArrayList 的构造函数自动添加另一个列表中的所有值,这是其文档.

This constructor of ArrayList automatically adds all values from the other list, here is its documentation.

您的代码将如下所示:

public Test(List<String> list) {
    mWorkList = new ArrayList<>(list);
    mOriginalList = new ArrayList<>(list);
}

或者,如果您不想更改 mOriginalList ,也可以将其保留为 mOriginalList = list .但是请记住,如果用户对 list (来自类的外部)进行了更改,这些更改也将反映在您的 mOriginalList ,这很容易导致讨厌的错误.

Or if you don't intent to change mOriginalList you could also leave it as mOriginalList = list. But then bear in mind that if the user makes changes to list (which comes from outside of your class) they will also be reflected in your mOriginalList which could easily lead to nasty bugs.

这篇关于更新另一个Java列表时Java列表已更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 03:23