Java ArrayList 和修改其中包含的对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9774651/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 07:31:39  来源:igfitidea点击:

ArrayList and modifying objects included in it

javaarraylistpass-by-reference

提问by Primo? Kralj

Say we have an ArrayList myArray. I want to modify an object by calling its function. If I do it this way, will the original object be changed or not?

假设我们有一个 ArrayList myArray。我想通过调用它的函数来修改一个对象。如果我这样做,是否会更改原始对象?

myArray.get(0).myModyfyingFunction();

To clarify further - I am concerned if get() actually returns a reference to my original object or does it only return a copy of my original object.

进一步澄清 - 我担心 get() 是否真的返回对我的原始对象的引用,或者它是否只返回我的原始对象的副本。

采纳答案by óscar López

get()will return a reference to the object, never a copy. Any modification you do on the returned reference will be made on the object itself

get()将返回对对象的引用,而不是副本。您对返回的引用所做的任何修改都将在对象本身上进行

回答by Thomas

Java never returns copies of objects, only copies to references of objects. Thus the method would definitely change the object at index 0.

Java 从不返回对象的副本,只返回对象引用的副本。因此,该方法肯定会更改索引 0 处的对象。

You could get a "copy" of an object if the method would create one, e.g. by using return object.clone();if possible, but what is actuallyreturned is a reference to the copy that was still created in the method. So you could get a "copy" of an object in a broader sense, but ArrayList#get(...)won't do that - and by convention neither getter should do that unless explicitly stated.

如果方法会创建一个对象,您可以获得一个对象的“副本”,例如,return object.clone();如果可能的话,通过使用,但实际返回的是对仍然在方法中创建的副本的引用。因此,您可以在更广泛的意义上获得对象的“副本”,但 ArrayList#get(...)不会这样做 - 按照惯例,除非明确说明,否则 getter 都不应该这样做。

回答by ring bearer

This depends on what kind of object you stored in your ArrayList. For example, if they are java.lang.Strings, the calls will not modify anything. Otherwise, yes it will modify your object stored at index 0.

这取决于您存储在 ArrayList 中的对象类型。例如,如果它们是java.lang.Strings,则调用不会修改任何内容。否则,是的,它将修改您存储在索引 0 处的对象。

回答by Alonso Dominguez

It gives you a reference to the object so if your function performs any modification in its state, your object will be modified.

它为您提供对对象的引用,因此如果您的函数在其状态中执行任何修改,您的对象将被修改。

Same happens when you do this:

执行此操作时也会发生同样的情况:

ArrayList myArray = new ArrayList();
MyObject obj = new MyObject();
myArray.add(obj);
obj.myModifyingFunction();
myArray.get(0).equals(obj); // returns true
myArray.get(0) == obj; // returns true as well

回答by kundan bora

If you store any object in ArrayList, Object is not replicated and any change in object should reflect in object itself.

如果您在 ArrayList 中存储任何对象,则不会复制对象,并且对象中的任何更改都应反映在对象本身中。

for example we have class NewClass

例如我们有类 NewClass

  public class NewClass {

private String mystring="";

/**
 * @return the mystring
 */
public String getMystring() {
    return mystring;
}

/**
 * @param mystring the mystring to set
 */
public void setMystring(String mystring) {
    this.mystring = mystring;
}

}

}

here is code in main method of any other class

这是任何其他类的 main 方法中的代码

   List<NewClass> newclasses = new ArrayList<NewClass>();
    NewClass class1 = new NewClass();
    class1.setMystring("before1");
    NewClass class2 = new NewClass();
    class2.setMystring("before2");
    newclasses.add(class1);
newclasses.add(class2);
newclasses.get(0).setMystring("after1");
System.out.println(class1.getMystring());

This will output after1.

这将在1之后输出。

回答by Steer360

Here is an example. Modify an object of Test class in the List.

这是一个例子。修改List中Test类的一个对象。

public class ModifyArrayList {

    public static void main (String [] args) {

        List<Test> tests = new ArrayList<Test>();

        Test firstTest = new Test();
        firstTest.setId(100);
        firstTest.setName("John");
        tests.add(firstTest);

        Test secondTest = new Test();
        secondTest.setId(101);
        secondTest.setName("Tracy");
        tests.add(secondTest);

        Test thirdTest = new Test();
        thirdTest.setId(102);
        thirdTest.setName("Ryan");
        tests.add(thirdTest);

        ListIterator<Test> testIterator = tests.listIterator();
        while(testIterator.hasNext()) {

            Test test = testIterator.next();
            if (test.getName().equals("Ryan")) {
                test.setId(300);
            }

            testIterator.remove();
            testIterator.add(test);
        }

        for (Test test : tests) {
            System.out.println("Test #" + test.getId() + " name=" + test.getName());
        }

    }
}

Test.java

测试.java

class Test {

    private int id;
    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

回答by Dunno Dunno

Update objects in list:

更新列表中的对象:

for (User user: Users) {
    user.setName( user.getName() + " New Name");
}

Show updated objects

显示更新的对象

for (User user: Users) {    
    System.out.println( user.getName());
}