Test and fix for the ArrayList.addAll(), bug 2954.
diff --git a/libcore/luni/src/main/java/java/util/ArrayList.java b/libcore/luni/src/main/java/java/util/ArrayList.java
index 3bae372..78f9690 100644
--- a/libcore/luni/src/main/java/java/util/ArrayList.java
+++ b/libcore/luni/src/main/java/java/util/ArrayList.java
@@ -424,20 +424,16 @@
increment = 12;
}
E[] newArray = newElementArray(size + increment);
- if (location < size / 2) {
- int newFirst = newArray.length - (size + required);
- System.arraycopy(array, location, newArray, location + increment,
- size - location);
- System.arraycopy(array, firstIndex, newArray, newFirst, location);
- firstIndex = newFirst;
- lastIndex = newArray.length;
- } else {
- System.arraycopy(array, firstIndex, newArray, 0, location);
- System.arraycopy(array, location, newArray, location + required,
- size - location);
- firstIndex = 0;
- lastIndex += required;
- }
+ int newFirst = increment - required;
+ // Copy elements after location to the new array skipping inserted
+ // elements
+ System.arraycopy(array, location + firstIndex, newArray, newFirst
+ + location + required, size - location);
+ // Copy elements before location to the new array from firstIndex
+ System.arraycopy(array, firstIndex, newArray, newFirst, location);
+ firstIndex = newFirst;
+ lastIndex = size + increment;
+
array = newArray;
}
diff --git a/libcore/luni/src/test/java/org/apache/harmony/luni/tests/java/util/ArrayListTest.java b/libcore/luni/src/test/java/org/apache/harmony/luni/tests/java/util/ArrayListTest.java
index 96952a9..ab29579 100644
--- a/libcore/luni/src/test/java/org/apache/harmony/luni/tests/java/util/ArrayListTest.java
+++ b/libcore/luni/src/test/java/org/apache/harmony/luni/tests/java/util/ArrayListTest.java
@@ -8,6 +8,7 @@
import junit.framework.TestCase;
import java.util.ArrayList;
+import java.util.Arrays;
@TestTargetClass(ArrayList.class)
public class ArrayListTest extends TestCase {
@@ -34,4 +35,23 @@
assertEquals("d", blist.get(2));
}
+ @TestTargetNew(
+ level = TestLevel.PARTIAL_COMPLETE,
+ notes = "Regression test.",
+ method = "addAll",
+ args = {java.util.Collection.class}
+ )
+ public void test_growForInsert() {
+ ArrayList<Integer> arrayList = new ArrayList<Integer>();
+ arrayList.addAll(0, Arrays.asList(1, 2));
+ arrayList.addAll(2, Arrays.asList(13));
+ arrayList.addAll(0, Arrays.asList(0));
+ arrayList.addAll(3, Arrays.asList(11, 12));
+ arrayList.addAll(6, Arrays.asList(22, 23, 24, 25, 26, 27, 28, 29));
+ arrayList.addAll(6, Arrays.asList(14, 15, 16, 17, 18, 19, 20, 21));
+ arrayList.addAll(3, Arrays.asList(3, 4, 5, 6, 7, 8, 9, 10));
+ assertEquals(Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
+ 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29),
+ arrayList);
+ }
}
\ No newline at end of file