public class ClassInit { private Person person=new Person("test", "test1"); private Person[] flock =new Person[]{ person }; public ClassInit() { for (int i = 0; i < flock.length; i++) { flock[i] = new Person(i+"name",i+"Id"); } } public void print() { System.out.println(person); } public void printArray() { for (Person person : flock) { System.out.println(person); } } public static void main(String[] args) { ClassInit self = new ClassInit(); self.print(); self.printArray(); } } class Person { private String name; private String id; public Person(String name, String id) { super(); this.name = name; this.id = id; } @Override public String toString() { return this.name + ":" + this.id; } }
Output:
test:test1
0name:0Id
现象:
person的值没有改变
变形1:结果和上例相同
public class ClassInit { public static void main(String[] args) { Flock flock = new Flock(); flock.print(); flock.printArray(); } } class Flock { private Person person=new Person("test", "test1"); private Person[] flock =new Person[]{ person }; public Flock() { for (int i = 0; i < flock.length; i++) { flock[i] = new Person(i+"name",i+"Id"); } } public void print() { System.out.println(person); } public void printArray() { for (Person person : flock) { System.out.println(person); } } } class Person { private String name; private String id; public Person(String name, String id) { super(); this.name = name; this.id = id; } @Override public String toString() { return this.name + ":" + this.id; } }
变形2:结果和上例相同
import java.util.ArrayList; import java.util.List; public class ClassInit { public static void main(String[] args) { Flock flock = new Flock(); flock.print(); flock.printArray(); } } class Flock { private Person person=new Person("test", "test1"); private List<Person> flock =new ArrayList<Person>(); public Flock() { flock.add(person); for (int i = 0; i < flock.size(); i++) { flock.set(i, new Person(i+"name",i+"Id")); } } public void print() { System.out.println(person); } public void printArray() { for (Person person : flock) { System.out.println(person); } } } class Person { private String name; private String id; public Person(String name, String id) { super(); this.name = name; this.id = id; } @Override public String toString() { return this.name + ":" + this.id; } }