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

时间:2014-04-29 02:24:38

标签: java object arraylist

我的主要部分

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。 谢谢你的帮助!

3 个答案:

答案 0 :(得分:1)

因为你要加两次......

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删除第二次调用(在构造函数中)。

答案 1 :(得分:1)

您正在构造函数中添加它:

Vet.add(this);

并且您将其添加到主要内容中:

Veterinarian.Vet.add(work);

答案 2 :(得分:0)

当您使用

创建兽医实例时,会调用add方法两次

Veterinarian work = new Veterinarian(petname, birthday, species, bill, owner)

已调用add方法,之后再次调用

Veterinarian.Vet.add(work);