I'm coding a simple fun project in Java, creating a loop which creates an object in an arraylist with the name+Random(1-60) (ex. Dog2, Dog6) 59 times.
And this loop, will check if an object it just made has a same name as the other object in the same arraylist, and delete the object it just made.
Basically, it will delete an object with a clone name.
But I don't know how.
I've tried this but... It doesn't work.
public class main {
public static void main(String[] args) {
ArrayList<Animal> Pets = new ArrayList<Animal>();
Random rand = new Random();
int ha = rand.nextInt(59)+1;
for (int i = 0; i <= 59; i++) {
Pets.add(new Dog("Dog"+ha, 4));
//Clone name object detector,
if (Pets.size() > 0+1) {
if (Pets.get(i).name == Pets.get(i-1).name) {
Pets.remove(i);
} // and deleter
}
Pets.get(i).makeSound();
ha = rand.nextInt(59)+1;
}
}
}
An object with a clone name still exists. I know that wouldn't work, because i-1
is pretty small.
Dog4 barks.
Dog16 barks.
Dog11 barks.
Dog37 barks.
Dog25 barks.
Dog35 barks.
Dog40 barks.
Dog30 barks.
Dog14 barks.
Dog44 barks.
Dog4 barks.
Dog21 barks.
Dog37 barks.
Dog51 barks.
Dog20 barks.
Dog30 barks.
Dog32 barks.
Dog25 barks.
Dog26 barks.
Dog41 barks.
Dog20 barks.
Dog37 barks.
Dog23 barks.
Dog48 barks.
Dog49 barks.
Dog8 barks.
Dog7 barks.
Dog40 barks. --
Dog34 barks.
Dog29 barks.
Dog8 barks.
Dog52 barks.
Dog9 barks.
Dog27 barks.
Dog31 barks.
Dog46 barks.
Dog19 barks.
Dog46 barks.
Dog25 barks.
Dog33 barks.
Dog38 barks.
Dog9 barks.
Dog40 barks.--
Dog56 barks.
Dog18 barks.
Dog51 barks.
Dog17 barks.
Dog22 barks.
Dog6 barks.
Dog40 barks. --
Dog47 barks.
Dog23 barks.
Dog10 barks.
Dog23 barks.
Dog20 barks.
Dog13 barks.
Dog33 barks.
Dog35 barks.
Dog18 barks.
Dog17 barks.
So i need help, how can i do this?