0

Part of my main

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");}

this is my class

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);
}

I don't know why the add method I'm using is creating two copies of the object into two separate ArrayList's. Thanks for the help!

Bryce
  • 97
  • 1
  • 10

3 Answers3

1

Because you're adding it twice...

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
}

Also note, it would be better practice to remove the second invocation (in your constructor).

Community
  • 1
  • 1
Jeffrey
  • 44,417
  • 8
  • 90
  • 141
1

You are adding it in the constructor:

Vet.add(this);

and you are adding it in the main:

Veterinarian.Vet.add(work);
Couchy
  • 753
  • 1
  • 5
  • 25
0

the add method is called twice, when you new a instance of Veterinarian using

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

the add method has been called, and you call it again after that

Veterinarian.Vet.add(work);

Ginsan
  • 344
  • 2
  • 8