From 26209efac2a40f60626cf8bddff7ebf87d780350 Mon Sep 17 00:00:00 2001 From: Dain Date: Fri, 6 Jul 2012 13:53:18 -0600 Subject: [PATCH] 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. --- classpath/java/util/ArrayList.java | 7 ++++--- test/List.java | 19 +++++++++++++++++++ 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/classpath/java/util/ArrayList.java b/classpath/java/util/ArrayList.java index 3935aa44ec..498d442ecb 100644 --- a/classpath/java/util/ArrayList.java +++ b/classpath/java/util/ArrayList.java @@ -131,13 +131,14 @@ public class ArrayList extends AbstractList implements java.io.Serializabl 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; diff --git a/test/List.java b/test/List.java index c7d73d93fc..c25950c525 100644 --- a/test/List.java +++ b/test/List.java @@ -145,6 +145,24 @@ public class List { } } + private static void testRemove() { + ArrayList foo = new ArrayList(2); + foo.add("Uno"); + foo.add("Dos"); + foo.add("Tres"); + foo.add("Cuatro"); + + ArrayList fooToRemove = new ArrayList(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 l = new ArrayList(); l.add(1); l.add(2); l.add(3); l.add(4); l.add(5); @@ -170,5 +188,6 @@ public class List { testIterators2(new ArrayList()); testIterators2(new LinkedList()); testGrow(); + testRemove(); } }