add indexOf(value) and indexOf(value, offset)

This commit is contained in:
2017-10-13 17:02:01 +02:00
parent cbe468cae8
commit 6df2553fae
2 changed files with 65 additions and 1 deletions

View File

@@ -26,7 +26,6 @@ public final class IntList implements Serializable, Cloneable {
// TODO add removeRange // TODO add removeRange
// TODO add replace // TODO add replace
// TODO add lastIndexOf // TODO add lastIndexOf
// TODO add indexOf
// TODO remove bounds checks that are handled by java, e.g. negative indices // TODO remove bounds checks that are handled by java, e.g. negative indices
// TODO toString // TODO toString
@@ -352,6 +351,39 @@ public final class IntList implements Serializable, Cloneable {
return StreamSupport.intStream(spliterator, true); return StreamSupport.intStream(spliterator, true);
} }
/**
* Returns the index of the first occurrence of {@code value}, or -1 if it does
* not exist.
*
* @param value
* the value
* @return the index, or -1
*/
public int indexOf(final int value) {
return indexOf(value, 0);
}
/**
* Returns the index of the first occurrence of {@code value} starting at the
* {@code offset}'s element, or -1 if it does not exist.
*
* @param value
* the value
* @param offset
* the offset
* @return the index, or -1
* @throws ArrayIndexOutOfBoundsException
* if offset is negative, or larger than the size of the list
*/
public int indexOf(final int value, final int offset) {
for (int i = offset; i < index; i++) {
if (data[i] == value) {
return i;
}
}
return -1;
}
@Override @Override
public String toString() { public String toString() {

View File

@@ -583,4 +583,36 @@ public class IntListTest {
Assert.assertNotEquals("should use parallelism during computation", processingOrder.toString(), Assert.assertNotEquals("should use parallelism during computation", processingOrder.toString(),
list.toString()); list.toString());
} }
@Test
public void testIndexOf() {
final IntList list = new IntList();
Assert.assertEquals(-1, list.indexOf(0));
list.add(1);
Assert.assertEquals(-1, list.indexOf(0));
Assert.assertEquals(0, list.indexOf(1));
list.add(2);
Assert.assertEquals(-1, list.indexOf(0));
Assert.assertEquals(0, list.indexOf(1));
Assert.assertEquals(1, list.indexOf(2));
}
@Test
public void testIndexOfWithOffset() {
final IntList list = new IntList();
list.addAll(0, 2, 0, 2);
Assert.assertEquals(1, list.indexOf(2, 0));
Assert.assertEquals(1, list.indexOf(2, 1));
Assert.assertEquals(3, list.indexOf(2, 2));
Assert.assertEquals(3, list.indexOf(2, 3));
Assert.assertEquals(-1, list.indexOf(2, 4));
// indexed returned by indexOf() are consistent with get()
Assert.assertEquals(list.get(list.indexOf(2, 0)), 2);
Assert.assertEquals(list.get(list.indexOf(2, 1)), 2);
Assert.assertEquals(list.get(list.indexOf(2, 2)), 2);
Assert.assertEquals(list.get(list.indexOf(2, 3)), 2);
}
} }