我的主要部分
try{
Scanner read = new Scanner(file);
int fix = read.nextInt();
do{
for(int x = 0; x < fix; x++){
String petname = read.next();
int birthday = read.nextInt();
String species = read.next();
double bill = read.nextDouble();
String owner = read.next();
Veterinarian work = new Veterinarian(petname, birthday, species, bill, owner);
Veterinarian.Vet.add(work);
}
}
while(read.hasNextLine() == pick);
}
catch(FileNotFoundException FNF){
System.err.format("File not found");}
这是我的课
static List<Veterinarian> Vet = new ArrayList<>();
public Veterinarian(){}
public Veterinarian(String petname, int birthday, String species, double bill, String owner){
this.petname = petname;
this.birthday = birthday;
this.species = species;
this.bill = bill;
this.owner = owner;
Vet.add(this);
}
我不知道为什么我使用的 add 方法是将对象的两个副本创建到两个单独的 ArrayList 中。 感谢您的帮助!
最佳答案
因为你添加了两次......
String owner = read.next();
Veterinarian work = new Veterinarian(petname, birthday, species, bill, owner);
Veterinarian.Vet.add(work); // once
...
public Veterinarian(String petname, int birthday, String species, double bill, String owner){
this.petname = petname;
this.birthday = birthday;
this.species = species;
this.bill = bill;
this.owner = owner;
Vet.add(this); // twice
}
另请注意,它会 be better practice删除第二次调用(在构造函数中)。
关于java - 为什么我的 ArrayList 创建一个对象的两个副本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23354399/