Practice pieces


ArrayLists

Ok, the biggest problem here is that if you try to delete objects from a collection that the system is counting through, it either won't work or it won't like it.

In the case of using a standard for-loop, removing an object shifts all our remain objects, which we've yet to deal with, one position closer to the start of the associated array. However, our index goes up by one, so we skip the object that has just moved into the slot of the removed object...

for (int i = 0; i < arrayList.size(); i++) {

   if (arrayList.get(i).equals("Tweedledum")) {
      arrayList.remove(arrayList.get(i));
   }

}

The solution is to drop the index by one when you do a delete...

for (int i = 0; i < arrayList.size(); i++) {

   if (arrayList.get(i).equals("Tweedledum")) {
      arrayList.remove(arrayList.get(i));
      i--;
   }

}

If, on the other hand, you want to use a for-each loop, this won't work because it relies on the associated array length not changing as you loop. So, this won't work....

for (String person: arrayList) {

   if (person.equals("Tweedledum")) {
      arrayList.remove(person);
   }

}

It was more efficient for the people who wrote the for-each to remove the size checking. Because of this, changing the size of the associated array within a for-each loop isn't generally possible. Instead we need to copy the ArrayList, and loop through the copy, but deleting from the original ArrayList.

String[] arrayListArray = arrayList.toArray(new String[0]);

for (String person: arrayListArray) {

   if (person.equals("Tweedledum")) {
      arrayList.remove(person);
   }

}

If you didn't work that out, there's no embarrassment in that: it's a pretty tricky and off-the-wall problem, but one that's worth knowing about. If you did work it out, you can give yourself a pretty hearty pat on the back.


So here's the simplest way of constructing our class:

Alice.java

However, if you want to use a for-each loop:

Alice2.java

And, if you want to deal with generic objects, you can also do it like this:

Alice3.java


 

Can you finish this off by:

Changing the final while loop in Alice.java so it is a for loop that uses the array inside the ArrayList.