这段代码中的对象如何工作?

时间:2016-09-26 10:48:33

标签: java

public class MainClass
{
    private String name="";

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public static void main(String[] args)
    {
        ArrayList<String> al=new ArrayList<String>();
        String str=new String("abc");
        al.add(str);
         str="def";
        al.add(str);
         str="ghi";
        al.add(str);
         str="jkl";
        al.add(str);
        System.out.println(al);

        ArrayList<MainClass> al1=new ArrayList<MainClass>();
        MainClass mainclass=new MainClass();
        mainclass.setName("Abhi");
        al1.add(mainclass);
        mainclass.setName("Sajith");
        al1.add(mainclass);
        mainclass.setName("Sridhar");
        al1.add(mainclass);

        for(MainClass main:al1)
            System.out.println(main.getName());
     }
}

输出:

[abc, def, ghi, jkl]
Sridhar
Sridhar
Sridhar

为什么我的对象在第二种情况下在第一种情况下没有发生时会超控?

1 个答案:

答案 0 :(得分:1)

    ArrayList<String> al=new ArrayList<String>();
    //a1 is empty ArrayList of Strings.
    String str=new String("abc");
    //str is now a reference to "abc"
    al.add(str);
    //a1 has now reference to "abc"
    str="def";
    //str has now reference to "def"
    al.add(str);
    //a1 has now reference to "abc" and reference to "def"
    str="ghi";
    //str has now reference to "ghi"
    al.add(str);
    //a1 has now three different references
    str="jkl";
    //str has now reference to "jkl"
    al.add(str);
    //a1 has now four different references.
    System.out.println(al);

    ArrayList<MainClass> al1=new ArrayList<MainClass>();
    //al1 is now empty
    MainClass mainclass=new MainClass();
    //mainclass has now reference to an object with an empty String
    mainclass.setName("Abhi");
    //mainclass' reference didn't change. It's still the same, however the string is different
    al1.add(mainclass);
    //al1 has now one reference to the mainclass
    mainclass.setName("Sajith");
    //mainclass' reference didn't change. It's still the same, however the string is different
    al1.add(mainclass);
    //al1 has now two references to the mainclass
    mainclass.setName("Sridhar");
    //mainclass' reference didn't change. It's still the same, however the string is different
    al1.add(mainclass);
    //al1 has now three references to the mainclass

    for(MainClass main:al1)
        System.out.println(main.getName());

因此,您的第一个ArrayList有四个不同的引用,指向不同的值。你的第二个ArrayList的引用是同一引用的三倍,最后代表mainClass的{​​{1}}是“Sridhar”。