add method retainAll

This commit is contained in:
2017-11-10 10:03:10 +01:00
parent 81e1d1f131
commit a59db6cfe8
2 changed files with 54 additions and 4 deletions

View File

@@ -261,6 +261,26 @@ public final class IntList implements Serializable, Cloneable {
index = insertPosition;
}
/**
* Retains all elements contained in the specified list.
*
* @param retain
* the elements to retain
*/
public void retainAll(final IntList retain) {
final int size = index;
int insertPosition = 0;
for (int i = 0; i < size; i++) {
final int current = data[i];
if (retain.indexOf(current) >= 0) {
// keep current element
data[insertPosition] = current;
insertPosition++;
}
}
index = insertPosition;
}
/**
* Replaces all values in the list by applying {@code operator}.
*

View File

@@ -626,7 +626,7 @@ public class IntListTest {
}
@Test
public void replaceAllOnEmptyList() {
public void testReplaceAllOnEmptyList() {
final IntList list = new IntList();
list.replaceAll(i -> i * 3);
@@ -634,7 +634,7 @@ public class IntListTest {
}
@Test
public void removeAll() {
public void testRemoveAll() {
final IntList list = IntList.of(-2, -1, 0, 1, 2, 3, 4, 5, 6);
final IntList remove = IntList.of(-1, 2, 4, 5);
@@ -644,7 +644,7 @@ public class IntListTest {
}
@Test
public void removeEmptyList() {
public void testRemoveEmptyList() {
final IntList list = IntList.of(1, 2, 3, 4, 5, 6);
final IntList remove = new IntList();
@@ -654,7 +654,7 @@ public class IntListTest {
}
@Test
public void removeAllFromEmptyList() {
public void testRemoveAllFromEmptyList() {
final IntList list = new IntList();
final IntList remove = IntList.of(1);
@@ -662,4 +662,34 @@ public class IntListTest {
Assert.assertArrayEquals(new int[] {}, list.toArray());
Assert.assertEquals(0, list.size());
}
@Test
public void testRetainAll() {
final IntList list = IntList.of(-2, -1, 0, 1, 2, 3, 4, 5, 6);
final IntList retain = IntList.of(-1, 2, 4, 5, 99);
list.retainAll(retain);
Assert.assertArrayEquals(new int[] { -1, 2, 4, 5 }, list.toArray());
Assert.assertArrayEquals(new int[] { -1, 2, 4, 5, 99 }, retain.toArray());
}
@Test
public void testRetainAllOnEmptyList() {
final IntList list = IntList.of();
final IntList retain = IntList.of(-1, 2, 4, 5, 99);
list.retainAll(retain);
Assert.assertArrayEquals(new int[] {}, list.toArray());
Assert.assertArrayEquals(new int[] { -1, 2, 4, 5, 99 }, retain.toArray());
}
@Test
public void testRetainAllFromEmptyList() {
final IntList list = IntList.of(-2, -1, 0, 1, 2);
final IntList retain = IntList.of();
list.retainAll(retain);
Assert.assertArrayEquals(new int[] {}, list.toArray());
Assert.assertArrayEquals(new int[] {}, retain.toArray());
}
}