20 October 2006

List.remove

Here's a really simple one:


...
public static void main (String[] args) {
List <String> l = new ArrayList<String>();
String one = new String("one");
System.out.println(l.size());
l.add(one);
l.add(one);
System.out.println(l.size());
l.remove(one);
System.out.println(l.size());
}
...


That gets you this:


0
2
1


Well, it isn't rocket science. This isn't a Set, it is a List. And the method remove says:

Removes the first occurrence in this list of the specified element (optional operation). If this list does not contain the element, it is unchanged. More formally, removes the element with the lowest index i such that (o==null ? get(i)==null : o.equals(get(i))) (if such an element exists).


The block that does all the hard work in the ArrayList class looks like so:


for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}



So, if you want your output to look like so:

0
2
0


Change your list's remove to look like this:

while (l.remove(one));


Or better yet, use a Set.

No comments:

Post a Comment