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
为什么我的对象在第二种情况下在第一种情况下没有发生时会超控?
答案 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”。