gpt4 book ai didi

java - 为什么我的 ArrayList 创建一个对象的两个副本?

转载 作者:行者123 更新时间:2023-12-02 05:53:15 24 4
gpt4 key购买 nike

我的主要部分

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com