Files
primitive-collections/README.md
2022-08-15 16:18:50 +00:00

2.7 KiB

Java collections for primitives (currently only int) released under MIT license.

IntList and LongList are implementations of lists that store primitive integers/longs. The ints/longs are stored in an int/long array and the class takes care of growing the array as needed. You can trim the list to reduce the memory overhead. No dependencies.

The lists support the following operations:

  • add/remove elements via single and bulk operations
  • replace elements
  • sort and shuffle
  • the lists know whether or not they are sorted and can leverage that knowledge for searching (binary search), union and intersection
  • search for elements
  • union, intersection, retainIf, retainAll removeIf, removeAll
  • clear and trim are separate methods, so that the list can be re-used without having to re-allocate memory
  • stream support
  • the lists are serializable and cloneable
  • the lists are not thread-safe

How to use

The library is still considered beta. There no pre-build artifacts on Maven Central or JCenter, but you can download them from repo.lucares.org.

Example for Gradle:

apply plugin: 'maven'
repositories {
	maven { url 'https://repo.lucares.org/' }
}
dependencies {
	compile 'org.lucares:primitiveCollections:0.3'
}

Examples

IntList / LongList

An alternative to int[]/long[] that grows dynamically. The list supports a few features that are either not supported by arrays or that would be expensive to implement. The most unique feature is that the list knows if it is sorted.

isSorted()

The lists keep track of whether they are sorted or not. This makes the call to isSorted() very cheap, because we only have to return the value of a field. The drawback is that some operations are much more expensive. This affects shuffle(), as well as remove(int, int), removeIf(), removeAll(IntList) and 'retainAll()' if the list was not sorted before.

The fact that we know if a list is sorted allows us to use more efficient algorithms for union(IntList, IntList), intersection(IntList, IntList), indexOf(int), lastIndexOf() and uniq().

final IntList list = IntList.of(1, 3, 5);
System.out.println(list + " is sorted: " + list.isSorted());

list.insert(2, 7);
System.out.println(list + " is sorted: " + list.isSorted());

list.sort();
System.out.println(list + " is sorted: " + list.isSorted());

Running this program gives the following output:

[1, 3, 5] is sorted: true
[1, 3, 7, 5] is sorted: false
[1, 3, 5, 7] is sorted: true

The fact that we know if a list is sorted allows us to use more efficient algorithms for union(IntList, IntList), intersection(IntList, IntList), indexOf(int), lastIndexOf() and uniq().