Permalink
Browse files

Fix an off-by-1 error in the remove method.

The change to only grow the array when the capacity has been reached
exposed a bug in the remove method when shifting the array elements.
  • Loading branch information...
1 parent 8706b6a commit 26209efac2a40f60626cf8bddff7ebf87d780350 Dain committed with dicej Jul 6, 2012
Showing with 23 additions and 3 deletions.
  1. +4 −3 classpath/java/util/ArrayList.java
  2. +19 −0 test/List.java
View
7 classpath/java/util/ArrayList.java
@@ -131,13 +131,14 @@ public T set(int index, T element) {
public T remove(int index) {
T v = get(index);
- if (index == size - 1) {
+ int newSize = size - 1;
+
+ if (index == newSize) {
array[index] = null;
} else {
- System.arraycopy(array, index + 1, array, index, size - index);
+ System.arraycopy(array, index + 1, array, index, newSize - index);
}
- int newSize = size - 1;
shrink(newSize);
size = newSize;
View
19 test/List.java
@@ -145,6 +145,24 @@ private static void testGrow() {
}
}
+ private static void testRemove() {
+ ArrayList<String> foo = new ArrayList<String>(2);
+ foo.add("Uno");
+ foo.add("Dos");
+ foo.add("Tres");
+ foo.add("Cuatro");
+
+ ArrayList<String> fooToRemove = new ArrayList<String>(2);
+ fooToRemove.add(foo.get(0));
+ fooToRemove.add(foo.get(1));
+
+ for (String s : fooToRemove) {
+ foo.remove(s);
+ }
+
+ expect(foo.size() == 2);
+ }
+
public static void main(String args[]) {
ArrayList<Integer> l = new ArrayList<Integer>();
l.add(1); l.add(2); l.add(3); l.add(4); l.add(5);
@@ -170,5 +188,6 @@ public static void main(String args[]) {
testIterators2(new ArrayList());
testIterators2(new LinkedList());
testGrow();
+ testRemove();
}
}

0 comments on commit 26209ef

Please sign in to comment.