add replaceAll

This commit is contained in:
2017-11-09 09:33:19 +01:00
parent 6df2553fae
commit db6ca1387d
3 changed files with 49 additions and 1 deletions

View File

@@ -27,7 +27,6 @@ public final class IntList implements Serializable, Cloneable {
// TODO add replace
// TODO add lastIndexOf
// TODO remove bounds checks that are handled by java, e.g. negative indices
// TODO toString
private static final long serialVersionUID = 2622570032686034909L;
@@ -229,6 +228,20 @@ public final class IntList implements Serializable, Cloneable {
index = index - (toIndex - fromIndex);
}
/**
* Replaces all values in the list by applying {@code operator}.
*
* @param operator
* the operator
*/
public void replaceAll(final UnaryIntOperator operator) {
final int size = index;
for (int i = 0; i < size; i++) {
data[i] = operator.apply(data[i]);
}
}
/**
* Returns the element at position {@code pos}.
*

View File

@@ -0,0 +1,18 @@
package org.lucares.collections;
import java.util.function.Function;
/**
* Represents an operation that maps an int to an int. This is a specialization
* of {@link Function} for a primitive integer.
*/
public interface UnaryIntOperator {
/**
* Applies the operation to the integer
*
* @param value
* the input value
* @return the result of the operation
*/
int apply(int value);
}

View File

@@ -615,4 +615,21 @@ public class IntListTest {
Assert.assertEquals(list.get(list.indexOf(2, 2)), 2);
Assert.assertEquals(list.get(list.indexOf(2, 3)), 2);
}
@Test
public void replaceAll() {
final IntList list = new IntList();
list.addAll(1, 2, 3);
list.replaceAll(i -> i * 2);
Assert.assertArrayEquals(new int[] { 2, 4, 6 }, list.toArray());
}
@Test
public void replaceAllOnEmptyList() {
final IntList list = new IntList();
list.replaceAll(i -> i * 3);
Assert.assertArrayEquals(new int[0], list.toArray());
}
}