I have an ArrayList, which includes a number of items I want to remove. I have the ids of the items to remove stored in another list. Figured the following code should work trivially, but for some reason, the remove() calls are returning a false value:
ArrayList<Integer> toRemove = new ArrayList<Integer>();
ArrayList<JCheckBox> al = new ArrayList<JCheckBox>();
/* Code that adds a bunch of items to al, and a few integers to toRemove */
System.out.println("Size before removing: " + al.size());
for (int i = toRemove.size() - 1; i >= 0; i--) {
System.out.println("Removing id: " + toRemove.get(i) + ": ");
System.out.println(al.get(toRemove.get(i)));
System.out.println(al.remove(toRemove.get(i)));
}
System.out.println("Size after removing: " + al.size());
I’d get it if the get() call also returned a false value, but it does actually return the object in question. What am I missing here?
The output of the code above:
Size before removing: 3
Removing id: 2:
javax.swing.JCheckBox[...]
false
Size after removing: 3
My guess is you are having a problem with the fact that
remove()is overloaded with bothintandObject, whileget()only takes anint. Tryremove(toRemove.get(i).intValue()).remove(Object)fromAbstractCollectionwill search through the list and remove the given object, which won’t be there because you are sending it anIntegerand the list only hasJCheckBoxs. You are trying to callremove(int), but because you are giving it anInteger, the Object overload is called instead. By converting theIntegerto anint, you avoid this problemAlso, can you always be sure the Id in toRemove always equals the index? If toRemove is not in greatest to least order, it won’t be.