Skip to content

Commit

Permalink
Merge pull request #135 from karypid/karypid
Browse files Browse the repository at this point in the history
Add unordered remove to primitive collection
  • Loading branch information
mjpt777 authored Mar 9, 2018
2 parents d61f6fc + 46e8fe1 commit a4824ed
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
30 changes: 30 additions & 0 deletions agrona/src/main/java/org/agrona/collections/IntArrayList.java
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,36 @@ public Integer remove(
return value;
}

/**
* Removes element at index, but instead of copying all elements to the
* left, moves into the same slot the last element. This avoids the copy
* costs, but spoils the list order. If index is the last element it is just
* removed.
*
* @param index
* of the element to be removed.
* @return the existing value at this index.
* @throws IndexOutOfBoundsException
* if index is out of bounds.
*/
public int fastUnorderedRemove(
@DoNotSub final int index)
{
checkIndex(index);

final int value = elements[index];

@DoNotSub final int moveCount = size - index - 1;
if (moveCount > 0)
{
elements[index] = elements[size - 1];
}

size--;

return value;
}

/**
* Remove the first instance of a value if found in the list.
*
Expand Down
12 changes: 12 additions & 0 deletions agrona/src/test/java/org/agrona/collections/IntArrayListTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,18 @@ public void shouldRemoveAtIndex()
assertThat(list.getInt(10), is(11));
}

@Test
public void shouldFastRemoveUnorderedAtIndex()
{
final int count = 20;
IntStream.range(0, count).forEachOrdered(list::addInt);

assertThat(list.fastUnorderedRemove(10), is(10));

assertThat(list.size(), is(count - 1));
assertThat(list.getInt(10), is(19));
}

@Test
public void shouldForEachOrderedInt()
{
Expand Down

0 comments on commit a4824ed

Please sign in to comment.