按引用或按值存储在列表中的对象

时间:2014-10-05 03:56:33

标签: java

通过参数传递对象时,它通过引用传递。当我从List调用add方法时,它是否存储对列表中对象的引用或List中对象的新实例?如果它是通过引用存储的,那么我可以同时存在一个具有两个列表的对象吗?

1 个答案:

答案 0 :(得分:0)

Java中的所有内容都是按值传递的。我们有:

  • 基元:例如intbooleandouble,等等。这些很容易被视为通过价值。

  • 对象:对象引用按值传递

对象示例:

public static void main(String[] args) {
    String first = "a";

    tryToChangeReference(a);

    // The value of 'first' is still "a"
    // In fact, if the value of 'first' was changed by 
    //    the tryToChangeReference method, then you 
    //    know that the language passes by reference
    System.out.println(a); //outputs: a
}

private static void tryToChangeReference(String a) {
    a = "b";
}

所以,回答你的问题......是的,你可以让一个对象存在两个不同的列表。 例如:

public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }
    public void getAge() {
        return age;
    }
    public void setAge(int newAge) {
        this.age = newAge;
    }

    @Override
    public String toString() {
        return name + ":" + age;
    }
}

// a main somewhere else
public static void main(String[] args) {
    List<String> firstList = new ArrayList<String>();
    List<String> secondList = new ArrayList<String>();

    Person tom = new Person("Tom", 20);

    firstList.add(tom);
    secondList.add(tom);

    System.out.println(firstList.get(0));  //output: Tom:20
    System.out.println(secondList.get(0)); //output: Tom:20

    //we modify the Person object in firstList
    firstList.get(0).setAge(33);

    System.out.println(firstList.get(0));  //output: Tom:33
    System.out.println(secondList.get(0)); //output: Tom:33

    //we modify the Person object 'tom'
    tom.setAge(99);

    System.out.println(firstList.get(0));  //output: Tom:99
    System.out.println(secondList.get(0)); //output: Tom:99

    //we now change the reference value of the Person object 'tom'
    tom = new Person("Sam", 44);

    System.out.println(firstList.get(0));  //output: Tom:99
    System.out.println(secondList.get(0)); //output: Tom:99

    //how about this
    secondList.set(0, new Person("Mat", 50);

    System.out.println(firstList.get(0));  //output: Tom:99
    System.out.println(secondList.get(0)); //output: Mat:50
}