I am trying to Add and delete from an arraylist of a collection of objects in the same loop but in different methods and my problem is after adding and deleteing i try to print my array list but i cant get the values that is added recently. I am using the ListIterator to add and the Iterator to delete because I read in a bunch of website that this is the only ways to add and delete and the change will take place directly in the arraylist but my problem is that it is adding and deleting and the arraylist count or reference number on the debugger looks fine but when I search through it I cant find the new. added object and I still find the deleted objects.
this is the remove and add methods
public void RemoveFromAnimalList(Animal A) {
Iterator<Animal> i = AnimalList.iterator();
while (i.hasNext()) {
if (A == i.next()) {
i.remove();
}
}
}
public boolean AddNewAnimalList(Animal A) {
ListIterator litr = AnimalList.listIterator();
Animal B = null;
while (litr.hasNext()) {
B = (Animal) litr.next();
litr.add(A);
return true;
}
return false;
}
this is the method that is calling those methods above and i have tried everything and debug everything and everytime i cant find the new add element eventhough the arraylist number looks right i have 400 objects and when i delete it reachs to 399 and then again when i add it get back to 400 but when i try to print and go through the objects i cant find the new ones.
public void FirstBirth() {
TheXYAxisControl XYSave = null;
int X = 0;
int Y = 0;
for (Animal A : AnimalList) {
if (A.Type.equals("Empty")) {
X = A.XAxis;
Y = A.YAxis;
XYSave = new TheXYAxisControl(X, Y);
TheXYaxisArrayList.add(XYSave);
}
}
Random RandomNumberGen = new Random();
for (int s = 0; s < 3; s++) {
int RandomNumberGenerator = RandomNumberGen.nextInt(TheXYaxisArrayList.size());
Animal NewAnimal = new Animal(0, "Male", 0, TheXYaxisArrayList.get(RandomNumberGenerator).getX(), TheXYaxisArrayList.get(RandomNumberGenerator).getY(), 0);
RemoveFromAnimalList(AnimalList.get(RandomNumberGenerator));
AddNewAnimalList(NewAnimal);
RemoveFromOtherList(TheXYaxisArrayList.get(RandomNumberGenerator));
}
int RandomNumberGenerator = RandomNumberGen.nextInt(TheXYaxisArrayList.size());
Animal NewAnimal = new Animal(0, "Female", 0, TheXYaxisArrayList.get(RandomNumberGenerator).getX(), TheXYaxisArrayList.get(RandomNumberGenerator).getY(), 0);
RemoveFromAnimalList(AnimalList.get(RandomNumberGenerator));
AddNewAnimalList(NewAnimal);
RemoveFromOtherList(TheXYaxisArrayList.get(RandomNumberGenerator));
}
please if you have any question or other part of code i can explain.
You should really use Java generics in your Collection, List, Iterator, ListIterator etc and avoid casting.
Also you’re comparing with
==sign here:Which is just comparing 2 references. Change that to: