diff --git a/README.md b/README.md index 0a32131..109149d 100644 --- a/README.md +++ b/README.md @@ -25,7 +25,7 @@ executed concurrently also. ## Gradle ```groovy -compile group: 'com.github.akurilov', name: 'java-concurrent', version: '1.1.4' +compile group: 'com.github.akurilov', name: 'java-concurrent', version: '2.0.1' ``` ## Implementing Basic Coroutine diff --git a/src/main/java/it/unimi/dsi/fastutil/Arrays.java b/src/main/java/it/unimi/dsi/fastutil/Arrays.java deleted file mode 100644 index 99c5923..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/Arrays.java +++ /dev/null @@ -1,438 +0,0 @@ -package it.unimi.dsi.fastutil; - -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import it.unimi.dsi.fastutil.Swapper; -import it.unimi.dsi.fastutil.ints.IntComparator; - -import java.util.ArrayList; -import java.util.concurrent.ForkJoinPool; -import java.util.concurrent.RecursiveAction; - -/** A class providing static methods and objects that do useful things with arrays. - * - *

In addition to commodity methods, this class contains {@link Swapper}-based implementations - * of {@linkplain #quickSort(int, int, IntComparator, Swapper) quicksort} and of - * a stable, in-place {@linkplain #mergeSort(int, int, IntComparator, Swapper) mergesort}. These - * generic sorting methods can be used to sort any kind of list, but they find their natural - * usage, for instance, in sorting arrays in parallel. - * - * @see it.unimi.dsi.fastutil.Arrays - */ - -public class Arrays { - - private Arrays() {} - - /** This is a safe value used by {@link ArrayList} (as of Java 7) to avoid - * throwing {@link OutOfMemoryError} on some JVMs. We adopt the same value. */ - public static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; - - /** Ensures that a range given by its first (inclusive) and last (exclusive) elements fits an array of given length. - * - *

This method may be used whenever an array range check is needed. - * - * @param arrayLength an array length. - * @param from a start index (inclusive). - * @param to an end index (inclusive). - * @throws IllegalArgumentException if from is greater than to. - * @throws ArrayIndexOutOfBoundsException if from or to are greater than arrayLength or negative. - */ - public static void ensureFromTo( final int arrayLength, final int from, final int to ) { - if ( from < 0 ) throw new ArrayIndexOutOfBoundsException( "Start index (" + from + ") is negative" ); - if ( from > to ) throw new IllegalArgumentException( "Start index (" + from + ") is greater than end index (" + to + ")" ); - if ( to > arrayLength ) throw new ArrayIndexOutOfBoundsException( "End index (" + to + ") is greater than array length (" + arrayLength + ")" ); - } - - /** Ensures that a range given by an offset and a length fits an array of given length. - * - *

This method may be used whenever an array range check is needed. - * - * @param arrayLength an array length. - * @param offset a start index for the fragment - * @param length a length (the number of elements in the fragment). - * @throws IllegalArgumentException if length is negative. - * @throws ArrayIndexOutOfBoundsException if offset is negative or offset+length is greater than arrayLength. - */ - public static void ensureOffsetLength( final int arrayLength, final int offset, final int length ) { - if ( offset < 0 ) throw new ArrayIndexOutOfBoundsException( "Offset (" + offset + ") is negative" ); - if ( length < 0 ) throw new IllegalArgumentException( "Length (" + length + ") is negative" ); - if ( offset + length > arrayLength ) throw new ArrayIndexOutOfBoundsException( "Last index (" + ( offset + length ) + ") is greater than array length (" + arrayLength + ")" ); - } - - /** - * Transforms two consecutive sorted ranges into a single sorted range. The initial ranges are - * [first..middle) and [middle..last), and the resulting range is - * [first..last). Elements in the first input range will precede equal elements in - * the second. - */ - private static void inPlaceMerge( final int from, int mid, final int to, final IntComparator comp, final Swapper swapper ) { - if ( from >= mid || mid >= to ) return; - if ( to - from == 2 ) { - if ( comp.compare( mid, from ) < 0 ) swapper.swap( from, mid ); - return; - } - - int firstCut; - int secondCut; - - if ( mid - from > to - mid ) { - firstCut = from + ( mid - from ) / 2; - secondCut = lowerBound( mid, to, firstCut, comp ); - } - else { - secondCut = mid + ( to - mid ) / 2; - firstCut = upperBound( from, mid, secondCut, comp ); - } - - int first2 = firstCut; - int middle2 = mid; - int last2 = secondCut; - if ( middle2 != first2 && middle2 != last2 ) { - int first1 = first2; - int last1 = middle2; - while ( first1 < --last1 ) - swapper.swap( first1++, last1 ); - first1 = middle2; - last1 = last2; - while ( first1 < --last1 ) - swapper.swap( first1++, last1 ); - first1 = first2; - last1 = last2; - while ( first1 < --last1 ) - swapper.swap( first1++, last1 ); - } - - mid = firstCut + ( secondCut - mid ); - inPlaceMerge( from, firstCut, mid, comp, swapper ); - inPlaceMerge( mid, secondCut, to, comp, swapper ); - } - - /** - * Performs a binary search on an already-sorted range: finds the first position where an - * element can be inserted without violating the ordering. Sorting is by a user-supplied - * comparison function. - * - * @param from the index of the first element (inclusive) to be included in the binary search. - * @param to the index of the last element (exclusive) to be included in the binary search. - * @param pos the position of the element to be searched for. - * @param comp the comparison function. - * @return the largest index i such that, for every j in the range [first..i), - * comp.compare(j, pos) is true. - */ - private static int lowerBound( int from, final int to, final int pos, final IntComparator comp ) { - // if (comp==null) throw new NullPointerException(); - int len = to - from; - while ( len > 0 ) { - int half = len / 2; - int middle = from + half; - if ( comp.compare( middle, pos ) < 0 ) { - from = middle + 1; - len -= half + 1; - } - else { - len = half; - } - } - return from; - } - - - /** - * Performs a binary search on an already sorted range: finds the last position where an element - * can be inserted without violating the ordering. Sorting is by a user-supplied comparison - * function. - * - * @param from the index of the first element (inclusive) to be included in the binary search. - * @param to the index of the last element (exclusive) to be included in the binary search. - * @param pos the position of the element to be searched for. - * @param comp the comparison function. - * @return The largest index i such that, for every j in the range [first..i), - * comp.compare(pos, j) is false. - */ - private static int upperBound( int from, final int mid, final int pos, final IntComparator comp ) { - // if (comp==null) throw new NullPointerException(); - int len = mid - from; - while ( len > 0 ) { - int half = len / 2; - int middle = from + half; - if ( comp.compare( pos, middle ) < 0 ) { - len = half; - } - else { - from = middle + 1; - len -= half + 1; - } - } - return from; - } - - /** - * Returns the index of the median of the three indexed chars. - */ - private static int med3( final int a, final int b, final int c, final IntComparator comp ) { - int ab = comp.compare( a, b ); - int ac = comp.compare( a, c ); - int bc = comp.compare( b, c ); - return ( ab < 0 ? - ( bc < 0 ? b : ac < 0 ? c : a ) : - ( bc > 0 ? b : ac > 0 ? c : a ) ); - } - - private static final int MERGESORT_NO_REC = 16; - - /** Sorts the specified range of elements using the specified swapper and according to the order induced by the specified - * comparator using mergesort. - * - *

This sort is guaranteed to be stable: equal elements will not be reordered as a result - * of the sort. The sorting algorithm is an in-place mergesort that is significantly slower than a - * standard mergesort, as its running time is O(n (log n)2), but it does not allocate additional memory; as a result, it can be - * used as a generic sorting algorithm. - * - * @param from the index of the first element (inclusive) to be sorted. - * @param to the index of the last element (exclusive) to be sorted. - * @param c the comparator to determine the order of the generic data (arguments are positions). - * @param swapper an object that knows how to swap the elements at any two positions. - */ - public static void mergeSort( final int from, final int to, final IntComparator c, final Swapper swapper ) { - /* - * We retain the same method signature as quickSort. Given only a comparator and swapper we - * do not know how to copy and move elements from/to temporary arrays. Hence, in contrast to - * the JDK mergesorts this is an "in-place" mergesort, i.e. does not allocate any temporary - * arrays. A non-inplace mergesort would perhaps be faster in most cases, but would require - * non-intuitive delegate objects... - */ - final int length = to - from; - - // Insertion sort on smallest arrays - if ( length < MERGESORT_NO_REC ) { - for ( int i = from; i < to; i++ ) { - for ( int j = i; j > from && ( c.compare( j - 1, j ) > 0 ); j-- ) { - swapper.swap( j, j - 1 ); - } - } - return; - } - - // Recursively sort halves - int mid = ( from + to ) >>> 1; - mergeSort( from, mid, c, swapper ); - mergeSort( mid, to, c, swapper ); - - // If list is already sorted, nothing left to do. This is an - // optimization that results in faster sorts for nearly ordered lists. - if ( c.compare( mid - 1, mid ) <= 0 ) return; - - // Merge sorted halves - inPlaceMerge( from, mid, to, c, swapper ); - } - - /** Swaps two sequences of elements using a provided swapper. - * - * @param swapper the swapper. - * @param a a position in {@code x}. - * @param b another position in {@code x}. - * @param n the number of elements to exchange starting at {@code a} and {@code b}. - */ - protected static void swap( final Swapper swapper, int a, int b, final int n ) { - for ( int i = 0; i < n; i++, a++, b++ ) swapper.swap( a, b ); - } - - private static final int QUICKSORT_NO_REC = 16; - private static final int PARALLEL_QUICKSORT_NO_FORK = 8192; - private static final int QUICKSORT_MEDIAN_OF_9 = 128; - - protected static class ForkJoinGenericQuickSort extends RecursiveAction { - private static final long serialVersionUID = 1L; - private final int from; - private final int to; - private final IntComparator comp; - private final Swapper swapper; - - public ForkJoinGenericQuickSort( final int from, final int to, final IntComparator comp, final Swapper swapper ) { - this.from = from; - this.to = to; - this.comp = comp; - this.swapper = swapper; - } - - @Override - protected void compute() { - final int len = to - from; - if ( len < PARALLEL_QUICKSORT_NO_FORK ) { - quickSort( from, to, comp, swapper ); - return; - } - // Choose a partition element, v - int m = from + len / 2; - int l = from; - int n = to - 1; - int s = len / 8; - l = med3( l, l + s, l + 2 * s, comp ); - m = med3( m - s, m, m + s, comp ); - n = med3( n - 2 * s, n - s, n, comp ); - m = med3( l, m, n, comp ); - // Establish Invariant: v* (v)* v* - int a = from, b = a, c = to - 1, d = c; - while ( true ) { - int comparison; - while ( b <= c && ( ( comparison = comp.compare( b, m ) ) <= 0 ) ) { - if ( comparison == 0 ) { - // Fix reference to pivot if necessary - if ( a == m ) m = b; - else if ( b == m ) m = a; - swapper.swap( a++, b ); - } - b++; - } - while ( c >= b && ( ( comparison = comp.compare( c, m ) ) >= 0 ) ) { - if ( comparison == 0 ) { - // Fix reference to pivot if necessary - if ( c == m ) m = d; - else if ( d == m ) m = c; - swapper.swap( c, d-- ); - } - c--; - } - if ( b > c ) break; - // Fix reference to pivot if necessary - if ( b == m ) m = d; - else if ( c == m ) m = c; - swapper.swap( b++, c-- ); - } - - // Swap partition elements back to middle - s = Math.min( a - from, b - a ); - swap( swapper, from, b - s, s ); - s = Math.min( d - c, to - d - 1 ); - swap( swapper, b, to - s, s ); - - // Recursively sort non-partition-elements - int t; - s = b - a; - t = d - c; - if ( s > 1 && t > 1 ) invokeAll( new ForkJoinGenericQuickSort( from, from + s, comp, swapper ), new ForkJoinGenericQuickSort( to - t, to, comp, swapper ) ); - else if ( s > 1 ) invokeAll( new ForkJoinGenericQuickSort( from, from + s, comp, swapper ) ); - else invokeAll( new ForkJoinGenericQuickSort( to - t, to, comp, swapper ) ); - } - } - - /** Sorts the specified range of elements using the specified swapper and according to the order induced by the specified - * comparator using a parallel quicksort. - * - *

The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley and M. Douglas - * McIlroy, “Engineering a Sort Function”, Software: Practice and Experience, 23(11), pages - * 1249−1265, 1993. - * - *

This implementation uses a {@link ForkJoinPool} executor service with {@link Runtime#availableProcessors()} parallel threads. - * - * @param from the index of the first element (inclusive) to be sorted. - * @param to the index of the last element (exclusive) to be sorted. - * @param comp the comparator to determine the order of the generic data. - * @param swapper an object that knows how to swap the elements at any two positions. - * - */ - public static void parallelQuickSort( final int from, final int to, final IntComparator comp, final Swapper swapper ) { - final ForkJoinPool pool = new ForkJoinPool( Runtime.getRuntime().availableProcessors() ); - pool.invoke( new ForkJoinGenericQuickSort( from, to, comp, swapper ) ); - pool.shutdown(); - } - - - /** Sorts the specified range of elements using the specified swapper and according to the order induced by the specified - * comparator using parallel quicksort. - * - *

The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley and M. Douglas - * McIlroy, “Engineering a Sort Function”, Software: Practice and Experience, 23(11), pages - * 1249−1265, 1993. - * - *

This implementation uses a {@link ForkJoinPool} executor service with {@link Runtime#availableProcessors()} parallel threads. - * - * @param from the index of the first element (inclusive) to be sorted. - * @param to the index of the last element (exclusive) to be sorted. - * @param comp the comparator to determine the order of the generic data. - * @param swapper an object that knows how to swap the elements at any two positions. - * - */ - public static void quickSort( final int from, final int to, final IntComparator comp, final Swapper swapper ) { - final int len = to - from; - // Insertion sort on smallest arrays - if ( len < QUICKSORT_NO_REC ) { - for ( int i = from; i < to; i++ ) - for ( int j = i; j > from && ( comp.compare( j - 1, j ) > 0 ); j-- ) { - swapper.swap( j, j - 1 ); - } - return; - } - - // Choose a partition element, v - int m = from + len / 2; // Small arrays, middle element - int l = from; - int n = to - 1; - if ( len > QUICKSORT_MEDIAN_OF_9 ) { // Big arrays, pseudomedian of 9 - int s = len / 8; - l = med3( l, l + s, l + 2 * s, comp ); - m = med3( m - s, m, m + s, comp ); - n = med3( n - 2 * s, n - s, n, comp ); - } - m = med3( l, m, n, comp ); // Mid-size, med of 3 - // int v = x[m]; - - int a = from; - int b = a; - int c = to - 1; - // Establish Invariant: v* (v)* v* - int d = c; - while ( true ) { - int comparison; - while ( b <= c && ( ( comparison = comp.compare( b, m ) ) <= 0 ) ) { - if ( comparison == 0 ) { - // Fix reference to pivot if necessary - if ( a == m ) m = b; - else if ( b == m ) m = a; - swapper.swap( a++, b ); - } - b++; - } - while ( c >= b && ( ( comparison = comp.compare( c, m ) ) >= 0 ) ) { - if ( comparison == 0 ) { - // Fix reference to pivot if necessary - if ( c == m ) m = d; - else if ( d == m ) m = c; - swapper.swap( c, d-- ); - } - c--; - } - if ( b > c ) break; - // Fix reference to pivot if necessary - if ( b == m ) m = d; - else if ( c == m ) m = c; - swapper.swap( b++, c-- ); - } - - // Swap partition elements back to middle - int s; - s = Math.min( a - from, b - a ); - swap( swapper, from, b - s, s ); - s = Math.min( d - c, to - d - 1 ); - swap( swapper, b, to - s, s ); - - // Recursively sort non-partition-elements - if ( ( s = b - a ) > 1 ) quickSort( from, from + s, comp, swapper ); - if ( ( s = d - c ) > 1 ) quickSort( to - s, to, comp, swapper ); - } -} diff --git a/src/main/java/it/unimi/dsi/fastutil/BidirectionalIterator.java b/src/main/java/it/unimi/dsi/fastutil/BidirectionalIterator.java deleted file mode 100644 index 0a7b3b4..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/BidirectionalIterator.java +++ /dev/null @@ -1,55 +0,0 @@ -package it.unimi.dsi.fastutil; - -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -import java.util.Iterator; -import java.util.ListIterator; - -/** A bidirectional {@link Iterator}. - * - *

This kind of iterator is essentially a {@link ListIterator} that - * does not support {@link ListIterator#previousIndex()} and {@link - * ListIterator#nextIndex()}. It is useful for those maps that can easily - * provide bidirectional iteration, but provide no index. - * - *

Note that iterators returned by fastutil classes are more - * specific, and support skipping. This class serves the purpose of organising - * in a cleaner way the relationships between various iterators. - * - * @see Iterator - * @see ListIterator - */ - -public interface BidirectionalIterator extends Iterator { - - /** Returns the previous element from the collection. - * - * @return the previous element from the collection. - * @see ListIterator#previous() - */ - - K previous(); - - /** Returns whether there is a previous element. - * - * @return whether there is a previous element. - * @see ListIterator#hasPrevious() - */ - - boolean hasPrevious(); -} diff --git a/src/main/java/it/unimi/dsi/fastutil/Function.java b/src/main/java/it/unimi/dsi/fastutil/Function.java deleted file mode 100644 index 6dfff44..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/Function.java +++ /dev/null @@ -1,101 +0,0 @@ -package it.unimi.dsi.fastutil; - -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -/** A function mapping keys into values. - * - *

Instances of this class represent functions: the main difference with {@link java.util.Map} - * is that functions do not in principle allow enumeration of their domain or range. The need for - * this interface lies in the existence of several highly optimized implementations of - * functions (e.g., minimal perfect hashes) which do not actually store their domain or range explicitly. - * In case the domain is known, {@link #containsKey(Object)} can be used to perform membership queries. - * - *

The choice of naming all methods exactly as in {@link java.util.Map} makes it possible - * for all type-specific maps to extend type-specific functions (e.g., {@link it.unimi.dsi.fastutil.ints.Int2IntMap} - * extends {@link it.unimi.dsi.fastutil.ints.Int2IntFunction}). However, {@link #size()} is allowed to return -1 to denote - * that the number of keys is not available (e.g., in the case of a string hash function). - * - - * can also set its default return value. - * - *

Warning: Equality of functions is not specified - * by contract, and it will usually be by reference, as there is no way to enumerate the keys - * and establish whether two functions represent the same mathematical entity. - * - * @see java.util.Map - */ - -public interface Function { - - /** Associates the specified value with the specified key in this function (optional operation). - * - * @param key the key. - * @param value the value. - * @return the old value, or null if no value was present for the given key. - * @see java.util.Map#put(Object,Object) - */ - - V put(K key, V value); - - /** Returns the value associated by this function to the specified key. - * - * @param key the key. - * @return the corresponding value, or null if no value was present for the given key. - * @see java.util.Map#get(Object) - */ - - V get(Object key); - - /** Returns true if this function contains a mapping for the specified key. - * - *

Note that for some kind of functions (e.g., hashes) this method - * will always return true. - * - * @param key the key. - * @return true if this function associates a value to key. - * @see java.util.Map#containsKey(Object) - */ - - boolean containsKey(Object key); - - /** Removes this key and the associated value from this function if it is present (optional operation). - * - * @param key the key. - * @return the old value, or null if no value was present for the given key. - * @see java.util.Map#remove(Object) - */ - - V remove(Object key); - - /** Returns the intended number of keys in this function, or -1 if no such number exists. - * - *

Most function implementations will have some knowledge of the intended number of keys - * in their domain. In some cases, however, this might not be possible. - * - * @return the intended number of keys in this function, or -1 if that number is not available. - */ - int size(); - - /** Removes all associations from this function (optional operation). - * - * @see java.util.Map#clear() - */ - - void clear(); - -} diff --git a/src/main/java/it/unimi/dsi/fastutil/Hash.java b/src/main/java/it/unimi/dsi/fastutil/Hash.java deleted file mode 100644 index 1ef24f1..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/Hash.java +++ /dev/null @@ -1,173 +0,0 @@ -package it.unimi.dsi.fastutil; - -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -/** Basic data for all hash-based classes. - * - *

Historical note

- * - *

Warning: the following comments are here for historical reasons, - * and apply just to the double hash classes that can be optionally generated. - * The standard fastutil distribution since 6.1.0 uses linear-probing hash - * tables, and tables are always sized as powers of two. - * - *

The classes in fastutil are built around open-addressing hashing - * implemented via double hashing. Following Knuth's suggestions in the third volume of The Art of Computer - * Programming, we use for the table size a prime p such that - * p-2 is also prime. In this way hashing is implemented with modulo p, - * and secondary hashing with modulo p-2. - * - *

Entries in a table can be in three states: {@link #FREE}, {@link #OCCUPIED} or {@link #REMOVED}. - * The naive handling of removed entries requires that you search for a free entry as if they were occupied. However, - * fastutil implements two useful optimizations, based on the following invariant: - *

- * Let i0, i1, …, ip-1 be - * the permutation of the table indices induced by the key k, that is, i0 is the hash - * of k and the following indices are obtained by adding (modulo p) the secondary hash plus one. - * If there is a {@link #OCCUPIED} entry with key k, its index in the sequence above comes before - * the indices of any {@link #REMOVED} entries with key k. - *
- * - *

When we search for the key k we scan the entries in the - * sequence i0, i1, …, - * ip-1 and stop when k is found, - * when we finished the sequence or when we find a {@link #FREE} entry. Note - * that the correctness of this procedure it is not completely trivial. Indeed, - * when we stop at a {@link #REMOVED} entry with key k we must rely - * on the invariant to be sure that no {@link #OCCUPIED} entry with the same - * key can appear later. If we insert and remove frequently the same entries, - * this optimization can be very effective (note, however, that when using - * objects as keys or values deleted entries are set to a special fixed value to - * optimize garbage collection). - * - *

Moreover, during the probe we keep the index of the first {@link #REMOVED} entry we meet. - * If we actually have to insert a new element, we use that - * entry if we can, thus avoiding to pollute another {@link #FREE} entry. Since this position comes - * a fortiori before any {@link #REMOVED} entries with the same key, we are also keeping the invariant true. - */ - -public interface Hash { - - /** The initial default size of a hash table. */ - final public int DEFAULT_INITIAL_SIZE = 16; - /** The default load factor of a hash table. */ - final public float DEFAULT_LOAD_FACTOR = .75f; - /** The load factor for a (usually small) table that is meant to be particularly fast. */ - final public float FAST_LOAD_FACTOR = .5f; - /** The load factor for a (usually very small) table that is meant to be extremely fast. */ - final public float VERY_FAST_LOAD_FACTOR = .25f; - - /** A generic hash strategy. - * - - - * using arbitrary functions, a typical example being that of {@linkplain - * it.unimi.dsi.fastutil.ints.IntArrays#HASH_STRATEGY arrays}. Of course, - * one has to compare objects for equality consistently with the chosen - * function. A hash strategy, thus, specifies an {@linkplain - * #equals(Object,Object) equality method} and a {@linkplain - * #hashCode(Object) hash function}, with the obvious property that - * equal objects must have the same hash code. - * - *

Note that the {@link #equals(Object,Object) equals()} method of a strategy must - * be able to handle null, too. - */ - - public interface Strategy { - - /** Returns the hash code of the specified object with respect to this hash strategy. - * - * @param o an object (or null). - * @return the hash code of the given object with respect to this hash strategy. - */ - - public int hashCode(K o); - - /** Returns true if the given objects are equal with respect to this hash strategy. - * - * @param a an object (or null). - * @param b another object (or null). - * @return true if the two specified objects are equal with respect to this hash strategy. - */ - public boolean equals(K a, K b); - } - - /** The default growth factor of a hash table. */ - final public int DEFAULT_GROWTH_FACTOR = 16; - /** The state of a free hash table entry. */ - final public byte FREE = 0; - /** The state of a occupied hash table entry. */ - final public byte OCCUPIED = -1; - /** The state of a hash table entry freed by a deletion. */ - final public byte REMOVED = 1; - - /** A list of primes to be used as table sizes. The i-th element is - * the largest prime p smaller than 2(i+28)/16 - * and such that p-2 is also prime (or 1, for the first few entries). */ - - final public int PRIMES[] = { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 5, 5, 5, 5, 5, 5, 7, 7, 7, - 7, 7, 7, 7, 7, 7, 7, 7, 13, 13, 13, 13, 13, 13, 13, 13, 19, 19, 19, 19, 19, - 19, 19, 19, 19, 19, 19, 19, 31, 31, 31, 31, 31, 31, 31, 43, 43, 43, 43, 43, - 43, 43, 43, 61, 61, 61, 61, 61, 73, 73, 73, 73, 73, 73, 73, 103, 103, 109, - 109, 109, 109, 109, 139, 139, 151, 151, 151, 151, 181, 181, 193, 199, 199, - 199, 229, 241, 241, 241, 271, 283, 283, 313, 313, 313, 349, 349, 349, 349, - 421, 433, 463, 463, 463, 523, 523, 571, 601, 619, 661, 661, 661, 661, 661, - 823, 859, 883, 883, 883, 1021, 1063, 1093, 1153, 1153, 1231, 1321, 1321, - 1429, 1489, 1489, 1621, 1699, 1789, 1873, 1951, 2029, 2131, 2143, 2311, - 2383, 2383, 2593, 2731, 2803, 3001, 3121, 3259, 3391, 3583, 3673, 3919, - 4093, 4273, 4423, 4651, 4801, 5023, 5281, 5521, 5743, 5881, 6301, 6571, - 6871, 7129, 7489, 7759, 8089, 8539, 8863, 9283, 9721, 10141, 10531, 11071, - 11551, 12073, 12613, 13009, 13759, 14323, 14869, 15649, 16363, 17029, - 17839, 18541, 19471, 20233, 21193, 22159, 23059, 24181, 25171, 26263, - 27541, 28753, 30013, 31321, 32719, 34213, 35731, 37309, 38923, 40639, - 42463, 44281, 46309, 48313, 50461, 52711, 55051, 57529, 60091, 62299, - 65521, 68281, 71413, 74611, 77713, 81373, 84979, 88663, 92671, 96739, - 100801, 105529, 109849, 115021, 120079, 125509, 131011, 136861, 142873, - 149251, 155863, 162751, 169891, 177433, 185071, 193381, 202129, 211063, - 220021, 229981, 240349, 250969, 262111, 273643, 285841, 298411, 311713, - 325543, 339841, 355009, 370663, 386989, 404269, 422113, 440809, 460081, - 480463, 501829, 524221, 547399, 571603, 596929, 623353, 651019, 679909, - 709741, 741343, 774133, 808441, 844201, 881539, 920743, 961531, 1004119, - 1048573, 1094923, 1143283, 1193911, 1246963, 1302181, 1359733, 1420039, - 1482853, 1548541, 1616899, 1688413, 1763431, 1841293, 1922773, 2008081, - 2097133, 2189989, 2286883, 2388163, 2493853, 2604013, 2719669, 2840041, - 2965603, 3097123, 3234241, 3377191, 3526933, 3682363, 3845983, 4016041, - 4193803, 4379719, 4573873, 4776223, 4987891, 5208523, 5439223, 5680153, - 5931313, 6194191, 6468463, 6754879, 7053331, 7366069, 7692343, 8032639, - 8388451, 8759953, 9147661, 9552733, 9975193, 10417291, 10878619, 11360203, - 11863153, 12387841, 12936529, 13509343, 14107801, 14732413, 15384673, - 16065559, 16777141, 17519893, 18295633, 19105483, 19951231, 20834689, - 21757291, 22720591, 23726449, 24776953, 25873963, 27018853, 28215619, - 29464579, 30769093, 32131711, 33554011, 35039911, 36591211, 38211163, - 39903121, 41669479, 43514521, 45441199, 47452879, 49553941, 51747991, - 54039079, 56431513, 58930021, 61539091, 64263571, 67108669, 70079959, - 73182409, 76422793, 79806229, 83339383, 87029053, 90881083, 94906249, - 99108043, 103495879, 108077731, 112863013, 117860053, 123078019, 128526943, - 134217439, 140159911, 146365159, 152845393, 159612601, 166679173, - 174058849, 181765093, 189812341, 198216103, 206991601, 216156043, - 225726379, 235720159, 246156271, 257054491, 268435009, 280319203, - 292730833, 305691181, 319225021, 333358513, 348117151, 363529759, - 379624279, 396432481, 413983771, 432312511, 451452613, 471440161, - 492312523, 514109251, 536870839, 560640001, 585461743, 611382451, - 638450569, 666717199, 696235363, 727060069, 759249643, 792864871, - 827967631, 864625033, 902905501, 942880663, 984625531, 1028218189, - 1073741719, 1121280091, 1170923713, 1222764841, 1276901371, 1333434301, - 1392470281, 1454120779, 1518500173, 1585729993, 1655935399, 1729249999, - 1805811253, 1885761133, 1969251079, 2056437379, 2147482951 }; - -} diff --git a/src/main/java/it/unimi/dsi/fastutil/HashCommon.java b/src/main/java/it/unimi/dsi/fastutil/HashCommon.java deleted file mode 100644 index f93025f..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/HashCommon.java +++ /dev/null @@ -1,240 +0,0 @@ -package it.unimi.dsi.fastutil; - -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -/** Common code for all hash-based classes. */ - -public class HashCommon { - - protected HashCommon() {}; - - /** This reference is used to fill keys and values of removed entries (if - they are objects). null cannot be used as it would confuse the - search algorithm in the presence of an actual null key. */ - public static final Object REMOVED = new Object(); - - /** 232 · φ, φ = (√5 − 1)/2. */ - private static final int INT_PHI = 0x9E3779B9; - /** The reciprocal of {@link #INT_PHI} modulo 232. */ - private static final int INV_INT_PHI = 0x144cbc89; - /** 264 · φ, φ = (√5 − 1)/2. */ - private static final long LONG_PHI = 0x9E3779B97F4A7C15L; - /** The reciprocal of {@link #LONG_PHI} modulo 264. */ - private static final long INV_LONG_PHI = 0xf1de83e19937733dL; - - /** Avalanches the bits of an integer by applying the finalisation step of MurmurHash3. - * - *

This method implements the finalisation step of Austin Appleby's MurmurHash3. - * Its purpose is to avalanche the bits of the argument to within 0.25% bias. - * - * @param x an integer. - * @return a hash value with good avalanching properties. - */ - public final static int murmurHash3( int x ) { - x ^= x >>> 16; - x *= 0x85ebca6b; - x ^= x >>> 13; - x *= 0xc2b2ae35; - x ^= x >>> 16; - return x; - } - - - /** Avalanches the bits of a long integer by applying the finalisation step of MurmurHash3. - * - *

This method implements the finalisation step of Austin Appleby's MurmurHash3. - * Its purpose is to avalanche the bits of the argument to within 0.25% bias. - * - * @param x a long integer. - * @return a hash value with good avalanching properties. - */ - public final static long murmurHash3( long x ) { - x ^= x >>> 33; - x *= 0xff51afd7ed558ccdL; - x ^= x >>> 33; - x *= 0xc4ceb9fe1a85ec53L; - x ^= x >>> 33; - return x; - } - - /** Quickly mixes the bits of an integer. - * - *

This method mixes the bits of the argument by multiplying by the golden ratio and - * xorshifting the result. It is borrowed from Koloboke, and - * it has slightly worse behaviour than {@link #murmurHash3(int)} (in open-addressing hash tables the average number of probes - * is slightly larger), but it's much faster. - * - * @param x an integer. - * @return a hash value obtained by mixing the bits of {@code x}. - * @see #invMix(int) - */ - public final static int mix( final int x ) { - final int h = x * INT_PHI; - return h ^ (h >>> 16); - } - - /** The inverse of {@link #mix(int)}. This method is mainly useful to create unit tests. - * - * @param x an integer. - * @return a value that passed through {@link #mix(int)} would give {@code x}. - */ - public final static int invMix( final int x ) { - return ( x ^ x >>> 16 ) * INV_INT_PHI; - } - - /** Quickly mixes the bits of a long integer. - * - *

This method mixes the bits of the argument by multiplying by the golden ratio and - * xorshifting twice the result. It is borrowed from Koloboke, and - * it has slightly worse behaviour than {@link #murmurHash3(long)} (in open-addressing hash tables the average number of probes - * is slightly larger), but it's much faster. - * - * @param x a long integer. - * @return a hash value obtained by mixing the bits of {@code x}. - */ - public final static long mix( final long x ) { - long h = x * LONG_PHI; - h ^= h >>> 32; - return h ^ (h >>> 16); - } - - /** The inverse of {@link #mix(long)}. This method is mainly useful to create unit tests. - * - * @param x a long integer. - * @return a value that passed through {@link #mix(long)} would give {@code x}. - */ - public final static long invMix( long x ) { - x ^= x >>> 32; - x ^= x >>> 16; - return ( x ^ x >>> 32 ) * INV_LONG_PHI; - } - - - /** Returns the hash code that would be returned by {@link Float#hashCode()}. - * - * @param f a float. - * @return the same code as {@link Float#hashCode() new Float(f).hashCode()}. - */ - - final public static int float2int( final float f ) { - return Float.floatToRawIntBits( f ); - } - - /** Returns the hash code that would be returned by {@link Double#hashCode()}. - * - * @param d a double. - * @return the same code as {@link Double#hashCode() new Double(f).hashCode()}. - */ - - final public static int double2int( final double d ) { - final long l = Double.doubleToRawLongBits( d ); - return (int)( l ^ ( l >>> 32 ) ); - } - - /** Returns the hash code that would be returned by {@link Long#hashCode()}. - * - * @param l a long. - * @return the same code as {@link Long#hashCode() new Long(f).hashCode()}. - */ - final public static int long2int( final long l ) { - return (int)( l ^ ( l >>> 32 ) ); - } - - /** Return the least power of two greater than or equal to the specified value. - * - *

Note that this function will return 1 when the argument is 0. - * - * @param x an integer smaller than or equal to 230. - * @return the least power of two greater than or equal to the specified value. - */ - public static int nextPowerOfTwo( int x ) { - if ( x == 0 ) return 1; - x--; - x |= x >> 1; - x |= x >> 2; - x |= x >> 4; - x |= x >> 8; - return ( x | x >> 16 ) + 1; - } - - /** Return the least power of two greater than or equal to the specified value. - * - *

Note that this function will return 1 when the argument is 0. - * - * @param x a long integer smaller than or equal to 262. - * @return the least power of two greater than or equal to the specified value. - */ - public static long nextPowerOfTwo( long x ) { - if ( x == 0 ) return 1; - x--; - x |= x >> 1; - x |= x >> 2; - x |= x >> 4; - x |= x >> 8; - x |= x >> 16; - return ( x | x >> 32 ) + 1; - } - - - /** Returns the maximum number of entries that can be filled before rehashing. - * - * @param n the size of the backing array. - * @param f the load factor. - * @return the maximum number of entries before rehashing. - */ - public static int maxFill( final int n, final float f ) { - /* We must guarantee that there is always at least - * one free entry (even with pathological load factors). */ - return Math.min( (int)Math.ceil( n * f ), n - 1 ); - } - - /** Returns the maximum number of entries that can be filled before rehashing. - * - * @param n the size of the backing array. - * @param f the load factor. - * @return the maximum number of entries before rehashing. - */ - public static long maxFill( final long n, final float f ) { - /* We must guarantee that there is always at least - * one free entry (even with pathological load factors). */ - return Math.min( (long)Math.ceil( n * f ), n - 1 ); - } - - /** Returns the least power of two smaller than or equal to 230 and larger than or equal to Math.ceil( expected / f ). - * - * @param expected the expected number of elements in a hash table. - * @param f the load factor. - * @return the minimum possible size for a backing array. - * @throws IllegalArgumentException if the necessary size is larger than 230. - */ - public static int arraySize( final int expected, final float f ) { - final long s = Math.max( 2, nextPowerOfTwo( (long)Math.ceil( expected / f ) ) ); - if ( s > (1 << 30) ) throw new IllegalArgumentException( "Too large (" + expected + " expected elements with load factor " + f + ")" ); - return (int)s; - } - - /** Returns the least power of two larger than or equal to Math.ceil( expected / f ). - * - * @param expected the expected number of elements in a hash table. - * @param f the load factor. - * @return the minimum possible size for a backing big array. - */ - public static long bigArraySize( final long expected, final float f ) { - return nextPowerOfTwo( (long)Math.ceil( expected / f ) ); - } -} diff --git a/src/main/java/it/unimi/dsi/fastutil/Stack.java b/src/main/java/it/unimi/dsi/fastutil/Stack.java deleted file mode 100644 index 47efa8a..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/Stack.java +++ /dev/null @@ -1,73 +0,0 @@ -package it.unimi.dsi.fastutil; - -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -import java.util.NoSuchElementException; - -/** A stack. - * - *

A stack must provide the classical {@link #push(Object)} and - * {@link #pop()} operations, but may be also peekable - * to some extent: it may provide just the {@link #top()} function, - * or even a more powerful {@link #peek(int)} method that provides - * access to all elements on the stack (indexed from the top, which - * has index 0). - */ - -public interface Stack { - - /** Pushes the given object on the stack. - * - * @param o the object that will become the new top of the stack. - */ - - void push(K o); - - /** Pops the top off the stack. - * - * @return the top of the stack. - * @throws NoSuchElementException if the stack is empty. - */ - - K pop(); - - /** Checks whether the stack is empty. - * - * @return true if the stack is empty. - */ - - boolean isEmpty(); - - /** Peeks at the top of the stack (optional operation). - * - * @return the top of the stack. - * @throws NoSuchElementException if the stack is empty. - */ - - K top(); - - /** Peeks at an element on the stack (optional operation). - * - * @param i an index from the stop of the stack (0 represents the top). - * @return the i-th element on the stack. - * @throws IndexOutOfBoundsException if the designated element does not exist.. - */ - - K peek(int i); - -} diff --git a/src/main/java/it/unimi/dsi/fastutil/Swapper.java b/src/main/java/it/unimi/dsi/fastutil/Swapper.java deleted file mode 100644 index 53fd36f..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/Swapper.java +++ /dev/null @@ -1,33 +0,0 @@ -package it.unimi.dsi.fastutil; - -/* - * Copyright (C) 2010-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import it.unimi.dsi.fastutil.Arrays; - -/** An object that can swap elements whose position is specified by integers - * - * @see Arrays#quickSort(int, int, it.unimi.dsi.fastutil.ints.IntComparator, it.unimi.dsi.fastutil.Swapper) - */ - -public interface Swapper { - /** Swaps the data at the given positions. - * - * @param a the first position to swap. - * @param b the second position to swap. - */ - void swap(int a, int b); -} diff --git a/src/main/java/it/unimi/dsi/fastutil/booleans/AbstractBooleanBidirectionalIterator.java b/src/main/java/it/unimi/dsi/fastutil/booleans/AbstractBooleanBidirectionalIterator.java deleted file mode 100644 index 726b5a2..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/booleans/AbstractBooleanBidirectionalIterator.java +++ /dev/null @@ -1,98 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Primitive-type-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.booleans; - -import it.unimi.dsi.fastutil.booleans.AbstractBooleanIterator; -import it.unimi.dsi.fastutil.booleans.BooleanBidirectionalIterator; - -/** - * An abstract class facilitating the creation of type-specific - * {@linkplain it.unimi.dsi.fastutil.BidirectionalIterator bidirectional - * iterators}. - * - *

- * To create a type-specific bidirectional iterator, besides what is needed for - * an iterator you need both a method returning the previous element as - * primitive type and a method returning the previous element as an object. - * However, if you inherit from this class you need just one (anyone). - * - *

- * This class implements also a trivial version of {@link #back(int)} that uses - * type-specific methods. - */ - -public abstract class AbstractBooleanBidirectionalIterator - extends - AbstractBooleanIterator - implements BooleanBidirectionalIterator { - - protected AbstractBooleanBidirectionalIterator() { - } - - /** Delegates to the corresponding generic method. */ - public boolean previousBoolean() { - return previous().booleanValue(); - } - - /** Delegates to the corresponding type-specific method. */ - public Boolean previous() { - return Boolean.valueOf(previousBoolean()); - } - - /** - * This method just iterates the type-specific version of - * {@link #previous()} for at most n times, stopping if - * {@link #hasPrevious()} becomes false. - */ - public int back(final int n) { - int i = n; - while (i-- != 0 && hasPrevious()) - previousBoolean(); - return n - i - 1; - } - -} diff --git a/src/main/java/it/unimi/dsi/fastutil/booleans/AbstractBooleanCollection.java b/src/main/java/it/unimi/dsi/fastutil/booleans/AbstractBooleanCollection.java deleted file mode 100644 index a6f4646..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/booleans/AbstractBooleanCollection.java +++ /dev/null @@ -1,368 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Primitive-type-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.booleans; - -import it.unimi.dsi.fastutil.booleans.BooleanCollection; -import it.unimi.dsi.fastutil.booleans.BooleanIterator; -import it.unimi.dsi.fastutil.booleans.BooleanIterators; - -import java.util.AbstractCollection; -import java.util.Collection; -import java.util.Iterator; - -/** - * An abstract class providing basic methods for collections implementing a - * type-specific interface. - * - *

- * In particular, this class provide {@link #iterator()}, add(), - * {@link #remove(Object)} and {@link #contains(Object)} methods that just call - * the type-specific counterpart. - */ - -public abstract class AbstractBooleanCollection - extends - AbstractCollection implements BooleanCollection { - - protected AbstractBooleanCollection() { - } - - public boolean[] toArray(boolean a[]) { - return toBooleanArray(a); - } - - public boolean[] toBooleanArray() { - return toBooleanArray(null); - } - - public boolean[] toBooleanArray(boolean a[]) { - if (a == null || a.length < size()) - a = new boolean[size()]; - BooleanIterators.unwrap(iterator(), a); - return a; - } - - /** - * Adds all elements of the given type-specific collection to this - * collection. - * - * @param c - * a type-specific collection. - * @return true if this collection changed as a result of the - * call. - */ - - public boolean addAll(BooleanCollection c) { - boolean retVal = false; - final BooleanIterator i = c.iterator(); - int n = c.size(); - - while (n-- != 0) - if (add(i.nextBoolean())) - retVal = true; - return retVal; - } - - /** - * Checks whether this collection contains all elements from the given - * type-specific collection. - * - * @param c - * a type-specific collection. - * @return true if this collection contains all elements of the - * argument. - */ - - public boolean containsAll(BooleanCollection c) { - final BooleanIterator i = c.iterator(); - int n = c.size(); - - while (n-- != 0) - if (!contains(i.nextBoolean())) - return false; - - return true; - } - - /** - * Retains in this collection only elements from the given type-specific - * collection. - * - * @param c - * a type-specific collection. - * @return true if this collection changed as a result of the - * call. - */ - - public boolean retainAll(BooleanCollection c) { - boolean retVal = false; - int n = size(); - - final BooleanIterator i = iterator(); - - while (n-- != 0) { - if (!c.contains(i.nextBoolean())) { - i.remove(); - retVal = true; - } - } - - return retVal; - } - - /** - * Remove from this collection all elements in the given type-specific - * collection. - * - * @param c - * a type-specific collection. - * @return true if this collection changed as a result of the - * call. - */ - - public boolean removeAll(BooleanCollection c) { - boolean retVal = false; - int n = c.size(); - - final BooleanIterator i = c.iterator(); - - while (n-- != 0) - if (rem(i.nextBoolean())) - retVal = true; - - return retVal; - } - - public Object[] toArray() { - final Object[] a = new Object[size()]; - it.unimi.dsi.fastutil.objects.ObjectIterators.unwrap(iterator(), a); - return a; - } - - @SuppressWarnings("unchecked") - public T[] toArray(T[] a) { - final int size = size(); - if (a.length < size) - a = (T[]) java.lang.reflect.Array.newInstance(a.getClass() - .getComponentType(), size); - it.unimi.dsi.fastutil.objects.ObjectIterators.unwrap(iterator(), a); - if (size < a.length) - a[size] = null; - return a; - } - - /** - * Adds all elements of the given collection to this collection. - * - * @param c - * a collection. - * @return true if this collection changed as a result of the - * call. - */ - - public boolean addAll(Collection c) { - boolean retVal = false; - final Iterator i = c.iterator(); - int n = c.size(); - - while (n-- != 0) - if (add(i.next())) - retVal = true; - return retVal; - } - - public boolean add(boolean k) { - throw new UnsupportedOperationException(); - } - - /** Delegates to the new covariantly stronger generic method. */ - - @Deprecated - public BooleanIterator booleanIterator() { - return iterator(); - } - - public abstract BooleanIterator iterator(); - - /** Delegates to the type-specific rem() method. */ - public boolean remove(Object ok) { - if (ok == null) - return false; - return rem(((((Boolean) (ok)).booleanValue()))); - } - - /** Delegates to the corresponding type-specific method. */ - public boolean add(final Boolean o) { - return add(o.booleanValue()); - } - - /** Delegates to the corresponding type-specific method. */ - public boolean rem(final Object o) { - if (o == null) - return false; - return rem(((((Boolean) (o)).booleanValue()))); - } - - /** Delegates to the corresponding type-specific method. */ - public boolean contains(final Object o) { - if (o == null) - return false; - return contains(((((Boolean) (o)).booleanValue()))); - } - - public boolean contains(final boolean k) { - final BooleanIterator iterator = iterator(); - while (iterator.hasNext()) - if (k == iterator.nextBoolean()) - return true; - return false; - } - - public boolean rem(final boolean k) { - final BooleanIterator iterator = iterator(); - while (iterator.hasNext()) - if (k == iterator.nextBoolean()) { - iterator.remove(); - return true; - } - return false; - } - - /** - * Checks whether this collection contains all elements from the given - * collection. - * - * @param c - * a collection. - * @return true if this collection contains all elements of the - * argument. - */ - - public boolean containsAll(Collection c) { - int n = c.size(); - - final Iterator i = c.iterator(); - while (n-- != 0) - if (!contains(i.next())) - return false; - - return true; - } - - /** - * Retains in this collection only elements from the given collection. - * - * @param c - * a collection. - * @return true if this collection changed as a result of the - * call. - */ - - public boolean retainAll(Collection c) { - boolean retVal = false; - int n = size(); - - final Iterator i = iterator(); - while (n-- != 0) { - if (!c.contains(i.next())) { - i.remove(); - retVal = true; - } - } - - return retVal; - } - - /** - * Remove from this collection all elements in the given collection. If the - * collection is an instance of this class, it uses faster iterators. - * - * @param c - * a collection. - * @return true if this collection changed as a result of the - * call. - */ - - public boolean removeAll(Collection c) { - boolean retVal = false; - int n = c.size(); - - final Iterator i = c.iterator(); - while (n-- != 0) - if (remove(i.next())) - retVal = true; - - return retVal; - } - - public boolean isEmpty() { - return size() == 0; - } - - public String toString() { - final StringBuilder s = new StringBuilder(); - final BooleanIterator i = iterator(); - int n = size(); - boolean k; - boolean first = true; - - s.append("{"); - - while (n-- != 0) { - if (first) - first = false; - else - s.append(", "); - k = i.nextBoolean(); - - s.append(String.valueOf(k)); - } - - s.append("}"); - return s.toString(); - } -} diff --git a/src/main/java/it/unimi/dsi/fastutil/booleans/AbstractBooleanIterator.java b/src/main/java/it/unimi/dsi/fastutil/booleans/AbstractBooleanIterator.java deleted file mode 100644 index 4dc78b7..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/booleans/AbstractBooleanIterator.java +++ /dev/null @@ -1,104 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Primitive-type-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.booleans; - -import it.unimi.dsi.fastutil.booleans.BooleanIterator; - -/** - * An abstract class facilitating the creation of type-specific iterators. - * - *

- * To create a type-specific iterator you need both a method returning the next - * element as primitive type and a method returning the next element as an - * object. However, if you inherit from this class you need just one (anyone). - * - *

- * This class implements also a trivial version of {@link #skip(int)} that uses - * type-specific methods; moreover, {@link #remove()} will throw an - * {@link UnsupportedOperationException}. - * - * @see java.util.Iterator - */ - -public abstract class AbstractBooleanIterator implements BooleanIterator { - - protected AbstractBooleanIterator() { - } - - /** Delegates to the corresponding generic method. */ - public boolean nextBoolean() { - return next().booleanValue(); - } - - /** - * Delegates to the corresponding type-specific method. - * - * @deprecated Please use the corresponding type-specific method instead. - */ - @Deprecated - public Boolean next() { - return Boolean.valueOf(nextBoolean()); - } - - /** This method just throws an {@link UnsupportedOperationException}. */ - public void remove() { - throw new UnsupportedOperationException(); - } - - /** - * This method just iterates the type-specific version of {@link #next()} - * for at most n times, stopping if {@link #hasNext()} becomes - * false. - */ - - public int skip(final int n) { - int i = n; - while (i-- != 0 && hasNext()) - nextBoolean(); - return n - i - 1; - } -} diff --git a/src/main/java/it/unimi/dsi/fastutil/booleans/AbstractBooleanList.java b/src/main/java/it/unimi/dsi/fastutil/booleans/AbstractBooleanList.java deleted file mode 100644 index c592f48..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/booleans/AbstractBooleanList.java +++ /dev/null @@ -1,841 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Primitive-type-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.booleans; - -import it.unimi.dsi.fastutil.booleans.AbstractBooleanCollection; -import it.unimi.dsi.fastutil.booleans.AbstractBooleanListIterator; -import it.unimi.dsi.fastutil.booleans.BooleanCollection; -import it.unimi.dsi.fastutil.booleans.BooleanIterator; -import it.unimi.dsi.fastutil.booleans.BooleanList; -import it.unimi.dsi.fastutil.booleans.BooleanListIterator; -import it.unimi.dsi.fastutil.booleans.BooleanStack; - -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; -import java.util.NoSuchElementException; - -/** - * An abstract class providing basic methods for lists implementing a - * type-specific list interface. - * - *

- * As an additional bonus, this class implements on top of the list operations a - * type-specific stack. - */ - -public abstract class AbstractBooleanList extends AbstractBooleanCollection - implements - BooleanList, - BooleanStack { - - protected AbstractBooleanList() { - } - - /** - * Ensures that the given index is nonnegative and not greater than the list - * size. - * - * @param index - * an index. - * @throws IndexOutOfBoundsException - * if the given index is negative or greater than the list size. - */ - protected void ensureIndex(final int index) { - if (index < 0) - throw new IndexOutOfBoundsException("Index (" + index - + ") is negative"); - if (index > size()) - throw new IndexOutOfBoundsException("Index (" + index - + ") is greater than list size (" + (size()) + ")"); - } - - /** - * Ensures that the given index is nonnegative and smaller than the list - * size. - * - * @param index - * an index. - * @throws IndexOutOfBoundsException - * if the given index is negative or not smaller than the list - * size. - */ - protected void ensureRestrictedIndex(final int index) { - if (index < 0) - throw new IndexOutOfBoundsException("Index (" + index - + ") is negative"); - if (index >= size()) - throw new IndexOutOfBoundsException("Index (" + index - + ") is greater than or equal to list size (" + (size()) - + ")"); - } - - public void add(final int index, final boolean k) { - throw new UnsupportedOperationException(); - } - - public boolean add(final boolean k) { - add(size(), k); - return true; - } - - public boolean removeBoolean(int i) { - throw new UnsupportedOperationException(); - } - - public boolean set(final int index, final boolean k) { - throw new UnsupportedOperationException(); - } - - public boolean addAll(int index, final Collection c) { - ensureIndex(index); - int n = c.size(); - if (n == 0) - return false; - Iterator i = c.iterator(); - while (n-- != 0) - add(index++, i.next()); - return true; - } - - /** Delegates to a more generic method. */ - public boolean addAll(final Collection c) { - return addAll(size(), c); - } - - /** Delegates to the new covariantly stronger generic method. */ - - @Deprecated - public BooleanListIterator booleanListIterator() { - return listIterator(); - } - - /** Delegates to the new covariantly stronger generic method. */ - - @Deprecated - public BooleanListIterator booleanListIterator(final int index) { - return listIterator(index); - } - - public BooleanListIterator iterator() { - return listIterator(); - } - - public BooleanListIterator listIterator() { - return listIterator(0); - } - - public BooleanListIterator listIterator(final int index) { - ensureIndex(index); - - return new AbstractBooleanListIterator() { - int pos = index, last = -1; - - public boolean hasNext() { - return pos < it.unimi.dsi.fastutil.booleans.AbstractBooleanList.this.size(); - } - public boolean hasPrevious() { - return pos > 0; - } - public boolean nextBoolean() { - if (!hasNext()) - throw new NoSuchElementException(); - return it.unimi.dsi.fastutil.booleans.AbstractBooleanList.this.getBoolean(last = pos++); - } - public boolean previousBoolean() { - if (!hasPrevious()) - throw new NoSuchElementException(); - return it.unimi.dsi.fastutil.booleans.AbstractBooleanList.this.getBoolean(last = --pos); - } - public int nextIndex() { - return pos; - } - public int previousIndex() { - return pos - 1; - } - public void add(boolean k) { - it.unimi.dsi.fastutil.booleans.AbstractBooleanList.this.add(pos++, k); - last = -1; - } - public void set(boolean k) { - if (last == -1) - throw new IllegalStateException(); - it.unimi.dsi.fastutil.booleans.AbstractBooleanList.this.set(last, k); - } - public void remove() { - if (last == -1) - throw new IllegalStateException(); - it.unimi.dsi.fastutil.booleans.AbstractBooleanList.this.removeBoolean(last); - /* - * If the last operation was a next(), we are removing an - * element *before* us, and we must decrease pos - * correspondingly. - */ - if (last < pos) - pos--; - last = -1; - } - }; - } - - public boolean contains(final boolean k) { - return indexOf(k) >= 0; - } - - public int indexOf(final boolean k) { - final BooleanListIterator i = listIterator(); - boolean e; - while (i.hasNext()) { - e = i.nextBoolean(); - if (((k) == (e))) - return i.previousIndex(); - } - return -1; - } - - public int lastIndexOf(final boolean k) { - BooleanListIterator i = listIterator(size()); - boolean e; - while (i.hasPrevious()) { - e = i.previousBoolean(); - if (((k) == (e))) - return i.nextIndex(); - } - return -1; - } - - public void size(final int size) { - int i = size(); - if (size > i) - while (i++ < size) - add((false)); - else - while (i-- != size) - remove(i); - } - - public BooleanList subList(final int from, final int to) { - ensureIndex(from); - ensureIndex(to); - if (from > to) - throw new IndexOutOfBoundsException("Start index (" + from - + ") is greater than end index (" + to + ")"); - - return new BooleanSubList(this, from, to); - } - - /** Delegates to the new covariantly stronger generic method. */ - - @Deprecated - public BooleanList booleanSubList(final int from, final int to) { - return subList(from, to); - } - - /** - * Removes elements of this type-specific list one-by-one. - * - *

- * This is a trivial iterator-based implementation. It is expected that - * implementations will override this method with a more optimized version. - * - * - * @param from - * the start index (inclusive). - * @param to - * the end index (exclusive). - */ - - public void removeElements(final int from, final int to) { - ensureIndex(to); - BooleanListIterator i = listIterator(from); - int n = to - from; - if (n < 0) - throw new IllegalArgumentException("Start index (" + from - + ") is greater than end index (" + to + ")"); - while (n-- != 0) { - i.nextBoolean(); - i.remove(); - } - } - - /** - * Adds elements to this type-specific list one-by-one. - * - *

- * This is a trivial iterator-based implementation. It is expected that - * implementations will override this method with a more optimized version. - * - * @param index - * the index at which to add elements. - * @param a - * the array containing the elements. - * @param offset - * the offset of the first element to add. - * @param length - * the number of elements to add. - */ - - public void addElements(int index, final boolean a[], int offset, int length) { - ensureIndex(index); - if (offset < 0) - throw new ArrayIndexOutOfBoundsException("Offset (" + offset - + ") is negative"); - if (offset + length > a.length) - throw new ArrayIndexOutOfBoundsException("End index (" - + (offset + length) + ") is greater than array length (" - + a.length + ")"); - while (length-- != 0) - add(index++, a[offset++]); - } - - public void addElements(final int index, final boolean a[]) { - addElements(index, a, 0, a.length); - } - - /** - * Copies element of this type-specific list into the given array - * one-by-one. - * - *

- * This is a trivial iterator-based implementation. It is expected that - * implementations will override this method with a more optimized version. - * - * @param from - * the start index (inclusive). - * @param a - * the destination array. - * @param offset - * the offset into the destination array where to store the first - * element copied. - * @param length - * the number of elements to be copied. - */ - - public void getElements(final int from, final boolean a[], int offset, - int length) { - BooleanListIterator i = listIterator(from); - if (offset < 0) - throw new ArrayIndexOutOfBoundsException("Offset (" + offset - + ") is negative"); - if (offset + length > a.length) - throw new ArrayIndexOutOfBoundsException("End index (" - + (offset + length) + ") is greater than array length (" - + a.length + ")"); - if (from + length > size()) - throw new IndexOutOfBoundsException("End index (" + (from + length) - + ") is greater than list size (" + size() + ")"); - while (length-- != 0) - a[offset++] = i.nextBoolean(); - } - - private boolean valEquals(final Object a, final Object b) { - return a == null ? b == null : a.equals(b); - } - - public boolean equals(final Object o) { - if (o == this) - return true; - if (!(o instanceof List)) - return false; - - final List l = (List) o; - int s = size(); - if (s != l.size()) - return false; - - if (l instanceof BooleanList) { - final BooleanListIterator i1 = listIterator(), i2 = ((BooleanList) l) - .listIterator(); - while (s-- != 0) - if (i1.nextBoolean() != i2.nextBoolean()) - return false; - return true; - } - - final ListIterator i1 = listIterator(), i2 = l.listIterator(); - - while (s-- != 0) - if (!valEquals(i1.next(), i2.next())) - return false; - - return true; - } - - /** - * Compares this list to another object. If the argument is a - * {@link List}, this method performs a lexicographical - * comparison; otherwise, it throws a ClassCastException. - * - * @param l - * a list. - * @return if the argument is a {@link List}, a negative integer, - * zero, or a positive integer as this list is lexicographically - * less than, equal to, or greater than the argument. - * @throws ClassCastException - * if the argument is not a list. - */ - - public int compareTo(final List l) { - if (l == this) - return 0; - - if (l instanceof BooleanList) { - - final BooleanListIterator i1 = listIterator(), i2 = ((BooleanList) l) - .listIterator(); - int r; - boolean e1, e2; - - while (i1.hasNext() && i2.hasNext()) { - e1 = i1.nextBoolean(); - e2 = i2.nextBoolean(); - if ((r = (Boolean.compare((e1), (e2)))) != 0) - return r; - } - return i2.hasNext() ? -1 : (i1.hasNext() ? 1 : 0); - } - - ListIterator i1 = listIterator(), i2 = l - .listIterator(); - int r; - - while (i1.hasNext() && i2.hasNext()) { - if ((r = ((Comparable) i1.next()).compareTo(i2 - .next())) != 0) - return r; - } - return i2.hasNext() ? -1 : (i1.hasNext() ? 1 : 0); - } - - /** - * Returns the hash code for this list, which is identical to - * {@link List#hashCode()}. - * - * @return the hash code for this list. - */ - public int hashCode() { - BooleanIterator i = iterator(); - int h = 1, s = size(); - while (s-- != 0) { - boolean k = i.nextBoolean(); - h = 31 * h + ((k) ? 1231 : 1237); - } - return h; - } - - public void push(boolean o) { - add(o); - } - - public boolean popBoolean() { - if (isEmpty()) - throw new NoSuchElementException(); - return removeBoolean(size() - 1); - } - - public boolean topBoolean() { - if (isEmpty()) - throw new NoSuchElementException(); - return getBoolean(size() - 1); - } - - public boolean peekBoolean(int i) { - return getBoolean(size() - 1 - i); - } - - public boolean rem(boolean k) { - int index = indexOf(k); - if (index == -1) - return false; - removeBoolean(index); - return true; - } - - /** Delegates to rem(). */ - public boolean remove(final Object o) { - return rem(((((Boolean) (o)).booleanValue()))); - } - - /** Delegates to a more generic method. */ - public boolean addAll(final int index, final BooleanCollection c) { - return addAll(index, (Collection) c); - } - - /** Delegates to a more generic method. */ - public boolean addAll(final int index, final BooleanList l) { - return addAll(index, (BooleanCollection) l); - } - - public boolean addAll(final BooleanCollection c) { - return addAll(size(), c); - } - - public boolean addAll(final BooleanList l) { - return addAll(size(), l); - } - - /** Delegates to the corresponding type-specific method. */ - public void add(final int index, final Boolean ok) { - add(index, ok.booleanValue()); - } - - /** - * Delegates to the corresponding type-specific method. - * - * @deprecated Please use the corresponding type-specific method instead. - */ - @Deprecated - public Boolean set(final int index, final Boolean ok) { - return (Boolean.valueOf(set(index, ok.booleanValue()))); - } - - /** - * Delegates to the corresponding type-specific method. - * - * @deprecated Please use the corresponding type-specific method instead. - */ - @Deprecated - public Boolean get(final int index) { - return (Boolean.valueOf(getBoolean(index))); - } - - /** Delegates to the corresponding type-specific method. */ - public int indexOf(final Object ok) { - return indexOf(((((Boolean) (ok)).booleanValue()))); - } - - /** Delegates to the corresponding type-specific method. */ - public int lastIndexOf(final Object ok) { - return lastIndexOf(((((Boolean) (ok)).booleanValue()))); - } - - /** - * Delegates to the corresponding type-specific method. - * - * @deprecated Please use the corresponding type-specific method instead. - */ - @Deprecated - public Boolean remove(final int index) { - return (Boolean.valueOf(removeBoolean(index))); - } - - /** Delegates to the corresponding type-specific method. */ - public void push(Boolean o) { - push(o.booleanValue()); - } - - /** - * Delegates to the corresponding type-specific method. - * - * @deprecated Please use the corresponding type-specific method instead. - */ - @Deprecated - public Boolean pop() { - return Boolean.valueOf(popBoolean()); - } - - /** - * Delegates to the corresponding type-specific method. - * - * @deprecated Please use the corresponding type-specific method instead. - */ - @Deprecated - public Boolean top() { - return Boolean.valueOf(topBoolean()); - } - - /** - * Delegates to the corresponding type-specific method. - * - * @deprecated Please use the corresponding type-specific method instead. - */ - @Deprecated - public Boolean peek(int i) { - return Boolean.valueOf(peekBoolean(i)); - } - - public String toString() { - final StringBuilder s = new StringBuilder(); - final BooleanIterator i = iterator(); - int n = size(); - boolean k; - boolean first = true; - - s.append("["); - - while (n-- != 0) { - if (first) - first = false; - else - s.append(", "); - k = i.nextBoolean(); - - s.append(String.valueOf(k)); - } - - s.append("]"); - return s.toString(); - } - - public static class BooleanSubList extends it.unimi.dsi.fastutil.booleans.AbstractBooleanList - implements - java.io.Serializable { - private static final long serialVersionUID = -7046029254386353129L; - /** The list this sublist restricts. */ - protected final BooleanList l; - /** Initial (inclusive) index of this sublist. */ - protected final int from; - /** Final (exclusive) index of this sublist. */ - protected int to; - - private static final boolean ASSERTS = false; - - public BooleanSubList(final BooleanList l, final int from, final int to) { - this.l = l; - this.from = from; - this.to = to; - } - - private void assertRange() { - if (ASSERTS) { - assert from <= l.size(); - assert to <= l.size(); - assert to >= from; - } - } - - public boolean add(final boolean k) { - l.add(to, k); - to++; - if (ASSERTS) - assertRange(); - return true; - } - - public void add(final int index, final boolean k) { - ensureIndex(index); - l.add(from + index, k); - to++; - if (ASSERTS) - assertRange(); - } - - public boolean addAll(final int index, - final Collection c) { - ensureIndex(index); - to += c.size(); - if (ASSERTS) { - boolean retVal = l.addAll(from + index, c); - assertRange(); - return retVal; - } - return l.addAll(from + index, c); - } - - public boolean getBoolean(int index) { - ensureRestrictedIndex(index); - return l.getBoolean(from + index); - } - - public boolean removeBoolean(int index) { - ensureRestrictedIndex(index); - to--; - return l.removeBoolean(from + index); - } - - public boolean set(int index, boolean k) { - ensureRestrictedIndex(index); - return l.set(from + index, k); - } - - public void clear() { - removeElements(0, size()); - if (ASSERTS) - assertRange(); - } - - public int size() { - return to - from; - } - - public void getElements(final int from, final boolean[] a, - final int offset, final int length) { - ensureIndex(from); - if (from + length > size()) - throw new IndexOutOfBoundsException("End index (" + from - + length + ") is greater than list size (" + size() - + ")"); - l.getElements(this.from + from, a, offset, length); - } - - public void removeElements(final int from, final int to) { - ensureIndex(from); - ensureIndex(to); - l.removeElements(this.from + from, this.from + to); - this.to -= (to - from); - if (ASSERTS) - assertRange(); - } - - public void addElements(int index, final boolean a[], int offset, - int length) { - ensureIndex(index); - l.addElements(this.from + index, a, offset, length); - this.to += length; - if (ASSERTS) - assertRange(); - } - - public BooleanListIterator listIterator(final int index) { - ensureIndex(index); - - return new AbstractBooleanListIterator() { - int pos = index, last = -1; - - public boolean hasNext() { - return pos < size(); - } - public boolean hasPrevious() { - return pos > 0; - } - public boolean nextBoolean() { - if (!hasNext()) - throw new NoSuchElementException(); - return l.getBoolean(from + (last = pos++)); - } - public boolean previousBoolean() { - if (!hasPrevious()) - throw new NoSuchElementException(); - return l.getBoolean(from + (last = --pos)); - } - public int nextIndex() { - return pos; - } - public int previousIndex() { - return pos - 1; - } - public void add(boolean k) { - if (last == -1) - throw new IllegalStateException(); - BooleanSubList.this.add(pos++, k); - last = -1; - if (ASSERTS) - assertRange(); - } - public void set(boolean k) { - if (last == -1) - throw new IllegalStateException(); - BooleanSubList.this.set(last, k); - } - public void remove() { - if (last == -1) - throw new IllegalStateException(); - BooleanSubList.this.removeBoolean(last); - /* - * If the last operation was a next(), we are removing an - * element *before* us, and we must decrease pos - * correspondingly. - */ - if (last < pos) - pos--; - last = -1; - if (ASSERTS) - assertRange(); - } - }; - } - - public BooleanList subList(final int from, final int to) { - ensureIndex(from); - ensureIndex(to); - if (from > to) - throw new IllegalArgumentException("Start index (" + from - + ") is greater than end index (" + to + ")"); - - return new BooleanSubList(this, from, to); - } - - public boolean rem(boolean k) { - int index = indexOf(k); - if (index == -1) - return false; - to--; - l.removeBoolean(from + index); - if (ASSERTS) - assertRange(); - return true; - } - - public boolean remove(final Object o) { - return rem(((((Boolean) (o)).booleanValue()))); - } - - public boolean addAll(final int index, final BooleanCollection c) { - ensureIndex(index); - to += c.size(); - if (ASSERTS) { - boolean retVal = l.addAll(from + index, c); - assertRange(); - return retVal; - } - return l.addAll(from + index, c); - } - - public boolean addAll(final int index, final BooleanList l) { - ensureIndex(index); - to += l.size(); - if (ASSERTS) { - boolean retVal = this.l.addAll(from + index, l); - assertRange(); - return retVal; - } - return this.l.addAll(from + index, l); - } - } - -} diff --git a/src/main/java/it/unimi/dsi/fastutil/booleans/AbstractBooleanListIterator.java b/src/main/java/it/unimi/dsi/fastutil/booleans/AbstractBooleanListIterator.java deleted file mode 100644 index a24aec7..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/booleans/AbstractBooleanListIterator.java +++ /dev/null @@ -1,94 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Primitive-type-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.booleans; - -import it.unimi.dsi.fastutil.booleans.AbstractBooleanBidirectionalIterator; -import it.unimi.dsi.fastutil.booleans.BooleanListIterator; - -/** - * An abstract class facilitating the creation of type-specific - * {@linkplain java.util.ListIterator list iterators}. - * - *

- * This class provides trivial type-specific implementations of - * {@link java.util.ListIterator#set(Object) set()} and - * {@link java.util.ListIterator#add(Object) add()} which throw an - * {@link UnsupportedOperationException}. For primitive types, it also provides - * a trivial implementation of {@link java.util.ListIterator#set(Object) set()} - * and {@link java.util.ListIterator#add(Object) add()} that just invokes the - * type-specific one. - * - * - * @see java.util.ListIterator - */ - -public abstract class AbstractBooleanListIterator - extends - AbstractBooleanBidirectionalIterator - implements BooleanListIterator { - - protected AbstractBooleanListIterator() { - } - - /** Delegates to the corresponding type-specific method. */ - public void set(Boolean ok) { - set(ok.booleanValue()); - } - /** Delegates to the corresponding type-specific method. */ - public void add(Boolean ok) { - add(ok.booleanValue()); - } - - /** This method just throws an {@link UnsupportedOperationException}. */ - public void set(boolean k) { - throw new UnsupportedOperationException(); - } - /** This method just throws an {@link UnsupportedOperationException}. */ - public void add(boolean k) { - throw new UnsupportedOperationException(); - } -} diff --git a/src/main/java/it/unimi/dsi/fastutil/booleans/AbstractBooleanSet.java b/src/main/java/it/unimi/dsi/fastutil/booleans/AbstractBooleanSet.java deleted file mode 100644 index 32211f4..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/booleans/AbstractBooleanSet.java +++ /dev/null @@ -1,114 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Primitive-type-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.booleans; - -import it.unimi.dsi.fastutil.booleans.AbstractBooleanCollection; -import it.unimi.dsi.fastutil.booleans.BooleanIterator; -import it.unimi.dsi.fastutil.booleans.BooleanSet; - -import java.util.Set; - -/** - * An abstract class providing basic methods for sets implementing a - * type-specific interface. - */ - -public abstract class AbstractBooleanSet - extends AbstractBooleanCollection - implements - Cloneable, - BooleanSet { - - protected AbstractBooleanSet() { - } - - public abstract BooleanIterator iterator(); - - public boolean equals(final Object o) { - if (o == this) - return true; - if (!(o instanceof Set)) - return false; - - Set s = (Set) o; - if (s.size() != size()) - return false; - return containsAll(s); - } - - /** - * Returns a hash code for this set. - * - * The hash code of a set is computed by summing the hash codes of its - * elements. - * - * @return a hash code for this set. - */ - - public int hashCode() { - int h = 0, n = size(); - BooleanIterator i = iterator(); - boolean k; - - while (n-- != 0) { - k = i.nextBoolean(); // We need k because KEY2JAVAHASH() is a macro - // with repeated evaluation. - h += ((k) ? 1231 : 1237); - } - return h; - } - - public boolean remove(boolean k) { - return rem(k); - } - - /** Delegates to the corresponding type-specific method. */ - public boolean remove(final Object o) { - return remove(((((Boolean) (o)).booleanValue()))); - } - -} diff --git a/src/main/java/it/unimi/dsi/fastutil/booleans/BooleanArrayList.java b/src/main/java/it/unimi/dsi/fastutil/booleans/BooleanArrayList.java deleted file mode 100644 index 5e568e9..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/booleans/BooleanArrayList.java +++ /dev/null @@ -1,716 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Primitive-type-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.booleans; - -import it.unimi.dsi.fastutil.booleans.AbstractBooleanList; -import it.unimi.dsi.fastutil.booleans.AbstractBooleanListIterator; -import it.unimi.dsi.fastutil.booleans.BooleanArrays; -import it.unimi.dsi.fastutil.booleans.BooleanCollection; -import it.unimi.dsi.fastutil.booleans.BooleanIterator; -import it.unimi.dsi.fastutil.booleans.BooleanIterators; -import it.unimi.dsi.fastutil.booleans.BooleanList; -import it.unimi.dsi.fastutil.booleans.BooleanListIterator; - -import java.util.Arrays; -import java.util.Collection; -import java.util.Iterator; -import java.util.NoSuchElementException; -import java.util.RandomAccess; - -/** - * A type-specific array-based list; provides some additional methods that use - * polymorphism to avoid (un)boxing. - * - *

- * This class implements a lightweight, fast, open, optimized, reuse-oriented - * version of array-based lists. Instances of this class represent a list with - * an array that is enlarged as needed when new entries are created (by doubling - * its current length), but is never made smaller (even on a - * {@link #clear()}). A family of {@linkplain #trim() trimming methods} lets you - * control the size of the backing array; this is particularly useful if you - * reuse instances of this class. Range checks are equivalent to those of - * {@link java.util}'s classes, but they are delayed as much as possible. The - * backing array is exposed by the {@link #elements()} method. - * - *

- * This class implements the bulk methods removeElements(), - * addElements() and getElements() using - * high-performance system calls (e.g., - * {@link System#arraycopy(Object,int,Object,int,int) System.arraycopy()} instead - * of expensive loops. - * - * @see java.util.ArrayList - */ - -public class BooleanArrayList extends AbstractBooleanList - implements - RandomAccess, - Cloneable, - java.io.Serializable { - private static final long serialVersionUID = -7046029254386353130L; - /** The initial default capacity of an array list. */ - public final static int DEFAULT_INITIAL_CAPACITY = 16; - - /** The backing array. */ - protected transient boolean a[]; - - /** - * The current actual size of the list (never greater than the backing-array - * length). - */ - protected int size; - - private static final boolean ASSERTS = false; - - /** - * Creates a new array list using a given array. - * - *

- * This constructor is only meant to be used by the wrapping methods. - * - * @param a - * the array that will be used to back this array list. - */ - - @SuppressWarnings("unused") - protected BooleanArrayList(final boolean a[], boolean dummy) { - this.a = a; - - } - - /** - * Creates a new array list with given capacity. - * - * @param capacity - * the initial capacity of the array list (may be 0). - */ - - public BooleanArrayList(final int capacity) { - if (capacity < 0) - throw new IllegalArgumentException("Initial capacity (" + capacity - + ") is negative"); - - a = new boolean[capacity]; - - } - - /** - * Creates a new array list with {@link #DEFAULT_INITIAL_CAPACITY} capacity. - */ - - public BooleanArrayList() { - this(DEFAULT_INITIAL_CAPACITY); - } - - /** - * Creates a new array list and fills it with a given collection. - * - * @param c - * a collection that will be used to fill the array list. - */ - - public BooleanArrayList(final Collection c) { - this(c.size()); - - size = BooleanIterators.unwrap( - BooleanIterators.asBooleanIterator(c.iterator()), a); - - } - - /** - * Creates a new array list and fills it with a given type-specific - * collection. - * - * @param c - * a type-specific collection that will be used to fill the array - * list. - */ - - public BooleanArrayList(final BooleanCollection c) { - this(c.size()); - size = BooleanIterators.unwrap(c.iterator(), a); - } - - /** - * Creates a new array list and fills it with a given type-specific list. - * - * @param l - * a type-specific list that will be used to fill the array list. - */ - - public BooleanArrayList(final BooleanList l) { - this(l.size()); - l.getElements(0, a, 0, size = l.size()); - } - - /** - * Creates a new array list and fills it with the elements of a given array. - * - * @param a - * an array whose elements will be used to fill the array list. - */ - - public BooleanArrayList(final boolean a[]) { - this(a, 0, a.length); - } - - /** - * Creates a new array list and fills it with the elements of a given array. - * - * @param a - * an array whose elements will be used to fill the array list. - * @param offset - * the first element to use. - * @param length - * the number of elements to use. - */ - - public BooleanArrayList(final boolean a[], final int offset, - final int length) { - this(length); - System.arraycopy(a, offset, this.a, 0, length); - size = length; - } - - /** - * Creates a new array list and fills it with the elements returned by an - * iterator.. - * - * @param i - * an iterator whose returned elements will fill the array list. - */ - - public BooleanArrayList(final Iterator i) { - this(); - while (i.hasNext()) - this.add(i.next()); - } - - /** - * Creates a new array list and fills it with the elements returned by a - * type-specific iterator.. - * - * @param i - * a type-specific iterator whose returned elements will fill the - * array list. - */ - - public BooleanArrayList(final BooleanIterator i) { - this(); - while (i.hasNext()) - this.add(i.nextBoolean()); - } - - /** - * Returns the backing array of this list. - * - * @return the backing array. - */ - - public boolean[] elements() { - return a; - } - /** - * Wraps a given array into an array list of given size. - * - *

- * Note it is guaranteed that the type of the array returned by - * {@link #elements()} will be the same (see the comments in the class - * documentation). - * - * @param a - * an array to wrap. - * @param length - * the length of the resulting array list. - * @return a new array list of the given size, wrapping the given array. - */ - - public static it.unimi.dsi.fastutil.booleans.BooleanArrayList wrap(final boolean a[], final int length) { - if (length > a.length) - throw new IllegalArgumentException("The specified length (" - + length + ") is greater than the array size (" + a.length - + ")"); - final it.unimi.dsi.fastutil.booleans.BooleanArrayList l = new it.unimi.dsi.fastutil.booleans.BooleanArrayList(a, false); - l.size = length; - return l; - } - - /** - * Wraps a given array into an array list. - * - *

- * Note it is guaranteed that the type of the array returned by - * {@link #elements()} will be the same (see the comments in the class - * documentation). - * - * @param a - * an array to wrap. - * @return a new array list wrapping the given array. - */ - - public static it.unimi.dsi.fastutil.booleans.BooleanArrayList wrap(final boolean a[]) { - return wrap(a, a.length); - } - - /** - * Ensures that this array list can contain the given number of entries - * without resizing. - * - * @param capacity - * the new minimum capacity for this array list. - */ - - public void ensureCapacity(final int capacity) { - - a = BooleanArrays.ensureCapacity(a, capacity, size); - if (ASSERTS) - assert size <= a.length; - } - - /** - * Grows this array list, ensuring that it can contain the given number of - * entries without resizing, and in case enlarging it at least by a factor - * of two. - * - * @param capacity - * the new minimum capacity for this array list. - */ - - private void grow(final int capacity) { - - a = BooleanArrays.grow(a, capacity, size); - if (ASSERTS) - assert size <= a.length; - } - - public void add(final int index, final boolean k) { - ensureIndex(index); - grow(size + 1); - if (index != size) - System.arraycopy(a, index, a, index + 1, size - index); - a[index] = k; - size++; - if (ASSERTS) - assert size <= a.length; - } - - public boolean add(final boolean k) { - grow(size + 1); - a[size++] = k; - if (ASSERTS) - assert size <= a.length; - return true; - } - - public boolean getBoolean(final int index) { - if (index >= size) - throw new IndexOutOfBoundsException("Index (" + index - + ") is greater than or equal to list size (" + size + ")"); - return a[index]; - } - - public int indexOf(final boolean k) { - for (int i = 0; i < size; i++) - if (((k) == (a[i]))) - return i; - return -1; - } - - public int lastIndexOf(final boolean k) { - for (int i = size; i-- != 0;) - if (((k) == (a[i]))) - return i; - return -1; - } - - public boolean removeBoolean(final int index) { - if (index >= size) - throw new IndexOutOfBoundsException("Index (" + index - + ") is greater than or equal to list size (" + size + ")"); - final boolean old = a[index]; - size--; - if (index != size) - System.arraycopy(a, index + 1, a, index, size - index); - - if (ASSERTS) - assert size <= a.length; - return old; - } - - public boolean rem(final boolean k) { - int index = indexOf(k); - if (index == -1) - return false; - removeBoolean(index); - if (ASSERTS) - assert size <= a.length; - return true; - } - - public boolean set(final int index, final boolean k) { - if (index >= size) - throw new IndexOutOfBoundsException("Index (" + index - + ") is greater than or equal to list size (" + size + ")"); - boolean old = a[index]; - a[index] = k; - return old; - } - - public void clear() { - - size = 0; - if (ASSERTS) - assert size <= a.length; - } - - public int size() { - return size; - } - - public void size(final int size) { - if (size > a.length) - ensureCapacity(size); - if (size > this.size) - Arrays.fill(a, this.size, size, (false)); - - this.size = size; - } - - public boolean isEmpty() { - return size == 0; - } - - /** - * Trims this array list so that the capacity is equal to the size. - * - * @see java.util.ArrayList#trimToSize() - */ - public void trim() { - trim(0); - } - - /** - * Trims the backing array if it is too large. - * - * If the current array length is smaller than or equal to n, - * this method does nothing. Otherwise, it trims the array length to the - * maximum between n and {@link #size()}. - * - *

- * This method is useful when reusing lists. {@linkplain #clear() Clearing a - * list} leaves the array length untouched. If you are reusing a list many - * times, you can call this method with a typical size to avoid keeping - * around a very large array just because of a few large transient lists. - * - * @param n - * the threshold for the trimming. - */ - - public void trim(final int n) { - // TODO: use Arrays.trim() and preserve type only if necessary - if (n >= a.length || size == a.length) - return; - final boolean t[] = new boolean[Math.max(n, size)]; - System.arraycopy(a, 0, t, 0, size); - a = t; - if (ASSERTS) - assert size <= a.length; - } - - /** - * Copies element of this type-specific list into the given array using - * optimized system calls. - * - * @param from - * the start index (inclusive). - * @param a - * the destination array. - * @param offset - * the offset into the destination array where to store the first - * element copied. - * @param length - * the number of elements to be copied. - */ - - public void getElements(final int from, final boolean[] a, - final int offset, final int length) { - BooleanArrays.ensureOffsetLength(a, offset, length); - System.arraycopy(this.a, from, a, offset, length); - } - - /** - * Removes elements of this type-specific list using optimized system calls. - * - * @param from - * the start index (inclusive). - * @param to - * the end index (exclusive). - */ - public void removeElements(final int from, final int to) { - it.unimi.dsi.fastutil.Arrays.ensureFromTo(size, from, to); - System.arraycopy(a, to, a, from, size - to); - size -= (to - from); - - } - - /** - * Adds elements to this type-specific list using optimized system calls. - * - * @param index - * the index at which to add elements. - * @param a - * the array containing the elements. - * @param offset - * the offset of the first element to add. - * @param length - * the number of elements to add. - */ - public void addElements(final int index, final boolean a[], - final int offset, final int length) { - ensureIndex(index); - BooleanArrays.ensureOffsetLength(a, offset, length); - grow(size + length); - System.arraycopy(this.a, index, this.a, index + length, size - index); - System.arraycopy(a, offset, this.a, index, length); - size += length; - } - - public boolean[] toBooleanArray(boolean a[]) { - if (a == null || a.length < size) - a = new boolean[size]; - System.arraycopy(this.a, 0, a, 0, size); - return a; - } - - public boolean addAll(int index, final BooleanCollection c) { - ensureIndex(index); - int n = c.size(); - if (n == 0) - return false; - grow(size + n); - if (index != size) - System.arraycopy(a, index, a, index + n, size - index); - final BooleanIterator i = c.iterator(); - size += n; - while (n-- != 0) - a[index++] = i.nextBoolean(); - if (ASSERTS) - assert size <= a.length; - return true; - } - - public boolean addAll(final int index, final BooleanList l) { - ensureIndex(index); - final int n = l.size(); - if (n == 0) - return false; - grow(size + n); - if (index != size) - System.arraycopy(a, index, a, index + n, size - index); - l.getElements(0, a, index, n); - size += n; - if (ASSERTS) - assert size <= a.length; - return true; - } - - @Override - public boolean removeAll(final BooleanCollection c) { - final boolean[] a = this.a; - int j = 0; - for (int i = 0; i < size; i++) - if (!c.contains(a[i])) - a[j++] = a[i]; - final boolean modified = size != j; - size = j; - return modified; - } - - @Override - public boolean removeAll(final Collection c) { - final boolean[] a = this.a; - int j = 0; - for (int i = 0; i < size; i++) - if (!c.contains((Boolean.valueOf(a[i])))) - a[j++] = a[i]; - final boolean modified = size != j; - size = j; - return modified; - } - public BooleanListIterator listIterator(final int index) { - ensureIndex(index); - - return new AbstractBooleanListIterator() { - int pos = index, last = -1; - - public boolean hasNext() { - return pos < size; - } - public boolean hasPrevious() { - return pos > 0; - } - public boolean nextBoolean() { - if (!hasNext()) - throw new NoSuchElementException(); - return a[last = pos++]; - } - public boolean previousBoolean() { - if (!hasPrevious()) - throw new NoSuchElementException(); - return a[last = --pos]; - } - public int nextIndex() { - return pos; - } - public int previousIndex() { - return pos - 1; - } - public void add(boolean k) { - it.unimi.dsi.fastutil.booleans.BooleanArrayList.this.add(pos++, k); - last = -1; - } - public void set(boolean k) { - if (last == -1) - throw new IllegalStateException(); - it.unimi.dsi.fastutil.booleans.BooleanArrayList.this.set(last, k); - } - public void remove() { - if (last == -1) - throw new IllegalStateException(); - it.unimi.dsi.fastutil.booleans.BooleanArrayList.this.removeBoolean(last); - /* - * If the last operation was a next(), we are removing an - * element *before* us, and we must decrease pos - * correspondingly. - */ - if (last < pos) - pos--; - last = -1; - } - }; - } - - public it.unimi.dsi.fastutil.booleans.BooleanArrayList clone() { - it.unimi.dsi.fastutil.booleans.BooleanArrayList c = new it.unimi.dsi.fastutil.booleans.BooleanArrayList(size); - System.arraycopy(a, 0, c.a, 0, size); - c.size = size; - return c; - } - - /** - * Compares this type-specific array list to another one. - * - *

- * This method exists only for sake of efficiency. The implementation - * inherited from the abstract implementation would already work. - * - * @param l - * a type-specific array list. - * @return true if the argument contains the same elements of this - * type-specific array list. - */ - public boolean equals(final it.unimi.dsi.fastutil.booleans.BooleanArrayList l) { - if (l == this) - return true; - int s = size(); - if (s != l.size()) - return false; - final boolean[] a1 = a; - final boolean[] a2 = l.a; - - while (s-- != 0) - if (a1[s] != a2[s]) - return false; - - return true; - } - - /** - * Compares this array list to another array list. - * - *

- * This method exists only for sake of efficiency. The implementation - * inherited from the abstract implementation would already work. - * - * @param l - * an array list. - * @return a negative integer, zero, or a positive integer as this list is - * lexicographically less than, equal to, or greater than the - * argument. - */ - - public int compareTo(final it.unimi.dsi.fastutil.booleans.BooleanArrayList l) { - final int s1 = size(), s2 = l.size(); - final boolean a1[] = a, a2[] = l.a; - boolean e1, e2; - int r, i; - - for (i = 0; i < s1 && i < s2; i++) { - e1 = a1[i]; - e2 = a2[i]; - if ((r = (Boolean.compare((e1), (e2)))) != 0) - return r; - } - - return i < s2 ? -1 : (i < s1 ? 1 : 0); - } - - private void writeObject(java.io.ObjectOutputStream s) - throws java.io.IOException { - s.defaultWriteObject(); - for (int i = 0; i < size; i++) - s.writeBoolean(a[i]); - } - - private void readObject(java.io.ObjectInputStream s) - throws java.io.IOException, ClassNotFoundException { - s.defaultReadObject(); - a = new boolean[size]; - for (int i = 0; i < size; i++) - a[i] = s.readBoolean(); - } -} diff --git a/src/main/java/it/unimi/dsi/fastutil/booleans/BooleanArraySet.java b/src/main/java/it/unimi/dsi/fastutil/booleans/BooleanArraySet.java deleted file mode 100644 index 4c5a583..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/booleans/BooleanArraySet.java +++ /dev/null @@ -1,269 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Primitive-type-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2007-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.booleans; - -import it.unimi.dsi.fastutil.booleans.AbstractBooleanIterator; -import it.unimi.dsi.fastutil.booleans.AbstractBooleanSet; -import it.unimi.dsi.fastutil.booleans.BooleanArrays; -import it.unimi.dsi.fastutil.booleans.BooleanCollection; -import it.unimi.dsi.fastutil.booleans.BooleanIterator; - -import java.util.Collection; -import java.util.NoSuchElementException; - -/** - * A simple, brute-force implementation of a set based on a backing array. - * - *

- * The main purpose of this implementation is that of wrapping cleanly the - * brute-force approach to the storage of a very small number of items: just put - * them into an array and scan linearly to find an item. - */ - -public class BooleanArraySet extends AbstractBooleanSet - implements - java.io.Serializable, - Cloneable { - - private static final long serialVersionUID = 1L; - /** The backing array (valid up to {@link #size}, excluded). */ - private transient boolean[] a; - /** The number of valid entries in {@link #a}. */ - private int size; - - /** - * Creates a new array set using the given backing array. The resulting set - * will have as many elements as the array. - * - *

- * It is responsibility of the caller that the elements of a - * are distinct. - * - * @param a - * the backing array. - */ - public BooleanArraySet(final boolean[] a) { - this.a = a; - size = a.length; - } - - /** - * Creates a new empty array set. - */ - public BooleanArraySet() { - this.a = BooleanArrays.EMPTY_ARRAY; - } - - /** - * Creates a new empty array set of given initial capacity. - * - * @param capacity - * the initial capacity. - */ - public BooleanArraySet(final int capacity) { - this.a = new boolean[capacity]; - } - - /** - * Creates a new array set copying the contents of a given collection. - * - * @param c - * a collection. - */ - public BooleanArraySet(BooleanCollection c) { - this(c.size()); - addAll(c); - } - - /** - * Creates a new array set copying the contents of a given set. - * - * @param c - * a collection. - */ - public BooleanArraySet(final Collection c) { - this(c.size()); - addAll(c); - } - - /** - * Creates a new array set using the given backing array and the given - * number of elements of the array. - * - *

- * It is responsibility of the caller that the first size - * elements of a are distinct. - * - * @param a - * the backing array. - * @param size - * the number of valid elements in a. - */ - public BooleanArraySet(final boolean[] a, final int size) { - this.a = a; - this.size = size; - if (size > a.length) - throw new IllegalArgumentException("The provided size (" + size - + ") is larger than or equal to the array size (" - + a.length + ")"); - } - - private int findKey(final boolean o) { - for (int i = size; i-- != 0;) - if (((a[i]) == (o))) - return i; - return -1; - } - - @Override - public BooleanIterator iterator() { - return new AbstractBooleanIterator() { - int next = 0; - - public boolean hasNext() { - return next < size; - } - - public boolean nextBoolean() { - if (!hasNext()) - throw new NoSuchElementException(); - return a[next++]; - } - - public void remove() { - final int tail = size-- - next--; - System.arraycopy(a, next + 1, a, next, tail); - - } - }; - } - - public boolean contains(final boolean k) { - return findKey(k) != -1; - } - - public int size() { - return size; - } - - @Override - public boolean remove(final boolean k) { - final int pos = findKey(k); - if (pos == -1) - return false; - final int tail = size - pos - 1; - for (int i = 0; i < tail; i++) - a[pos + i] = a[pos + i + 1]; - size--; - - return true; - } - - @Override - public boolean add(final boolean k) { - final int pos = findKey(k); - if (pos != -1) - return false; - if (size == a.length) { - final boolean[] b = new boolean[size == 0 ? 2 : size * 2]; - for (int i = size; i-- != 0;) - b[i] = a[i]; - a = b; - } - a[size++] = k; - return true; - } - - @Override - public void clear() { - - size = 0; - } - - @Override - public boolean isEmpty() { - return size == 0; - } - - /** - * Returns a deep copy of this set. - * - *

- * This method performs a deep copy of this hash set; the data stored in the - * set, however, is not cloned. Note that this makes a difference only for - * object keys. - * - * @return a deep copy of this set. - */ - - public it.unimi.dsi.fastutil.booleans.BooleanArraySet clone() { - it.unimi.dsi.fastutil.booleans.BooleanArraySet c; - try { - c = (it.unimi.dsi.fastutil.booleans.BooleanArraySet) super.clone(); - } catch (CloneNotSupportedException cantHappen) { - throw new InternalError(); - } - c.a = a.clone(); - return c; - } - - private void writeObject(java.io.ObjectOutputStream s) - throws java.io.IOException { - s.defaultWriteObject(); - for (int i = 0; i < size; i++) - s.writeBoolean(a[i]); - } - - private void readObject(java.io.ObjectInputStream s) - throws java.io.IOException, ClassNotFoundException { - s.defaultReadObject(); - a = new boolean[size]; - for (int i = 0; i < size; i++) - a[i] = s.readBoolean(); - } - -} diff --git a/src/main/java/it/unimi/dsi/fastutil/booleans/BooleanArrays.java b/src/main/java/it/unimi/dsi/fastutil/booleans/BooleanArrays.java deleted file mode 100644 index f261a45..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/booleans/BooleanArrays.java +++ /dev/null @@ -1,2035 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Primitive-type-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * - * - * For the sorting and binary search code: - * - * Copyright (C) 1999 CERN - European Organization for Nuclear Research. - * - * Permission to use, copy, modify, distribute and sell this software and - * its documentation for any purpose is hereby granted without fee, - * provided that the above copyright notice appear in all copies and that - * both that copyright notice and this permission notice appear in - * supporting documentation. CERN makes no representations about the - * suitability of this software for any purpose. It is provided "as is" - * without expressed or implied warranty. - */ - -package it.unimi.dsi.fastutil.booleans; - -import it.unimi.dsi.fastutil.Arrays; -import it.unimi.dsi.fastutil.Hash; -import it.unimi.dsi.fastutil.booleans.BooleanComparator; -import it.unimi.dsi.fastutil.ints.IntArrays; - -import java.util.Random; -import java.util.concurrent.ForkJoinPool; -import java.util.concurrent.RecursiveAction; - -/** - * A class providing static methods and objects that do useful things with - * type-specific arrays. - * - *

- * In particular, the ensureCapacity(), grow(), - * trim() and setLength() methods allow to handle - * arrays much like array lists. This can be very useful when efficiency (or - * syntactic simplicity) reasons make array lists unsuitable. - * - *

- - - * possible to load and save arrays of primitive types as sequences of elements - * in {@link java.io.DataInput} format (i.e., not as objects) or as sequences of - * lines of text. - * - *

Sorting

- * - *

- * There are several sorting methods available. The main theme is that of - * letting you choose the sorting algorithm you prefer (i.e., trading stability - * of mergesort for no memory allocation in quicksort). Several algorithms - * provide a parallel version, that will use the - * {@linkplain Runtime#availableProcessors() number of cores available}. Some - * algorithms also provide an explicit indirect sorting facility, which - * makes it possible to sort an array using the values in another array as - * comparator. - * - *

- * All comparison-based algorithm have an implementation based on a - * type-specific comparator. - * - *

- * As a general rule, sequential radix sort is significantly faster than - * quicksort or mergesort, in particular on random-looking data. In the parallel - * case, up to a few cores parallel radix sort is still the fastest, but at some - * point quicksort exploits parallelism better. - * - *

- * If you are fine with not knowing exactly which algorithm will be run (in - * particular, not knowing exactly whether a support array will be allocated), - * the dual-pivot parallel sorts in {@link java.util.Arrays} are about 50% - * faster than the classical single-pivot implementation used here. - * - *

- * In any case, if sorting time is important I suggest that you benchmark your - * sorting load with your data distribution and on your architecture. - * - * @see java.util.Arrays - */ - -public class BooleanArrays { - private BooleanArrays() { - } - - /** A static, final, empty array. */ - public final static boolean[] EMPTY_ARRAY = {}; - /** - * Ensures that an array can contain the given number of entries. - * - *

- * If you cannot foresee whether this array will need again to be enlarged, - * you should probably use grow() instead. - * - * @param array - * an array. - * @param length - * the new minimum length for this array. - * @return array, if it contains length entries or - * more; otherwise, an array with length entries whose - * first array.length entries are the same as those of - * array. - */ - public static boolean[] ensureCapacity(final boolean[] array, - final int length) { - if (length > array.length) { - final boolean t[] = - - new boolean[length]; - - System.arraycopy(array, 0, t, 0, array.length); - return t; - } - return array; - } - - /** - * Ensures that an array can contain the given number of entries, preserving - * just a part of the array. - * - * @param array - * an array. - * @param length - * the new minimum length for this array. - * @param preserve - * the number of elements of the array that must be preserved in - * case a new allocation is necessary. - * @return array, if it can contain length entries - * or more; otherwise, an array with length entries - * whose first preserve entries are the same as those - * of array. - */ - public static boolean[] ensureCapacity(final boolean[] array, - final int length, final int preserve) { - if (length > array.length) { - final boolean t[] = - - new boolean[length]; - - System.arraycopy(array, 0, t, 0, preserve); - return t; - } - return array; - } - - /** - * Grows the given array to the maximum between the given length and the - * current length multiplied by two, provided that the given length is - * larger than the current length. - * - *

- * If you want complete control on the array growth, you should probably use - * ensureCapacity() instead. - * - * @param array - * an array. - * @param length - * the new minimum length for this array. - * @return array, if it can contain length - * entries; otherwise, an array with max(length, - * array.length/φ) entries whose first - * array.length entries are the same as those of - * array. - * */ - - public static boolean[] grow(final boolean[] array, final int length) { - if (length > array.length) { - final int newLength = (int) Math.max( - Math.min(2L * array.length, Arrays.MAX_ARRAY_SIZE), length); - final boolean t[] = - - new boolean[newLength]; - - System.arraycopy(array, 0, t, 0, array.length); - return t; - } - return array; - } - - /** - * Grows the given array to the maximum between the given length and the - * current length multiplied by two, provided that the given length is - * larger than the current length, preserving just a part of the array. - * - *

- * If you want complete control on the array growth, you should probably use - * ensureCapacity() instead. - * - * @param array - * an array. - * @param length - * the new minimum length for this array. - * @param preserve - * the number of elements of the array that must be preserved in - * case a new allocation is necessary. - * @return array, if it can contain length - * entries; otherwise, an array with max(length, - * array.length/φ) entries whose first - * preserve entries are the same as those of - * array. - * */ - - public static boolean[] grow(final boolean[] array, final int length, - final int preserve) { - - if (length > array.length) { - final int newLength = (int) Math.max( - Math.min(2L * array.length, Arrays.MAX_ARRAY_SIZE), length); - - final boolean t[] = - - new boolean[newLength]; - - System.arraycopy(array, 0, t, 0, preserve); - - return t; - } - return array; - - } - - /** - * Trims the given array to the given length. - * - * @param array - * an array. - * @param length - * the new maximum length for the array. - * @return array, if it contains length entries or - * less; otherwise, an array with length entries whose - * entries are the same as the first length entries of - * array. - * - */ - - public static boolean[] trim(final boolean[] array, final int length) { - if (length >= array.length) - return array; - final boolean t[] = - - length == 0 ? EMPTY_ARRAY : new boolean[length]; - - System.arraycopy(array, 0, t, 0, length); - return t; - } - - /** - * Sets the length of the given array. - * - * @param array - * an array. - * @param length - * the new length for the array. - * @return array, if it contains exactly length - * entries; otherwise, if it contains more than - * length entries, an array with length - * entries whose entries are the same as the first - * length entries of array; otherwise, an - * array with length entries whose first - * array.length entries are the same as those of - * array. - * - */ - - public static boolean[] setLength(final boolean[] array, final int length) { - if (length == array.length) - return array; - if (length < array.length) - return trim(array, length); - return ensureCapacity(array, length); - } - - /** - * Returns a copy of a portion of an array. - * - * @param array - * an array. - * @param offset - * the first element to copy. - * @param length - * the number of elements to copy. - * @return a new array containing length elements of - * array starting at offset. - */ - - public static boolean[] copy(final boolean[] array, final int offset, - final int length) { - ensureOffsetLength(array, offset, length); - final boolean[] a = - - length == 0 ? EMPTY_ARRAY : new boolean[length]; - - System.arraycopy(array, offset, a, 0, length); - return a; - } - - /** - * Returns a copy of an array. - * - * @param array - * an array. - * @return a copy of array. - */ - - public static boolean[] copy(final boolean[] array) { - return array.clone(); - } - - /** - * Fills the given array with the given value. - * - * @param array - * an array. - * @param value - * the new value for all elements of the array. - * @deprecated Please use the corresponding {@link java.util.Arrays} method. - */ - - @Deprecated - public static void fill(final boolean[] array, final boolean value) { - int i = array.length; - while (i-- != 0) - array[i] = value; - } - - /** - * Fills a portion of the given array with the given value. - * - * @param array - * an array. - * @param from - * the starting index of the portion to fill (inclusive). - * @param to - * the end index of the portion to fill (exclusive). - * @param value - * the new value for all elements of the specified portion of the - * array. - * @deprecated Please use the corresponding {@link java.util.Arrays} method. - */ - - @Deprecated - public static void fill(final boolean[] array, final int from, int to, - final boolean value) { - ensureFromTo(array, from, to); - if (from == 0) - while (to-- != 0) - array[to] = value; - else - for (int i = from; i < to; i++) - array[i] = value; - } - - /** - * Returns true if the two arrays are elementwise equal. - * - * @param a1 - * an array. - * @param a2 - * another array. - * @return true if the two arrays are of the same length, and their elements - * are equal. - * @deprecated Please use the corresponding {@link java.util.Arrays} method, - * which is intrinsified in recent JVMs. - */ - - @Deprecated - public static boolean equals(final boolean[] a1, final boolean a2[]) { - int i = a1.length; - if (i != a2.length) - return false; - while (i-- != 0) - if (!((a1[i]) == (a2[i]))) - return false; - return true; - } - - /** - * Ensures that a range given by its first (inclusive) and last (exclusive) - * elements fits an array. - * - *

- * This method may be used whenever an array range check is needed. - * - * @param a - * an array. - * @param from - * a start index (inclusive). - * @param to - * an end index (exclusive). - * @throws IllegalArgumentException - * if from is greater than to. - * @throws ArrayIndexOutOfBoundsException - * if from or to are greater than the - * array length or negative. - */ - public static void ensureFromTo(final boolean[] a, final int from, - final int to) { - Arrays.ensureFromTo(a.length, from, to); - } - - /** - * Ensures that a range given by an offset and a length fits an array. - * - *

- * This method may be used whenever an array range check is needed. - * - * @param a - * an array. - * @param offset - * a start index. - * @param length - * a length (the number of elements in the range). - * @throws IllegalArgumentException - * if length is negative. - * @throws ArrayIndexOutOfBoundsException - * if offset is negative or offset+ - * length is greater than the array length. - */ - public static void ensureOffsetLength(final boolean[] a, final int offset, - final int length) { - Arrays.ensureOffsetLength(a.length, offset, length); - } - - /** - * Ensures that two arrays are of the same length. - * - * @param a - * an array. - * @param b - * another array. - * @throws IllegalArgumentException - * if the two argument arrays are not of the same length. - */ - public static void ensureSameLength(final boolean[] a, final boolean[] b) { - if (a.length != b.length) - throw new IllegalArgumentException("Array size mismatch: " - + a.length + " != " + b.length); - } - - private static final int QUICKSORT_NO_REC = 16; - private static final int PARALLEL_QUICKSORT_NO_FORK = 8192; - private static final int QUICKSORT_MEDIAN_OF_9 = 128; - private static final int MERGESORT_NO_REC = 16; - - /** - * Swaps two elements of an anrray. - * - * @param x - * an array. - * @param a - * a position in {@code x}. - * @param b - * another position in {@code x}. - */ - public static void swap(final boolean x[], final int a, final int b) { - final boolean t = x[a]; - x[a] = x[b]; - x[b] = t; - } - - /** - * Swaps two sequences of elements of an array. - * - * @param x - * an array. - * @param a - * a position in {@code x}. - * @param b - * another position in {@code x}. - * @param n - * the number of elements to exchange starting at {@code a} and - * {@code b}. - */ - public static void swap(final boolean[] x, int a, int b, final int n) { - for (int i = 0; i < n; i++, a++, b++) - swap(x, a, b); - } - - private static int med3(final boolean x[], final int a, final int b, - final int c, BooleanComparator comp) { - final int ab = comp.compare(x[a], x[b]); - final int ac = comp.compare(x[a], x[c]); - final int bc = comp.compare(x[b], x[c]); - return (ab < 0 ? (bc < 0 ? b : ac < 0 ? c : a) : (bc > 0 ? b : ac > 0 - ? c - : a)); - } - - private static void selectionSort(final boolean[] a, final int from, - final int to, final BooleanComparator comp) { - for (int i = from; i < to - 1; i++) { - int m = i; - for (int j = i + 1; j < to; j++) - if (comp.compare(a[j], a[m]) < 0) - m = j; - if (m != i) { - final boolean u = a[i]; - a[i] = a[m]; - a[m] = u; - } - } - } - - private static void insertionSort(final boolean[] a, final int from, - final int to, final BooleanComparator comp) { - for (int i = from; ++i < to;) { - boolean t = a[i]; - int j = i; - for (boolean u = a[j - 1]; comp.compare(t, u) < 0; u = a[--j - 1]) { - a[j] = u; - if (from == j - 1) { - --j; - break; - } - } - a[j] = t; - } - } - - /** - * Sorts the specified range of elements according to the order induced by - * the specified comparator using quicksort. - * - *

- * The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley - * and M. Douglas McIlroy, “Engineering a Sort Function”, - * Software: Practice and Experience, 23(11), pages 1249−1265, - * 1993. - * - *

- * Note that this implementation does not allocate any object, contrarily to - * the implementation used to sort primitive types in - * {@link java.util.Arrays}, which switches to mergesort on large inputs. - * - * @param x - * the array to be sorted. - * @param from - * the index of the first element (inclusive) to be sorted. - * @param to - * the index of the last element (exclusive) to be sorted. - * @param comp - * the comparator to determine the sorting order. - * - */ - public static void quickSort(final boolean[] x, final int from, - final int to, final BooleanComparator comp) { - final int len = to - from; - // Selection sort on smallest arrays - if (len < QUICKSORT_NO_REC) { - selectionSort(x, from, to, comp); - return; - } - - // Choose a partition element, v - int m = from + len / 2; - int l = from; - int n = to - 1; - if (len > QUICKSORT_MEDIAN_OF_9) { // Big arrays, pseudomedian of 9 - int s = len / 8; - l = med3(x, l, l + s, l + 2 * s, comp); - m = med3(x, m - s, m, m + s, comp); - n = med3(x, n - 2 * s, n - s, n, comp); - } - m = med3(x, l, m, n, comp); // Mid-size, med of 3 - - final boolean v = x[m]; - - // Establish Invariant: v* (v)* v* - int a = from, b = a, c = to - 1, d = c; - while (true) { - int comparison; - while (b <= c && (comparison = comp.compare(x[b], v)) <= 0) { - if (comparison == 0) - swap(x, a++, b); - b++; - } - while (c >= b && (comparison = comp.compare(x[c], v)) >= 0) { - if (comparison == 0) - swap(x, c, d--); - c--; - } - if (b > c) - break; - swap(x, b++, c--); - } - - // Swap partition elements back to middle - int s; - s = Math.min(a - from, b - a); - swap(x, from, b - s, s); - s = Math.min(d - c, to - d - 1); - swap(x, b, to - s, s); - - // Recursively sort non-partition-elements - if ((s = b - a) > 1) - quickSort(x, from, from + s, comp); - if ((s = d - c) > 1) - quickSort(x, to - s, to, comp); - } - - /** - * Sorts an array according to the order induced by the specified comparator - * using quicksort. - * - *

- * The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley - * and M. Douglas McIlroy, “Engineering a Sort Function”, - * Software: Practice and Experience, 23(11), pages 1249−1265, - * 1993. - * - *

- * Note that this implementation does not allocate any object, contrarily to - * the implementation used to sort primitive types in - * {@link java.util.Arrays}, which switches to mergesort on large inputs. - * - * @param x - * the array to be sorted. - * @param comp - * the comparator to determine the sorting order. - * - */ - public static void quickSort(final boolean[] x, final BooleanComparator comp) { - quickSort(x, 0, x.length, comp); - } - - protected static class ForkJoinQuickSortComp extends RecursiveAction { - private static final long serialVersionUID = 1L; - private final int from; - private final int to; - private final boolean[] x; - private final BooleanComparator comp; - - public ForkJoinQuickSortComp(final boolean[] x, final int from, - final int to, final BooleanComparator comp) { - this.from = from; - this.to = to; - this.x = x; - this.comp = comp; - } - - @Override - protected void compute() { - final boolean[] x = this.x; - final int len = to - from; - if (len < PARALLEL_QUICKSORT_NO_FORK) { - quickSort(x, from, to, comp); - return; - } - // Choose a partition element, v - int m = from + len / 2; - int l = from; - int n = to - 1; - int s = len / 8; - l = med3(x, l, l + s, l + 2 * s, comp); - m = med3(x, m - s, m, m + s, comp); - n = med3(x, n - 2 * s, n - s, n, comp); - m = med3(x, l, m, n, comp); - final boolean v = x[m]; - // Establish Invariant: v* (v)* v* - int a = from, b = a, c = to - 1, d = c; - while (true) { - int comparison; - while (b <= c && (comparison = comp.compare(x[b], v)) <= 0) { - if (comparison == 0) - swap(x, a++, b); - b++; - } - while (c >= b && (comparison = comp.compare(x[c], v)) >= 0) { - if (comparison == 0) - swap(x, c, d--); - c--; - } - if (b > c) - break; - swap(x, b++, c--); - } - // Swap partition elements back to middle - int t; - s = Math.min(a - from, b - a); - swap(x, from, b - s, s); - s = Math.min(d - c, to - d - 1); - swap(x, b, to - s, s); - // Recursively sort non-partition-elements - s = b - a; - t = d - c; - if (s > 1 && t > 1) - invokeAll(new ForkJoinQuickSortComp(x, from, from + s, comp), - new ForkJoinQuickSortComp(x, to - t, to, comp)); - else if (s > 1) - invokeAll(new ForkJoinQuickSortComp(x, from, from + s, comp)); - else - invokeAll(new ForkJoinQuickSortComp(x, to - t, to, comp)); - } - } - - /** - * Sorts the specified range of elements according to the order induced by - * the specified comparator using a parallel quicksort. - * - *

- * The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley - * and M. Douglas McIlroy, “Engineering a Sort Function”, - * Software: Practice and Experience, 23(11), pages 1249−1265, - * 1993. - * - *

- * This implementation uses a {@link ForkJoinPool} executor service with - * {@link Runtime#availableProcessors()} parallel threads. - * - * @param x - * the array to be sorted. - * @param from - * the index of the first element (inclusive) to be sorted. - * @param to - * the index of the last element (exclusive) to be sorted. - * @param comp - * the comparator to determine the sorting order. - */ - public static void parallelQuickSort(final boolean[] x, final int from, - final int to, final BooleanComparator comp) { - if (to - from < PARALLEL_QUICKSORT_NO_FORK) - quickSort(x, from, to, comp); - else { - final ForkJoinPool pool = new ForkJoinPool(Runtime.getRuntime() - .availableProcessors()); - pool.invoke(new ForkJoinQuickSortComp(x, from, to, comp)); - pool.shutdown(); - } - } - - /** - * Sorts an array according to the order induced by the specified comparator - * using a parallel quicksort. - * - *

- * The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley - * and M. Douglas McIlroy, “Engineering a Sort Function”, - * Software: Practice and Experience, 23(11), pages 1249−1265, - * 1993. - * - *

- * This implementation uses a {@link ForkJoinPool} executor service with - * {@link Runtime#availableProcessors()} parallel threads. - * - * @param x - * the array to be sorted. - * @param comp - * the comparator to determine the sorting order. - */ - public static void parallelQuickSort(final boolean[] x, - final BooleanComparator comp) { - parallelQuickSort(x, 0, x.length, comp); - } - - private static int med3(final boolean x[], final int a, final int b, - final int c) { - final int ab = (Boolean.compare((x[a]), (x[b]))); - final int ac = (Boolean.compare((x[a]), (x[c]))); - final int bc = (Boolean.compare((x[b]), (x[c]))); - return (ab < 0 ? (bc < 0 ? b : ac < 0 ? c : a) : (bc > 0 ? b : ac > 0 - ? c - : a)); - } - - private static void selectionSort(final boolean[] a, final int from, - final int to) { - for (int i = from; i < to - 1; i++) { - int m = i; - for (int j = i + 1; j < to; j++) - if ((!(a[j]) && (a[m]))) - m = j; - if (m != i) { - final boolean u = a[i]; - a[i] = a[m]; - a[m] = u; - } - } - } - - private static void insertionSort(final boolean[] a, final int from, - final int to) { - for (int i = from; ++i < to;) { - boolean t = a[i]; - int j = i; - for (boolean u = a[j - 1]; (!(t) && (u)); u = a[--j - 1]) { - a[j] = u; - if (from == j - 1) { - --j; - break; - } - } - a[j] = t; - } - } - - /** - * Sorts the specified range of elements according to the natural ascending - * order using quicksort. - * - *

- * The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley - * and M. Douglas McIlroy, “Engineering a Sort Function”, - * Software: Practice and Experience, 23(11), pages 1249−1265, - * 1993. - * - *

- * Note that this implementation does not allocate any object, contrarily to - * the implementation used to sort primitive types in - * {@link java.util.Arrays}, which switches to mergesort on large inputs. - * - * @param x - * the array to be sorted. - * @param from - * the index of the first element (inclusive) to be sorted. - * @param to - * the index of the last element (exclusive) to be sorted. - */ - - public static void quickSort(final boolean[] x, final int from, final int to) { - final int len = to - from; - // Selection sort on smallest arrays - if (len < QUICKSORT_NO_REC) { - selectionSort(x, from, to); - return; - } - - // Choose a partition element, v - int m = from + len / 2; - int l = from; - int n = to - 1; - if (len > QUICKSORT_MEDIAN_OF_9) { // Big arrays, pseudomedian of 9 - int s = len / 8; - l = med3(x, l, l + s, l + 2 * s); - m = med3(x, m - s, m, m + s); - n = med3(x, n - 2 * s, n - s, n); - } - m = med3(x, l, m, n); // Mid-size, med of 3 - - final boolean v = x[m]; - - // Establish Invariant: v* (v)* v* - int a = from, b = a, c = to - 1, d = c; - while (true) { - int comparison; - while (b <= c && (comparison = (Boolean.compare((x[b]), (v)))) <= 0) { - if (comparison == 0) - swap(x, a++, b); - b++; - } - while (c >= b && (comparison = (Boolean.compare((x[c]), (v)))) >= 0) { - if (comparison == 0) - swap(x, c, d--); - c--; - } - if (b > c) - break; - swap(x, b++, c--); - } - - // Swap partition elements back to middle - int s; - s = Math.min(a - from, b - a); - swap(x, from, b - s, s); - s = Math.min(d - c, to - d - 1); - swap(x, b, to - s, s); - - // Recursively sort non-partition-elements - if ((s = b - a) > 1) - quickSort(x, from, from + s); - if ((s = d - c) > 1) - quickSort(x, to - s, to); - } - - /** - * Sorts an array according to the natural ascending order using quicksort. - * - *

- * The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley - * and M. Douglas McIlroy, “Engineering a Sort Function”, - * Software: Practice and Experience, 23(11), pages 1249−1265, - * 1993. - * - *

- * Note that this implementation does not allocate any object, contrarily to - * the implementation used to sort primitive types in - * {@link java.util.Arrays}, which switches to mergesort on large inputs. - * - * @param x - * the array to be sorted. - * - */ - public static void quickSort(final boolean[] x) { - quickSort(x, 0, x.length); - } - - protected static class ForkJoinQuickSort extends RecursiveAction { - private static final long serialVersionUID = 1L; - private final int from; - private final int to; - private final boolean[] x; - - public ForkJoinQuickSort(final boolean[] x, final int from, final int to) { - this.from = from; - this.to = to; - this.x = x; - } - - @Override - protected void compute() { - final boolean[] x = this.x; - final int len = to - from; - if (len < PARALLEL_QUICKSORT_NO_FORK) { - quickSort(x, from, to); - return; - } - // Choose a partition element, v - int m = from + len / 2; - int l = from; - int n = to - 1; - int s = len / 8; - l = med3(x, l, l + s, l + 2 * s); - m = med3(x, m - s, m, m + s); - n = med3(x, n - 2 * s, n - s, n); - m = med3(x, l, m, n); - final boolean v = x[m]; - // Establish Invariant: v* (v)* v* - int a = from, b = a, c = to - 1, d = c; - while (true) { - int comparison; - while (b <= c - && (comparison = (Boolean.compare((x[b]), (v)))) <= 0) { - if (comparison == 0) - swap(x, a++, b); - b++; - } - while (c >= b - && (comparison = (Boolean.compare((x[c]), (v)))) >= 0) { - if (comparison == 0) - swap(x, c, d--); - c--; - } - if (b > c) - break; - swap(x, b++, c--); - } - // Swap partition elements back to middle - int t; - s = Math.min(a - from, b - a); - swap(x, from, b - s, s); - s = Math.min(d - c, to - d - 1); - swap(x, b, to - s, s); - // Recursively sort non-partition-elements - s = b - a; - t = d - c; - if (s > 1 && t > 1) - invokeAll(new ForkJoinQuickSort(x, from, from + s), - new ForkJoinQuickSort(x, to - t, to)); - else if (s > 1) - invokeAll(new ForkJoinQuickSort(x, from, from + s)); - else - invokeAll(new ForkJoinQuickSort(x, to - t, to)); - } - } - - /** - * Sorts the specified range of elements according to the natural ascending - * order using a parallel quicksort. - * - *

- * The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley - * and M. Douglas McIlroy, “Engineering a Sort Function”, - * Software: Practice and Experience, 23(11), pages 1249−1265, - * 1993. - * - *

- * This implementation uses a {@link ForkJoinPool} executor service with - * {@link Runtime#availableProcessors()} parallel threads. - * - * @param x - * the array to be sorted. - * @param from - * the index of the first element (inclusive) to be sorted. - * @param to - * the index of the last element (exclusive) to be sorted. - */ - public static void parallelQuickSort(final boolean[] x, final int from, - final int to) { - if (to - from < PARALLEL_QUICKSORT_NO_FORK) - quickSort(x, from, to); - else { - final ForkJoinPool pool = new ForkJoinPool(Runtime.getRuntime() - .availableProcessors()); - pool.invoke(new ForkJoinQuickSort(x, from, to)); - pool.shutdown(); - } - } - - /** - * Sorts an array according to the natural ascending order using a parallel - * quicksort. - * - *

- * The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley - * and M. Douglas McIlroy, “Engineering a Sort Function”, - * Software: Practice and Experience, 23(11), pages 1249−1265, - * 1993. - * - *

- * This implementation uses a {@link ForkJoinPool} executor service with - * {@link Runtime#availableProcessors()} parallel threads. - * - * @param x - * the array to be sorted. - * - */ - public static void parallelQuickSort(final boolean[] x) { - parallelQuickSort(x, 0, x.length); - } - - private static int med3Indirect(final int perm[], final boolean x[], - final int a, final int b, final int c) { - final boolean aa = x[perm[a]]; - final boolean bb = x[perm[b]]; - final boolean cc = x[perm[c]]; - final int ab = (Boolean.compare((aa), (bb))); - final int ac = (Boolean.compare((aa), (cc))); - final int bc = (Boolean.compare((bb), (cc))); - return (ab < 0 ? (bc < 0 ? b : ac < 0 ? c : a) : (bc > 0 ? b : ac > 0 - ? c - : a)); - } - - private static void insertionSortIndirect(final int[] perm, - final boolean[] a, final int from, final int to) { - for (int i = from; ++i < to;) { - int t = perm[i]; - int j = i; - for (int u = perm[j - 1]; (!(a[t]) && (a[u])); u = perm[--j - 1]) { - perm[j] = u; - if (from == j - 1) { - --j; - break; - } - } - perm[j] = t; - } - } - - /** - * Sorts the specified range of elements according to the natural ascending - * order using indirect quicksort. - * - *

- * The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley - * and M. Douglas McIlroy, “Engineering a Sort Function”, - * Software: Practice and Experience, 23(11), pages 1249−1265, - * 1993. - * - *

- * This method implement an indirect sort. The elements of - * perm (which must be exactly the numbers in the interval - * [0..perm.length)) will be permuted so that - * x[ perm[ i ] ] ≤ x[ perm[ i + 1 ] ]. - * - *

- * Note that this implementation does not allocate any object, contrarily to - * the implementation used to sort primitive types in - * {@link java.util.Arrays}, which switches to mergesort on large inputs. - * - * @param perm - * a permutation array indexing {@code x}. - * @param x - * the array to be sorted. - * @param from - * the index of the first element (inclusive) to be sorted. - * @param to - * the index of the last element (exclusive) to be sorted. - */ - - public static void quickSortIndirect(final int[] perm, final boolean[] x, - final int from, final int to) { - final int len = to - from; - // Selection sort on smallest arrays - if (len < QUICKSORT_NO_REC) { - insertionSortIndirect(perm, x, from, to); - return; - } - - // Choose a partition element, v - int m = from + len / 2; - int l = from; - int n = to - 1; - if (len > QUICKSORT_MEDIAN_OF_9) { // Big arrays, pseudomedian of 9 - int s = len / 8; - l = med3Indirect(perm, x, l, l + s, l + 2 * s); - m = med3Indirect(perm, x, m - s, m, m + s); - n = med3Indirect(perm, x, n - 2 * s, n - s, n); - } - m = med3Indirect(perm, x, l, m, n); // Mid-size, med of 3 - - final boolean v = x[perm[m]]; - - // Establish Invariant: v* (v)* v* - int a = from, b = a, c = to - 1, d = c; - while (true) { - int comparison; - while (b <= c - && (comparison = (Boolean.compare((x[perm[b]]), (v)))) <= 0) { - if (comparison == 0) - IntArrays.swap(perm, a++, b); - b++; - } - while (c >= b - && (comparison = (Boolean.compare((x[perm[c]]), (v)))) >= 0) { - if (comparison == 0) - IntArrays.swap(perm, c, d--); - c--; - } - if (b > c) - break; - IntArrays.swap(perm, b++, c--); - } - - // Swap partition elements back to middle - int s; - s = Math.min(a - from, b - a); - IntArrays.swap(perm, from, b - s, s); - s = Math.min(d - c, to - d - 1); - IntArrays.swap(perm, b, to - s, s); - - // Recursively sort non-partition-elements - if ((s = b - a) > 1) - quickSortIndirect(perm, x, from, from + s); - if ((s = d - c) > 1) - quickSortIndirect(perm, x, to - s, to); - } - - /** - * Sorts an array according to the natural ascending order using indirect - * quicksort. - * - *

- * The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley - * and M. Douglas McIlroy, “Engineering a Sort Function”, - * Software: Practice and Experience, 23(11), pages 1249−1265, - * 1993. - * - *

- * This method implement an indirect sort. The elements of - * perm (which must be exactly the numbers in the interval - * [0..perm.length)) will be permuted so that - * x[ perm[ i ] ] ≤ x[ perm[ i + 1 ] ]. - * - *

- * Note that this implementation does not allocate any object, contrarily to - * the implementation used to sort primitive types in - * {@link java.util.Arrays}, which switches to mergesort on large inputs. - * - * @param perm - * a permutation array indexing {@code x}. - * @param x - * the array to be sorted. - */ - public static void quickSortIndirect(final int perm[], final boolean[] x) { - quickSortIndirect(perm, x, 0, x.length); - } - - protected static class ForkJoinQuickSortIndirect extends RecursiveAction { - private static final long serialVersionUID = 1L; - private final int from; - private final int to; - private final int[] perm; - private final boolean[] x; - - public ForkJoinQuickSortIndirect(final int perm[], final boolean[] x, - final int from, final int to) { - this.from = from; - this.to = to; - this.x = x; - this.perm = perm; - } - - @Override - protected void compute() { - final boolean[] x = this.x; - final int len = to - from; - if (len < PARALLEL_QUICKSORT_NO_FORK) { - quickSortIndirect(perm, x, from, to); - return; - } - // Choose a partition element, v - int m = from + len / 2; - int l = from; - int n = to - 1; - int s = len / 8; - l = med3Indirect(perm, x, l, l + s, l + 2 * s); - m = med3Indirect(perm, x, m - s, m, m + s); - n = med3Indirect(perm, x, n - 2 * s, n - s, n); - m = med3Indirect(perm, x, l, m, n); - final boolean v = x[perm[m]]; - // Establish Invariant: v* (v)* v* - int a = from, b = a, c = to - 1, d = c; - while (true) { - int comparison; - while (b <= c - && (comparison = (Boolean.compare((x[perm[b]]), (v)))) <= 0) { - if (comparison == 0) - IntArrays.swap(perm, a++, b); - b++; - } - while (c >= b - && (comparison = (Boolean.compare((x[perm[c]]), (v)))) >= 0) { - if (comparison == 0) - IntArrays.swap(perm, c, d--); - c--; - } - if (b > c) - break; - IntArrays.swap(perm, b++, c--); - } - // Swap partition elements back to middle - int t; - s = Math.min(a - from, b - a); - IntArrays.swap(perm, from, b - s, s); - s = Math.min(d - c, to - d - 1); - IntArrays.swap(perm, b, to - s, s); - // Recursively sort non-partition-elements - s = b - a; - t = d - c; - if (s > 1 && t > 1) - invokeAll( - new ForkJoinQuickSortIndirect(perm, x, from, from + s), - new ForkJoinQuickSortIndirect(perm, x, to - t, to)); - else if (s > 1) - invokeAll(new ForkJoinQuickSortIndirect(perm, x, from, from + s)); - else - invokeAll(new ForkJoinQuickSortIndirect(perm, x, to - t, to)); - } - } - - /** - * Sorts the specified range of elements according to the natural ascending - * order using a parallel indirect quicksort. - * - *

- * The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley - * and M. Douglas McIlroy, “Engineering a Sort Function”, - * Software: Practice and Experience, 23(11), pages 1249−1265, - * 1993. - * - *

- * This method implement an indirect sort. The elements of - * perm (which must be exactly the numbers in the interval - * [0..perm.length)) will be permuted so that - * x[ perm[ i ] ] ≤ x[ perm[ i + 1 ] ]. - * - *

- * This implementation uses a {@link ForkJoinPool} executor service with - * {@link Runtime#availableProcessors()} parallel threads. - * - * @param perm - * a permutation array indexing {@code x}. - * @param x - * the array to be sorted. - * @param from - * the index of the first element (inclusive) to be sorted. - * @param to - * the index of the last element (exclusive) to be sorted. - */ - public static void parallelQuickSortIndirect(final int[] perm, - final boolean[] x, final int from, final int to) { - if (to - from < PARALLEL_QUICKSORT_NO_FORK) - quickSortIndirect(perm, x, from, to); - else { - final ForkJoinPool pool = new ForkJoinPool(Runtime.getRuntime() - .availableProcessors()); - pool.invoke(new ForkJoinQuickSortIndirect(perm, x, from, to)); - pool.shutdown(); - } - } - - /** - * Sorts an array according to the natural ascending order using a parallel - * indirect quicksort. - * - *

- * The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley - * and M. Douglas McIlroy, “Engineering a Sort Function”, - * Software: Practice and Experience, 23(11), pages 1249−1265, - * 1993. - * - *

- * This method implement an indirect sort. The elements of - * perm (which must be exactly the numbers in the interval - * [0..perm.length)) will be permuted so that - * x[ perm[ i ] ] ≤ x[ perm[ i + 1 ] ]. - * - *

- * This implementation uses a {@link ForkJoinPool} executor service with - * {@link Runtime#availableProcessors()} parallel threads. - * - * @param perm - * a permutation array indexing {@code x}. - * @param x - * the array to be sorted. - * - */ - public static void parallelQuickSortIndirect(final int perm[], - final boolean[] x) { - parallelQuickSortIndirect(perm, x, 0, x.length); - } - - /** - * Stabilizes a permutation. - * - *

- * This method can be used to stabilize the permutation generated by an - * indirect sorting, assuming that initially the permutation array was in - * ascending order (e.g., the identity, as usually happens). This method - * scans the permutation, and for each non-singleton block of elements with - * the same associated values in {@code x}, permutes them in ascending order. - * The resulting permutation corresponds to a stable sort. - * - *

- * Usually combining an unstable indirect sort and this method is more - * efficient than using a stable sort, as most stable sort algorithms - * require a support array. - * - *

- * More precisely, assuming that - * x[ perm[ i ] ] ≤ x[ perm[ i + 1 ] ], after stabilization - * we will also have that x[ perm[ i ] ] = x[ perm[ i + 1 ] ] - * implies perm[ i ] ≤ perm[ i + 1 ]. - * - * @param perm - * a permutation array indexing {@code x} so that it is sorted. - * @param x - * the sorted array to be stabilized. - * @param from - * the index of the first element (inclusive) to be stabilized. - * @param to - * the index of the last element (exclusive) to be stabilized. - */ - public static void stabilize(final int perm[], final boolean[] x, - final int from, final int to) { - int curr = from; - for (int i = from + 1; i < to; i++) { - if (x[perm[i]] != x[perm[curr]]) { - if (i - curr > 1) - IntArrays.parallelQuickSort(perm, curr, i); - curr = i; - } - } - if (to - curr > 1) - IntArrays.parallelQuickSort(perm, curr, to); - } - - /** - * Stabilizes a permutation. - * - *

- * This method can be used to stabilize the permutation generated by an - * indirect sorting, assuming that initially the permutation array was in - * ascending order (e.g., the identity, as usually happens). This method - * scans the permutation, and for each non-singleton block of elements with - * the same associated values in {@code x}, permutes them in ascending order. - * The resulting permutation corresponds to a stable sort. - * - *

- * Usually combining an unstable indirect sort and this method is more - * efficient than using a stable sort, as most stable sort algorithms - * require a support array. - * - *

- * More precisely, assuming that - * x[ perm[ i ] ] ≤ x[ perm[ i + 1 ] ], after stabilization - * we will also have that x[ perm[ i ] ] = x[ perm[ i + 1 ] ] - * implies perm[ i ] ≤ perm[ i + 1 ]. - * - * @param perm - * a permutation array indexing {@code x} so that it is sorted. - * @param x - * the sorted array to be stabilized. - */ - public static void stabilize(final int perm[], final boolean[] x) { - stabilize(perm, x, 0, perm.length); - } - - private static int med3(final boolean x[], final boolean[] y, final int a, - final int b, final int c) { - int t; - final int ab = (t = (Boolean.compare((x[a]), (x[b])))) == 0 ? (Boolean - .compare((y[a]), (y[b]))) : t; - final int ac = (t = (Boolean.compare((x[a]), (x[c])))) == 0 ? (Boolean - .compare((y[a]), (y[c]))) : t; - final int bc = (t = (Boolean.compare((x[b]), (x[c])))) == 0 ? (Boolean - .compare((y[b]), (y[c]))) : t; - return (ab < 0 ? (bc < 0 ? b : ac < 0 ? c : a) : (bc > 0 ? b : ac > 0 - ? c - : a)); - } - - private static void swap(final boolean x[], final boolean[] y, final int a, - final int b) { - final boolean t = x[a]; - final boolean u = y[a]; - x[a] = x[b]; - y[a] = y[b]; - x[b] = t; - y[b] = u; - } - - private static void swap(final boolean[] x, final boolean[] y, int a, - int b, final int n) { - for (int i = 0; i < n; i++, a++, b++) - swap(x, y, a, b); - } - - private static void selectionSort(final boolean[] a, final boolean[] b, - final int from, final int to) { - for (int i = from; i < to - 1; i++) { - int m = i, u; - for (int j = i + 1; j < to; j++) - if ((u = (Boolean.compare((a[j]), (a[m])))) < 0 || u == 0 - && (!(b[j]) && (b[m]))) - m = j; - - if (m != i) { - boolean t = a[i]; - a[i] = a[m]; - a[m] = t; - t = b[i]; - b[i] = b[m]; - b[m] = t; - } - } - } - - /** - * Sorts the specified range of elements of two arrays according to the - * natural lexicographical ascending order using quicksort. - * - *

- * The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley - * and M. Douglas McIlroy, “Engineering a Sort Function”, - * Software: Practice and Experience, 23(11), pages 1249−1265, - * 1993. - * - *

- * This method implements a lexicographical sorting of the - * arguments. Pairs of elements in the same position in the two provided - * arrays will be considered a single key, and permuted accordingly. In the - * end, either x[ i ] < x[ i + 1 ] or x[ i ] - * == x[ i + 1 ] and y[ i ] ≤ y[ i + 1 ]. - * - * @param x - * the first array to be sorted. - * @param y - * the second array to be sorted. - * @param from - * the index of the first element (inclusive) to be sorted. - * @param to - * the index of the last element (exclusive) to be sorted. - */ - - public static void quickSort(final boolean[] x, final boolean[] y, - final int from, final int to) { - final int len = to - from; - if (len < QUICKSORT_NO_REC) { - selectionSort(x, y, from, to); - return; - } - // Choose a partition element, v - int m = from + len / 2; - int l = from; - int n = to - 1; - if (len > QUICKSORT_MEDIAN_OF_9) { // Big arrays, pseudomedian of 9 - int s = len / 8; - l = med3(x, y, l, l + s, l + 2 * s); - m = med3(x, y, m - s, m, m + s); - n = med3(x, y, n - 2 * s, n - s, n); - } - m = med3(x, y, l, m, n); // Mid-size, med of 3 - final boolean v = x[m], w = y[m]; - // Establish Invariant: v* (v)* v* - int a = from, b = a, c = to - 1, d = c; - while (true) { - int comparison, t; - while (b <= c - && (comparison = (t = (Boolean.compare((x[b]), (v)))) == 0 - ? (Boolean.compare((y[b]), (w))) - : t) <= 0) { - if (comparison == 0) - swap(x, y, a++, b); - b++; - } - while (c >= b - && (comparison = (t = (Boolean.compare((x[c]), (v)))) == 0 - ? (Boolean.compare((y[c]), (w))) - : t) >= 0) { - if (comparison == 0) - swap(x, y, c, d--); - c--; - } - if (b > c) - break; - swap(x, y, b++, c--); - } - // Swap partition elements back to middle - int s; - s = Math.min(a - from, b - a); - swap(x, y, from, b - s, s); - s = Math.min(d - c, to - d - 1); - swap(x, y, b, to - s, s); - // Recursively sort non-partition-elements - if ((s = b - a) > 1) - quickSort(x, y, from, from + s); - if ((s = d - c) > 1) - quickSort(x, y, to - s, to); - } - - /** - * Sorts two arrays according to the natural lexicographical ascending order - * using quicksort. - * - *

- * The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley - * and M. Douglas McIlroy, “Engineering a Sort Function”, - * Software: Practice and Experience, 23(11), pages 1249−1265, - * 1993. - * - *

- * This method implements a lexicographical sorting of the - * arguments. Pairs of elements in the same position in the two provided - * arrays will be considered a single key, and permuted accordingly. In the - * end, either x[ i ] < x[ i + 1 ] or x[ i ] - * == x[ i + 1 ] and y[ i ] ≤ y[ i + 1 ]. - * - * @param x - * the first array to be sorted. - * @param y - * the second array to be sorted. - */ - public static void quickSort(final boolean[] x, final boolean[] y) { - ensureSameLength(x, y); - quickSort(x, y, 0, x.length); - } - - protected static class ForkJoinQuickSort2 extends RecursiveAction { - private static final long serialVersionUID = 1L; - private final int from; - private final int to; - private final boolean[] x, y; - - public ForkJoinQuickSort2(final boolean[] x, final boolean[] y, - final int from, final int to) { - this.from = from; - this.to = to; - this.x = x; - this.y = y; - } - - @Override - protected void compute() { - final boolean[] x = this.x; - final boolean[] y = this.y; - final int len = to - from; - if (len < PARALLEL_QUICKSORT_NO_FORK) { - quickSort(x, y, from, to); - return; - } - // Choose a partition element, v - int m = from + len / 2; - int l = from; - int n = to - 1; - int s = len / 8; - l = med3(x, y, l, l + s, l + 2 * s); - m = med3(x, y, m - s, m, m + s); - n = med3(x, y, n - 2 * s, n - s, n); - m = med3(x, y, l, m, n); - final boolean v = x[m], w = y[m]; - // Establish Invariant: v* (v)* v* - int a = from, b = a, c = to - 1, d = c; - while (true) { - int comparison, t; - while (b <= c - && (comparison = (t = (Boolean.compare((x[b]), (v)))) == 0 - ? (Boolean.compare((y[b]), (w))) - : t) <= 0) { - if (comparison == 0) - swap(x, y, a++, b); - b++; - } - while (c >= b - && (comparison = (t = (Boolean.compare((x[c]), (v)))) == 0 - ? (Boolean.compare((y[c]), (w))) - : t) >= 0) { - if (comparison == 0) - swap(x, y, c, d--); - c--; - } - if (b > c) - break; - swap(x, y, b++, c--); - } - // Swap partition elements back to middle - int t; - s = Math.min(a - from, b - a); - swap(x, y, from, b - s, s); - s = Math.min(d - c, to - d - 1); - swap(x, y, b, to - s, s); - s = b - a; - t = d - c; - // Recursively sort non-partition-elements - if (s > 1 && t > 1) - invokeAll(new ForkJoinQuickSort2(x, y, from, from + s), - new ForkJoinQuickSort2(x, y, to - t, to)); - else if (s > 1) - invokeAll(new ForkJoinQuickSort2(x, y, from, from + s)); - else - invokeAll(new ForkJoinQuickSort2(x, y, to - t, to)); - } - } - - /** - * Sorts the specified range of elements of two arrays according to the - * natural lexicographical ascending order using a parallel quicksort. - * - *

- * The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley - * and M. Douglas McIlroy, “Engineering a Sort Function”, - * Software: Practice and Experience, 23(11), pages 1249−1265, - * 1993. - * - *

- * This method implements a lexicographical sorting of the - * arguments. Pairs of elements in the same position in the two provided - * arrays will be considered a single key, and permuted accordingly. In the - * end, either x[ i ] < x[ i + 1 ] or x[ i ] - * == x[ i + 1 ] and y[ i ] ≤ y[ i + 1 ]. - * - *

- * This implementation uses a {@link ForkJoinPool} executor service with - * {@link Runtime#availableProcessors()} parallel threads. - * - * @param x - * the first array to be sorted. - * @param y - * the second array to be sorted. - * @param from - * the index of the first element (inclusive) to be sorted. - * @param to - * the index of the last element (exclusive) to be sorted. - */ - public static void parallelQuickSort(final boolean[] x, final boolean[] y, - final int from, final int to) { - if (to - from < PARALLEL_QUICKSORT_NO_FORK) - quickSort(x, y, from, to); - final ForkJoinPool pool = new ForkJoinPool(Runtime.getRuntime() - .availableProcessors()); - pool.invoke(new ForkJoinQuickSort2(x, y, from, to)); - pool.shutdown(); - } - - /** - * Sorts two arrays according to the natural lexicographical ascending order - * using a parallel quicksort. - * - *

- * The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley - * and M. Douglas McIlroy, “Engineering a Sort Function”, - * Software: Practice and Experience, 23(11), pages 1249−1265, - * 1993. - * - *

- * This method implements a lexicographical sorting of the - * arguments. Pairs of elements in the same position in the two provided - * arrays will be considered a single key, and permuted accordingly. In the - * end, either x[ i ] < x[ i + 1 ] or x[ i ] - * == x[ i + 1 ] and y[ i ] ≤ y[ i + 1 ]. - * - *

- * This implementation uses a {@link ForkJoinPool} executor service with - * {@link Runtime#availableProcessors()} parallel threads. - * - * @param x - * the first array to be sorted. - * @param y - * the second array to be sorted. - */ - public static void parallelQuickSort(final boolean[] x, final boolean[] y) { - ensureSameLength(x, y); - parallelQuickSort(x, y, 0, x.length); - } - - /** - * Sorts the specified range of elements according to the natural ascending - * order using mergesort, using a given pre-filled support array. - * - *

- * This sort is guaranteed to be stable: equal elements will not be - * reordered as a result of the sort. Moreover, no support arrays will be - * allocated. - * - * @param a - * the array to be sorted. - * @param from - * the index of the first element (inclusive) to be sorted. - * @param to - * the index of the last element (exclusive) to be sorted. - * @param supp - * a support array containing at least to elements, - * and whose entries are identical to those of {@code a} in the - * specified range. - */ - - public static void mergeSort(final boolean a[], final int from, - final int to, final boolean supp[]) { - int len = to - from; - - // Insertion sort on smallest arrays - if (len < MERGESORT_NO_REC) { - insertionSort(a, from, to); - return; - } - - // Recursively sort halves of a into supp - final int mid = (from + to) >>> 1; - mergeSort(supp, from, mid, a); - mergeSort(supp, mid, to, a); - - // If list is already sorted, just copy from supp to a. This is an - // optimization that results in faster sorts for nearly ordered lists. - if ((!(supp[mid - 1]) || (supp[mid]))) { - System.arraycopy(supp, from, a, from, len); - return; - } - - // Merge sorted halves (now in supp) into a - for (int i = from, p = from, q = mid; i < to; i++) { - if (q >= to || p < mid && (!(supp[p]) || (supp[q]))) - a[i] = supp[p++]; - else - a[i] = supp[q++]; - } - } - - /** - * Sorts the specified range of elements according to the natural ascending - * order using mergesort. - * - *

- * This sort is guaranteed to be stable: equal elements will not be - * reordered as a result of the sort. An array as large as a - * will be allocated by this method. - * - * @param a - * the array to be sorted. - * @param from - * the index of the first element (inclusive) to be sorted. - * @param to - * the index of the last element (exclusive) to be sorted. - */ - public static void mergeSort(final boolean a[], final int from, final int to) { - mergeSort(a, from, to, a.clone()); - } - - /** - * Sorts an array according to the natural ascending order using mergesort. - * - *

- * This sort is guaranteed to be stable: equal elements will not be - * reordered as a result of the sort. An array as large as a - * will be allocated by this method. - * - * @param a - * the array to be sorted. - */ - public static void mergeSort(final boolean a[]) { - mergeSort(a, 0, a.length); - } - - /** - * Sorts the specified range of elements according to the order induced by - * the specified comparator using mergesort, using a given pre-filled - * support array. - * - *

- * This sort is guaranteed to be stable: equal elements will not be - * reordered as a result of the sort. Moreover, no support arrays will be - * allocated. - * - * @param a - * the array to be sorted. - * @param from - * the index of the first element (inclusive) to be sorted. - * @param to - * the index of the last element (exclusive) to be sorted. - * @param comp - * the comparator to determine the sorting order. - * @param supp - * a support array containing at least to elements, - * and whose entries are identical to those of {@code a} in the - * specified range. - */ - public static void mergeSort(final boolean a[], final int from, - final int to, BooleanComparator comp, final boolean supp[]) { - int len = to - from; - - // Insertion sort on smallest arrays - if (len < MERGESORT_NO_REC) { - insertionSort(a, from, to, comp); - return; - } - - // Recursively sort halves of a into supp - final int mid = (from + to) >>> 1; - mergeSort(supp, from, mid, comp, a); - mergeSort(supp, mid, to, comp, a); - - // If list is already sorted, just copy from supp to a. This is an - // optimization that results in faster sorts for nearly ordered lists. - if (comp.compare(supp[mid - 1], supp[mid]) <= 0) { - System.arraycopy(supp, from, a, from, len); - return; - } - - // Merge sorted halves (now in supp) into a - for (int i = from, p = from, q = mid; i < to; i++) { - if (q >= to || p < mid && comp.compare(supp[p], supp[q]) <= 0) - a[i] = supp[p++]; - else - a[i] = supp[q++]; - } - } - - /** - * Sorts the specified range of elements according to the order induced by - * the specified comparator using mergesort. - * - *

- * This sort is guaranteed to be stable: equal elements will not be - * reordered as a result of the sort. An array as large as a - * will be allocated by this method. - * - * @param a - * the array to be sorted. - * @param from - * the index of the first element (inclusive) to be sorted. - * @param to - * the index of the last element (exclusive) to be sorted. - * @param comp - * the comparator to determine the sorting order. - */ - public static void mergeSort(final boolean a[], final int from, - final int to, BooleanComparator comp) { - mergeSort(a, from, to, comp, a.clone()); - } - - /** - * Sorts an array according to the order induced by the specified comparator - * using mergesort. - * - *

- * This sort is guaranteed to be stable: equal elements will not be - * reordered as a result of the sort. An array as large as a - * will be allocated by this method. - * - * @param a - * the array to be sorted. - * @param comp - * the comparator to determine the sorting order. - */ - public static void mergeSort(final boolean a[], BooleanComparator comp) { - mergeSort(a, 0, a.length, comp); - } - /** - * Shuffles the specified array fragment using the specified pseudorandom - * number generator. - * - * @param a - * the array to be shuffled. - * @param from - * the index of the first element (inclusive) to be shuffled. - * @param to - * the index of the last element (exclusive) to be shuffled. - * @param random - * a pseudorandom number generator (please use a XorShift* generator). - * @return a. - */ - public static boolean[] shuffle(final boolean[] a, final int from, - final int to, final Random random) { - for (int i = to - from; i-- != 0;) { - final int p = random.nextInt(i + 1); - final boolean t = a[from + i]; - a[from + i] = a[from + p]; - a[from + p] = t; - } - return a; - } - - /** - * Shuffles the specified array using the specified pseudorandom number - * generator. - * - * @param a - * the array to be shuffled. - * @param random - * a pseudorandom number generator (please use a XorShift* generator). - * @return a. - */ - public static boolean[] shuffle(final boolean[] a, final Random random) { - for (int i = a.length; i-- != 0;) { - final int p = random.nextInt(i + 1); - final boolean t = a[i]; - a[i] = a[p]; - a[p] = t; - } - return a; - } - - /** - * Reverses the order of the elements in the specified array. - * - * @param a - * the array to be reversed. - * @return a. - */ - public static boolean[] reverse(final boolean[] a) { - final int length = a.length; - for (int i = length / 2; i-- != 0;) { - final boolean t = a[length - i - 1]; - a[length - i - 1] = a[i]; - a[i] = t; - } - return a; - } - - /** - * Reverses the order of the elements in the specified array fragment. - * - * @param a - * the array to be reversed. - * @param from - * the index of the first element (inclusive) to be reversed. - * @param to - * the index of the last element (exclusive) to be reversed. - * @return a. - */ - public static boolean[] reverse(final boolean[] a, final int from, - final int to) { - final int length = to - from; - for (int i = length / 2; i-- != 0;) { - final boolean t = a[from + length - i - 1]; - a[from + length - i - 1] = a[from + i]; - a[from + i] = t; - } - return a; - } - - /** A type-specific content-based hash strategy for arrays. */ - - private static final class ArrayHashStrategy - implements - Hash.Strategy, - java.io.Serializable { - private static final long serialVersionUID = -7046029254386353129L; - - public int hashCode(final boolean[] o) { - return java.util.Arrays.hashCode(o); - } - - public boolean equals(final boolean[] a, final boolean[] b) { - return java.util.Arrays.equals(a, b); - } - } - - /** - * A type-specific content-based hash strategy for arrays. - * - *

- * This hash strategy may be used in custom hash collections whenever keys - * are arrays, and they must be considered equal by content. This strategy - * will handle null correctly, and it is serializable. - */ - - public final static Hash.Strategy HASH_STRATEGY = new ArrayHashStrategy(); - -} diff --git a/src/main/java/it/unimi/dsi/fastutil/booleans/BooleanBidirectionalIterator.java b/src/main/java/it/unimi/dsi/fastutil/booleans/BooleanBidirectionalIterator.java deleted file mode 100644 index b7ca651..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/booleans/BooleanBidirectionalIterator.java +++ /dev/null @@ -1,89 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Primitive-type-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.booleans; - -import it.unimi.dsi.fastutil.BidirectionalIterator; -import it.unimi.dsi.fastutil.booleans.BooleanIterator; -import it.unimi.dsi.fastutil.objects.ObjectBidirectionalIterator; - -/** - * A type-specific bidirectional iterator; provides an additional method to - * avoid (un)boxing, and the possibility to skip elements backwards. - * - * @see BidirectionalIterator - */ - -public interface BooleanBidirectionalIterator - extends - BooleanIterator, - ObjectBidirectionalIterator { - - /** - * Returns the previous element as a primitive type. - * - * @return the previous element in the iteration. - * @see java.util.ListIterator#previous() - */ - - boolean previousBoolean(); - - /** - * Moves back for the given number of elements. - * - *

- * The effect of this call is exactly the same as that of calling - * {@link #previous()} for n times (possibly stopping if - * {@link #hasPrevious()} becomes false). - * - * @param n - * the number of elements to skip back. - * @return the number of elements actually skipped. - * @see java.util.Iterator#next() - */ - - int back(int n); -} diff --git a/src/main/java/it/unimi/dsi/fastutil/booleans/BooleanCollection.java b/src/main/java/it/unimi/dsi/fastutil/booleans/BooleanCollection.java deleted file mode 100644 index 7e7cffc..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/booleans/BooleanCollection.java +++ /dev/null @@ -1,190 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Primitive-type-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.booleans; - -import it.unimi.dsi.fastutil.booleans.BooleanIterable; -import it.unimi.dsi.fastutil.booleans.BooleanIterator; - -import java.util.Collection; - -/** - * A type-specific {@link Collection}; provides some additional methods that use - * polymorphism to avoid (un)boxing. - * - *

- * Additionally, this class defines strengthens (again) {@link #iterator()} and - * defines a slightly different semantics for {@link #toArray(Object[])}. - * - * @see Collection - */ - -public interface BooleanCollection - extends Collection, BooleanIterable { - - /** - * Returns a type-specific iterator on the elements of this collection. - * - *

- * Note that this specification strengthens the one given in - * {@link Iterable#iterator()}, which was already strengthened in - * the corresponding type-specific class, but was weakened by the fact that - * this interface extends {@link Collection}. - * - * @return a type-specific iterator on the elements of this collection. - */ - BooleanIterator iterator(); - - /** - * Returns a type-specific iterator on this elements of this collection. - * - * @see #iterator() - * @deprecated As of fastutil 5, replaced by - * {@link #iterator()}. - */ - @Deprecated - BooleanIterator booleanIterator(); - - /** - * Returns an containing the items of this collection; the runtime type of - * the returned array is that of the specified array. - * - *

- * Warning: Note that, contrarily to - * {@link Collection#toArray(Object[])}, this methods just writes all - * elements of this collection: no special value will be added after the - * last one. - * - * @param a - * if this array is big enough, it will be used to store this - * collection. - * @return a primitive type array containing the items of this collection. - * @see Collection#toArray(Object[]) - */ - T[] toArray(T[] a); - - /** - * @see Collection#contains(Object) - */ - boolean contains(boolean key); - - /** - * Returns a primitive type array containing the items of this collection. - * - * @return a primitive type array containing the items of this collection. - * @see Collection#toArray() - */ - boolean[] toBooleanArray(); - - /** - * Returns a primitive type array containing the items of this collection. - * - *

- * Note that, contrarily to {@link Collection#toArray(Object[])}, this - * methods just writes all elements of this collection: no special value - * will be added after the last one. - * - * @param a - * if this array is big enough, it will be used to store this - * collection. - * @return a primitive type array containing the items of this collection. - * @see Collection#toArray(Object[]) - */ - boolean[] toBooleanArray(boolean a[]); - - /** - * Returns a primitive type array containing the items of this collection. - * - *

- * Note that, contrarily to {@link Collection#toArray(Object[])}, this - * methods just writes all elements of this collection: no special value - * will be added after the last one. - * - * @param a - * if this array is big enough, it will be used to store this - * collection. - * @return a primitive type array containing the items of this collection. - * @see Collection#toArray(Object[]) - */ - boolean[] toArray(boolean a[]); - - /** - * @see Collection#add(Object) - */ - boolean add(boolean key); - - /** - * Note that this method should be called - * {@link Collection#remove(Object) remove()}, but the clash with - * the similarly named index-based method in the {@link java.util.List} - * interface forces us to use a distinguished name. For simplicity, the set - * interfaces reinstates remove(). - * - * @see Collection#remove(Object) - */ - boolean rem(boolean key); - - /** - * @see Collection#addAll(Collection) - */ - boolean addAll(it.unimi.dsi.fastutil.booleans.BooleanCollection c); - - /** - * @see Collection#containsAll(Collection) - */ - boolean containsAll(it.unimi.dsi.fastutil.booleans.BooleanCollection c); - - /** - * @see Collection#removeAll(Collection) - */ - boolean removeAll(it.unimi.dsi.fastutil.booleans.BooleanCollection c); - - /** - * @see Collection#retainAll(Collection) - */ - boolean retainAll(it.unimi.dsi.fastutil.booleans.BooleanCollection c); - -} diff --git a/src/main/java/it/unimi/dsi/fastutil/booleans/BooleanCollections.java b/src/main/java/it/unimi/dsi/fastutil/booleans/BooleanCollections.java deleted file mode 100644 index bf75ff9..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/booleans/BooleanCollections.java +++ /dev/null @@ -1,505 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Primitive-type-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.booleans; - -import it.unimi.dsi.fastutil.booleans.AbstractBooleanCollection; -import it.unimi.dsi.fastutil.booleans.BooleanArrays; -import it.unimi.dsi.fastutil.booleans.BooleanBidirectionalIterator; -import it.unimi.dsi.fastutil.booleans.BooleanCollection; -import it.unimi.dsi.fastutil.booleans.BooleanIterable; -import it.unimi.dsi.fastutil.booleans.BooleanIterator; -import it.unimi.dsi.fastutil.booleans.BooleanIterators; -import it.unimi.dsi.fastutil.objects.ObjectArrays; - -import java.util.Collection; - -/** - * A class providing static methods and objects that do useful things with - * type-specific collections. - * - * @see java.util.Collections - */ - -public class BooleanCollections { - - private BooleanCollections() { - } - - /** - * An immutable class representing an empty type-specific collection. - * - *

- * This class may be useful to implement your own in case you subclass a - * type-specific collection. - */ - - public abstract static class EmptyCollection - extends - AbstractBooleanCollection { - - protected EmptyCollection() { - } - - public boolean add(boolean k) { - throw new UnsupportedOperationException(); - } - - public boolean contains(boolean k) { - return false; - } - - public Object[] toArray() { - return ObjectArrays.EMPTY_ARRAY; - } - - public boolean[] toBooleanArray(boolean[] a) { - return a; - } - public boolean[] toBooleanArray() { - return BooleanArrays.EMPTY_ARRAY; - } - - public boolean rem(boolean k) { - throw new UnsupportedOperationException(); - } - public boolean addAll(BooleanCollection c) { - throw new UnsupportedOperationException(); - } - public boolean removeAll(BooleanCollection c) { - throw new UnsupportedOperationException(); - } - public boolean retainAll(BooleanCollection c) { - throw new UnsupportedOperationException(); - } - public boolean containsAll(BooleanCollection c) { - return c.isEmpty(); - } - public BooleanBidirectionalIterator iterator() { - return BooleanIterators.EMPTY_ITERATOR; - } - - public int size() { - return 0; - } - public void clear() { - } - - public int hashCode() { - return 0; - } - public boolean equals(Object o) { - if (o == this) - return true; - if (!(o instanceof Collection)) - return false; - return ((Collection) o).isEmpty(); - } - } - - /** A synchronized wrapper class for collections. */ - - public static class SynchronizedCollection - implements - BooleanCollection, - java.io.Serializable { - - private static final long serialVersionUID = -7046029254386353129L; - - protected final BooleanCollection collection; - protected final Object sync; - - protected SynchronizedCollection(final BooleanCollection c, - final Object sync) { - if (c == null) - throw new NullPointerException(); - this.collection = c; - this.sync = sync; - } - - protected SynchronizedCollection(final BooleanCollection c) { - if (c == null) - throw new NullPointerException(); - this.collection = c; - this.sync = this; - } - - public int size() { - synchronized (sync) { - return collection.size(); - } - } - public boolean isEmpty() { - synchronized (sync) { - return collection.isEmpty(); - } - } - public boolean contains(final boolean o) { - synchronized (sync) { - return collection.contains(o); - } - } - - public boolean[] toBooleanArray() { - synchronized (sync) { - return collection.toBooleanArray(); - } - } - - public Object[] toArray() { - synchronized (sync) { - return collection.toArray(); - } - } - public boolean[] toBooleanArray(final boolean[] a) { - synchronized (sync) { - return collection.toBooleanArray(a); - } - } - public boolean[] toArray(final boolean[] a) { - synchronized (sync) { - return collection.toBooleanArray(a); - } - } - - public boolean addAll(final BooleanCollection c) { - synchronized (sync) { - return collection.addAll(c); - } - } - public boolean containsAll(final BooleanCollection c) { - synchronized (sync) { - return collection.containsAll(c); - } - } - public boolean removeAll(final BooleanCollection c) { - synchronized (sync) { - return collection.removeAll(c); - } - } - public boolean retainAll(final BooleanCollection c) { - synchronized (sync) { - return collection.retainAll(c); - } - } - - public boolean add(final Boolean k) { - synchronized (sync) { - return collection.add(k); - } - } - public boolean contains(final Object k) { - synchronized (sync) { - return collection.contains(k); - } - } - - public T[] toArray(final T[] a) { - synchronized (sync) { - return collection.toArray(a); - } - } - - public BooleanIterator iterator() { - return collection.iterator(); - } - - @Deprecated - public BooleanIterator booleanIterator() { - return iterator(); - } - - public boolean add(final boolean k) { - synchronized (sync) { - return collection.add(k); - } - } - public boolean rem(final boolean k) { - synchronized (sync) { - return collection.rem(k); - } - } - public boolean remove(final Object ok) { - synchronized (sync) { - return collection.remove(ok); - } - } - - public boolean addAll(final Collection c) { - synchronized (sync) { - return collection.addAll(c); - } - } - public boolean containsAll(final Collection c) { - synchronized (sync) { - return collection.containsAll(c); - } - } - public boolean removeAll(final Collection c) { - synchronized (sync) { - return collection.removeAll(c); - } - } - public boolean retainAll(final Collection c) { - synchronized (sync) { - return collection.retainAll(c); - } - } - - public void clear() { - synchronized (sync) { - collection.clear(); - } - } - public String toString() { - synchronized (sync) { - return collection.toString(); - } - } - } - - /** - * Returns a synchronized collection backed by the specified collection. - * - * @param c - * the collection to be wrapped in a synchronized collection. - * @return a synchronized view of the specified collection. - * @see java.util.Collections#synchronizedCollection(Collection) - */ - public static BooleanCollection synchronize(final BooleanCollection c) { - return new SynchronizedCollection(c); - } - - /** - * Returns a synchronized collection backed by the specified collection, - * using an assigned object to synchronize. - * - * @param c - * the collection to be wrapped in a synchronized collection. - * @param sync - * an object that will be used to synchronize the list access. - * @return a synchronized view of the specified collection. - * @see java.util.Collections#synchronizedCollection(Collection) - */ - - public static BooleanCollection synchronize(final BooleanCollection c, - final Object sync) { - return new SynchronizedCollection(c, sync); - } - - /** An unmodifiable wrapper class for collections. */ - - public static class UnmodifiableCollection - implements - BooleanCollection, - java.io.Serializable { - - private static final long serialVersionUID = -7046029254386353129L; - - protected final BooleanCollection collection; - - protected UnmodifiableCollection(final BooleanCollection c) { - if (c == null) - throw new NullPointerException(); - this.collection = c; - } - - public int size() { - return collection.size(); - } - public boolean isEmpty() { - return collection.isEmpty(); - } - public boolean contains(final boolean o) { - return collection.contains(o); - } - - public BooleanIterator iterator() { - return BooleanIterators.unmodifiable(collection.iterator()); - } - - @Deprecated - public BooleanIterator booleanIterator() { - return iterator(); - } - - public boolean add(final boolean k) { - throw new UnsupportedOperationException(); - } - public boolean remove(final Object ok) { - throw new UnsupportedOperationException(); - } - - public boolean addAll(final Collection c) { - throw new UnsupportedOperationException(); - } - public boolean containsAll(final Collection c) { - return collection.containsAll(c); - } - public boolean removeAll(final Collection c) { - throw new UnsupportedOperationException(); - } - public boolean retainAll(final Collection c) { - throw new UnsupportedOperationException(); - } - - public void clear() { - throw new UnsupportedOperationException(); - } - public String toString() { - return collection.toString(); - } - - public T[] toArray(final T[] a) { - return collection.toArray(a); - } - - public Object[] toArray() { - return collection.toArray(); - } - - public boolean[] toBooleanArray() { - return collection.toBooleanArray(); - } - public boolean[] toBooleanArray(final boolean[] a) { - return collection.toBooleanArray(a); - } - public boolean[] toArray(final boolean[] a) { - return collection.toArray(a); - } - public boolean rem(final boolean k) { - throw new UnsupportedOperationException(); - } - - public boolean addAll(final BooleanCollection c) { - throw new UnsupportedOperationException(); - } - public boolean containsAll(final BooleanCollection c) { - return collection.containsAll(c); - } - public boolean removeAll(final BooleanCollection c) { - throw new UnsupportedOperationException(); - } - public boolean retainAll(final BooleanCollection c) { - throw new UnsupportedOperationException(); - } - - public boolean add(final Boolean k) { - throw new UnsupportedOperationException(); - } - public boolean contains(final Object k) { - return collection.contains(k); - } - - } - - /** - * Returns an unmodifiable collection backed by the specified collection. - * - * @param c - * the collection to be wrapped in an unmodifiable collection. - * @return an unmodifiable view of the specified collection. - * @see java.util.Collections#unmodifiableCollection(Collection) - */ - public static BooleanCollection unmodifiable(final BooleanCollection c) { - return new UnmodifiableCollection(c); - } - - /** A collection wrapper class for iterables. */ - - public static class IterableCollection extends AbstractBooleanCollection - implements - java.io.Serializable { - - private static final long serialVersionUID = -7046029254386353129L; - - protected final BooleanIterable iterable; - - protected IterableCollection(final BooleanIterable iterable) { - if (iterable == null) - throw new NullPointerException(); - this.iterable = iterable; - } - - public int size() { - int c = 0; - final BooleanIterator iterator = iterator(); - while (iterator.hasNext()) { - iterator.next(); - c++; - } - - return c; - } - - public boolean isEmpty() { - return !iterable.iterator().hasNext(); - } - public BooleanIterator iterator() { - return iterable.iterator(); - } - - @Deprecated - public BooleanIterator booleanIterator() { - return iterator(); - } - } - - /** - * Returns an unmodifiable collection backed by the specified iterable. - * - * @param iterable - * the iterable object to be wrapped in an unmodifiable - * collection. - * @return an unmodifiable collection view of the specified iterable. - */ - public static BooleanCollection asCollection(final BooleanIterable iterable) { - if (iterable instanceof BooleanCollection) - return (BooleanCollection) iterable; - return new IterableCollection(iterable); - } - -} diff --git a/src/main/java/it/unimi/dsi/fastutil/booleans/BooleanComparator.java b/src/main/java/it/unimi/dsi/fastutil/booleans/BooleanComparator.java deleted file mode 100644 index 0266eab..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/booleans/BooleanComparator.java +++ /dev/null @@ -1,76 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Primitive-type-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.booleans; - -import java.util.Comparator; - -/** - * A type-specific {@link Comparator}; provides methods to compare two primitive - * types both as objects and as primitive types. - * - *

- * Note that fastutil provides a corresponding abstract class that - * can be used to implement this interface just by specifying the type-specific - * comparator. - * - * @see Comparator - */ - -public interface BooleanComparator - extends Comparator { - - /** - * Compares the given primitive types. - * - * @see Comparator - * @return A positive integer, zero, or a negative integer if the first - * argument is greater than, equal to, or smaller than, - * respectively, the second one. - */ - - public int compare(boolean k1, boolean k2); -} diff --git a/src/main/java/it/unimi/dsi/fastutil/booleans/BooleanIterable.java b/src/main/java/it/unimi/dsi/fastutil/booleans/BooleanIterable.java deleted file mode 100644 index b55ed01..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/booleans/BooleanIterable.java +++ /dev/null @@ -1,77 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Primitive-type-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.booleans; - -import it.unimi.dsi.fastutil.booleans.BooleanIterator; - -/** - * A type-specific {@link Iterable} that strengthens that specification of - * {@link Iterable#iterator()}. - * - *

- * Warning: Java will let you write “colon” - * for statements with primitive-type loop variables; however, what - * is (unfortunately) really happening is that at each iteration an unboxing - * (and, in the case of fastutil type-specific data structures, a - * boxing) will be performed. Watch out. - * - * @see Iterable - */ - -public interface BooleanIterable - extends Iterable { - - /** - * Returns a type-specific iterator. - * - * Note that this specification strengthens the one given in - * {@link Iterable#iterator()}. - * - * @return a type-specific iterator. - */ - BooleanIterator iterator(); -} diff --git a/src/main/java/it/unimi/dsi/fastutil/booleans/BooleanIterator.java b/src/main/java/it/unimi/dsi/fastutil/booleans/BooleanIterator.java deleted file mode 100644 index e2dd382..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/booleans/BooleanIterator.java +++ /dev/null @@ -1,85 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Primitive-type-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.booleans; - -import java.util.Iterator; - -/** - * A type-specific {@link Iterator}; provides an additional method to avoid - * (un)boxing, and the possibility to skip elements. - * - * @see Iterator - */ - -public interface BooleanIterator - extends Iterator { - - /** - * Returns the next element as a primitive type. - * - * @return the next element in the iteration. - * @see Iterator#next() - */ - - boolean nextBoolean(); - - /** - * Skips the given number of elements. - * - *

- * The effect of this call is exactly the same as that of calling - * {@link #next()} for n times (possibly stopping if - * {@link #hasNext()} becomes false). - * - * @param n - * the number of elements to skip. - * @return the number of elements actually skipped. - * @see Iterator#next() - */ - - int skip(int n); -} diff --git a/src/main/java/it/unimi/dsi/fastutil/booleans/BooleanIterators.java b/src/main/java/it/unimi/dsi/fastutil/booleans/BooleanIterators.java deleted file mode 100644 index bd946bc..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/booleans/BooleanIterators.java +++ /dev/null @@ -1,932 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Primitive-type-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.booleans; - -import it.unimi.dsi.fastutil.booleans.AbstractBooleanBidirectionalIterator; -import it.unimi.dsi.fastutil.booleans.AbstractBooleanIterator; -import it.unimi.dsi.fastutil.booleans.AbstractBooleanListIterator; -import it.unimi.dsi.fastutil.booleans.BooleanArrayList; -import it.unimi.dsi.fastutil.booleans.BooleanArrays; -import it.unimi.dsi.fastutil.booleans.BooleanBidirectionalIterator; -import it.unimi.dsi.fastutil.booleans.BooleanCollection; -import it.unimi.dsi.fastutil.booleans.BooleanIterator; -import it.unimi.dsi.fastutil.booleans.BooleanList; -import it.unimi.dsi.fastutil.booleans.BooleanListIterator; - -import java.util.Iterator; -import java.util.ListIterator; -import java.util.NoSuchElementException; - -/** - * A class providing static methods and objects that do useful things with - * type-specific iterators. - * - * @see Iterator - */ - -public class BooleanIterators { - - private BooleanIterators() { - } - - /** - * A class returning no elements and a type-specific iterator interface. - * - *

- * This class may be useful to implement your own in case you subclass a - * type-specific iterator. - */ - - public static class EmptyIterator extends AbstractBooleanListIterator - implements - java.io.Serializable, - Cloneable { - - private static final long serialVersionUID = -7046029254386353129L; - - protected EmptyIterator() { - } - - public boolean hasNext() { - return false; - } - public boolean hasPrevious() { - return false; - } - public boolean nextBoolean() { - throw new NoSuchElementException(); - } - public boolean previousBoolean() { - throw new NoSuchElementException(); - } - public int nextIndex() { - return 0; - } - public int previousIndex() { - return -1; - } - public int skip(int n) { - return 0; - }; - public int back(int n) { - return 0; - }; - public Object clone() { - return EMPTY_ITERATOR; - } - private Object readResolve() { - return EMPTY_ITERATOR; - } - } - - /** - * An empty iterator (immutable). It is serializable and cloneable. - * - *

- * The class of this objects represent an abstract empty iterator that can - * iterate as a type-specific (list) iterator. - */ - - public final static EmptyIterator EMPTY_ITERATOR = new EmptyIterator(); - - /** An iterator returning a single element. */ - - private static class SingletonIterator extends AbstractBooleanListIterator { - private final boolean element; - private int curr; - - public SingletonIterator(final boolean element) { - this.element = element; - } - - public boolean hasNext() { - return curr == 0; - } - public boolean hasPrevious() { - return curr == 1; - } - - public boolean nextBoolean() { - if (!hasNext()) - throw new NoSuchElementException(); - curr = 1; - return element; - } - - public boolean previousBoolean() { - if (!hasPrevious()) - throw new NoSuchElementException(); - curr = 0; - return element; - } - - public int nextIndex() { - return curr; - } - - public int previousIndex() { - return curr - 1; - } - } - - /** - * Returns an iterator that iterates just over the given element. - * - * @param element - * the only element to be returned by a type-specific list - * iterator. - * @return an iterator that iterates just over element. - */ - public static BooleanListIterator singleton(final boolean element) { - return new SingletonIterator(element); - } - - /** A class to wrap arrays in iterators. */ - - private static class ArrayIterator extends AbstractBooleanListIterator { - private final boolean[] array; - private final int offset, length; - private int curr; - - public ArrayIterator(final boolean[] array, final int offset, - final int length) { - this.array = array; - this.offset = offset; - this.length = length; - } - - public boolean hasNext() { - return curr < length; - } - public boolean hasPrevious() { - return curr > 0; - } - - public boolean nextBoolean() { - if (!hasNext()) - throw new NoSuchElementException(); - return array[offset + curr++]; - } - - public boolean previousBoolean() { - if (!hasPrevious()) - throw new NoSuchElementException(); - return array[offset + --curr]; - } - - public int skip(int n) { - if (n <= length - curr) { - curr += n; - return n; - } - n = length - curr; - curr = length; - return n; - } - - public int back(int n) { - if (n <= curr) { - curr -= n; - return n; - } - n = curr; - curr = 0; - return n; - } - - public int nextIndex() { - return curr; - } - - public int previousIndex() { - return curr - 1; - } - } - - /** - * Wraps the given part of an array into a type-specific list iterator. - * - *

- * The type-specific list iterator returned by this method will iterate - * length times, returning consecutive elements of the given - * array starting from the one with index offset. - * - * @param array - * an array to wrap into a type-specific list iterator. - * @param offset - * the first element of the array to be returned. - * @param length - * the number of elements to return. - * @return an iterator that will return length elements of - * array starting at position offset. - */ - public static BooleanListIterator wrap(final boolean[] array, - final int offset, final int length) { - BooleanArrays.ensureOffsetLength(array, offset, length); - return new ArrayIterator(array, offset, length); - } - - /** - * Wraps the given array into a type-specific list iterator. - * - *

- * The type-specific list iterator returned by this method will return all - * elements of the given array. - * - * @param array - * an array to wrap into a type-specific list iterator. - * @return an iterator that will the elements of array. - */ - public static BooleanListIterator wrap(final boolean[] array) { - return new ArrayIterator(array, 0, array.length); - } - - /** - * Unwraps an iterator into an array starting at a given offset for a given - * number of elements. - * - *

- * This method iterates over the given type-specific iterator and stores the - * elements returned, up to a maximum of length, in the given - * array starting at offset. The number of actually unwrapped - * elements is returned (it may be less than max if the - * iterator emits less than max elements). - * - * @param i - * a type-specific iterator. - * @param array - * an array to contain the output of the iterator. - * @param offset - * the first element of the array to be returned. - * @param max - * the maximum number of elements to unwrap. - * @return the number of elements unwrapped. - */ - public static int unwrap(final BooleanIterator i, final boolean array[], - int offset, final int max) { - if (max < 0) - throw new IllegalArgumentException( - "The maximum number of elements (" + max + ") is negative"); - if (offset < 0 || offset + max > array.length) - throw new IllegalArgumentException(); - int j = max; - while (j-- != 0 && i.hasNext()) - array[offset++] = i.nextBoolean(); - return max - j - 1; - } - - /** - * Unwraps an iterator into an array. - * - *

- * This method iterates over the given type-specific iterator and stores the - * elements returned in the given array. The iteration will stop when the - * iterator has no more elements or when the end of the array has been - * reached. - * - * @param i - * a type-specific iterator. - * @param array - * an array to contain the output of the iterator. - * @return the number of elements unwrapped. - */ - public static int unwrap(final BooleanIterator i, final boolean array[]) { - return unwrap(i, array, 0, array.length); - } - - /** - * Unwraps an iterator, returning an array, with a limit on the number of - * elements. - * - *

- * This method iterates over the given type-specific iterator and returns an - * array containing the elements returned by the iterator. At most - * max elements will be returned. - * - * @param i - * a type-specific iterator. - * @param max - * the maximum number of elements to be unwrapped. - * @return an array containing the elements returned by the iterator (at - * most max). - */ - - public static boolean[] unwrap(final BooleanIterator i, int max) { - if (max < 0) - throw new IllegalArgumentException( - "The maximum number of elements (" + max + ") is negative"); - boolean array[] = new boolean[16]; - int j = 0; - - while (max-- != 0 && i.hasNext()) { - if (j == array.length) - array = BooleanArrays.grow(array, j + 1); - array[j++] = i.nextBoolean(); - } - - return BooleanArrays.trim(array, j); - } - - /** - * Unwraps an iterator, returning an array. - * - *

- * This method iterates over the given type-specific iterator and returns an - * array containing the elements returned by the iterator. - * - * @param i - * a type-specific iterator. - * @return an array containing the elements returned by the iterator. - */ - - public static boolean[] unwrap(final BooleanIterator i) { - return unwrap(i, Integer.MAX_VALUE); - } - - /** - * Unwraps an iterator into a type-specific collection, with a limit on the - * number of elements. - * - *

- * This method iterates over the given type-specific iterator and stores the - * elements returned, up to a maximum of max, in the given - * type-specific collection. The number of actually unwrapped elements is - * returned (it may be less than max if the iterator emits less - * than max elements). - * - * @param i - * a type-specific iterator. - * @param c - * a type-specific collection array to contain the output of the - * iterator. - * @param max - * the maximum number of elements to unwrap. - * @return the number of elements unwrapped. Note that this is the number of - * elements returned by the iterator, which is not necessarily the - * number of elements that have been added to the collection - * (because of duplicates). - */ - public static int unwrap(final BooleanIterator i, - final BooleanCollection c, final int max) { - if (max < 0) - throw new IllegalArgumentException( - "The maximum number of elements (" + max + ") is negative"); - int j = max; - while (j-- != 0 && i.hasNext()) - c.add(i.nextBoolean()); - return max - j - 1; - } - - /** - * Unwraps an iterator into a type-specific collection. - * - *

- * This method iterates over the given type-specific iterator and stores the - * elements returned in the given type-specific collection. The returned - * count on the number unwrapped elements is a long, so that it will work - * also with very large collections. - * - * @param i - * a type-specific iterator. - * @param c - * a type-specific collection to contain the output of the - * iterator. - * @return the number of elements unwrapped. Note that this is the number of - * elements returned by the iterator, which is not necessarily the - * number of elements that have been added to the collection - * (because of duplicates). - */ - public static long unwrap(final BooleanIterator i, final BooleanCollection c) { - long n = 0; - while (i.hasNext()) { - c.add(i.nextBoolean()); - n++; - } - return n; - } - - /** - * Pours an iterator into a type-specific collection, with a limit on the - * number of elements. - * - *

- * This method iterates over the given type-specific iterator and adds the - * returned elements to the given collection (up to max). - * - * @param i - * a type-specific iterator. - * @param s - * a type-specific collection. - * @param max - * the maximum number of elements to be poured. - * @return the number of elements poured. Note that this is the number of - * elements returned by the iterator, which is not necessarily the - * number of elements that have been added to the collection - * (because of duplicates). - */ - - public static int pour(final BooleanIterator i, final BooleanCollection s, - final int max) { - if (max < 0) - throw new IllegalArgumentException( - "The maximum number of elements (" + max + ") is negative"); - int j = max; - while (j-- != 0 && i.hasNext()) - s.add(i.nextBoolean()); - return max - j - 1; - } - - /** - * Pours an iterator into a type-specific collection. - * - *

- * This method iterates over the given type-specific iterator and adds the - * returned elements to the given collection. - * - * @param i - * a type-specific iterator. - * @param s - * a type-specific collection. - * @return the number of elements poured. Note that this is the number of - * elements returned by the iterator, which is not necessarily the - * number of elements that have been added to the collection - * (because of duplicates). - */ - - public static int pour(final BooleanIterator i, final BooleanCollection s) { - return pour(i, s, Integer.MAX_VALUE); - } - - /** - * Pours an iterator, returning a type-specific list, with a limit on the - * number of elements. - * - *

- * This method iterates over the given type-specific iterator and returns a - * type-specific list containing the returned elements (up to - * max). Iteration on the returned list is guaranteed to - * produce the elements in the same order in which they appeared in the - * iterator. - * - * - * @param i - * a type-specific iterator. - * @param max - * the maximum number of elements to be poured. - * @return a type-specific list containing the returned elements, up to - * max. - */ - - public static BooleanList pour(final BooleanIterator i, int max) { - final BooleanArrayList l = new BooleanArrayList(); - pour(i, l, max); - l.trim(); - return l; - } - - /** - * Pours an iterator, returning a type-specific list. - * - *

- * This method iterates over the given type-specific iterator and returns a - * list containing the returned elements. Iteration on the returned list is - * guaranteed to produce the elements in the same order in which they - * appeared in the iterator. - * - * @param i - * a type-specific iterator. - * @return a type-specific list containing the returned elements. - */ - - public static BooleanList pour(final BooleanIterator i) { - return pour(i, Integer.MAX_VALUE); - } - - private static class IteratorWrapper extends AbstractBooleanIterator { - final Iterator i; - - public IteratorWrapper(final Iterator i) { - this.i = i; - } - - public boolean hasNext() { - return i.hasNext(); - } - public void remove() { - i.remove(); - } - - public boolean nextBoolean() { - return ((i.next()).booleanValue()); - } - } - - /** - * Wraps a standard iterator into a type-specific iterator. - * - *

- * This method wraps a standard iterator into a type-specific one which will - * handle the type conversions for you. Of course, any attempt to wrap an - * iterator returning the instances of the wrong class will generate a - * {@link ClassCastException}. The returned iterator is backed by - * i: changes to one of the iterators will affect the other, - * too. - * - *

- * If i is already type-specific, it will returned and no new - * object will be generated. - * - * @param i - * an iterator. - * @return a type-specific iterator backed by i. - */ - - @SuppressWarnings({"unchecked", "rawtypes"}) - public static BooleanIterator asBooleanIterator(final Iterator i) { - if (i instanceof BooleanIterator) - return (BooleanIterator) i; - return new IteratorWrapper(i); - } - - private static class ListIteratorWrapper - extends - AbstractBooleanListIterator { - final ListIterator i; - - public ListIteratorWrapper(final ListIterator i) { - this.i = i; - } - - public boolean hasNext() { - return i.hasNext(); - } - public boolean hasPrevious() { - return i.hasPrevious(); - } - public int nextIndex() { - return i.nextIndex(); - } - public int previousIndex() { - return i.previousIndex(); - } - public void set(boolean k) { - i.set((Boolean.valueOf(k))); - } - public void add(boolean k) { - i.add((Boolean.valueOf(k))); - } - public void remove() { - i.remove(); - } - - public boolean nextBoolean() { - return ((i.next()).booleanValue()); - } - public boolean previousBoolean() { - return ((i.previous()).booleanValue()); - } - } - - /** - * Wraps a standard list iterator into a type-specific list iterator. - * - *

- * This method wraps a standard list iterator into a type-specific one which - * will handle the type conversions for you. Of course, any attempt to wrap - * an iterator returning the instances of the wrong class will generate a - * {@link ClassCastException}. The returned iterator is backed by - * i: changes to one of the iterators will affect the other, - * too. - * - *

- * If i is already type-specific, it will returned and no new - * object will be generated. - * - * @param i - * a list iterator. - * @return a type-specific list iterator backed by i. - */ - - @SuppressWarnings({"unchecked", "rawtypes"}) - public static BooleanListIterator asBooleanIterator(final ListIterator i) { - if (i instanceof BooleanListIterator) - return (BooleanListIterator) i; - return new ListIteratorWrapper(i); - } - private static class IteratorConcatenator extends AbstractBooleanIterator { - final BooleanIterator a[]; - int offset, length, lastOffset = -1; - - public IteratorConcatenator(final BooleanIterator a[], int offset, - int length) { - this.a = a; - this.offset = offset; - this.length = length; - advance(); - } - - private void advance() { - while (length != 0) { - if (a[offset].hasNext()) - break; - length--; - offset++; - } - - return; - } - - public boolean hasNext() { - return length > 0; - } - - public boolean nextBoolean() { - if (!hasNext()) - throw new NoSuchElementException(); - boolean next = a[lastOffset = offset].nextBoolean(); - advance(); - return next; - } - - public void remove() { - if (lastOffset == -1) - throw new IllegalStateException(); - a[lastOffset].remove(); - } - - public int skip(int n) { - lastOffset = -1; - - int skipped = 0; - - while (skipped < n && length != 0) { - skipped += a[offset].skip(n - skipped); - if (a[offset].hasNext()) - break; - length--; - offset++; - } - - return skipped; - } - - } - - /** - * Concatenates all iterators contained in an array. - * - *

- * This method returns an iterator that will enumerate in order the elements - * returned by all iterators contained in the given array. - * - * @param a - * an array of iterators. - * @return an iterator obtained by concatenation. - */ - - public static BooleanIterator concat(final BooleanIterator a[]) { - return concat(a, 0, a.length); - } - - /** - * Concatenates a sequence of iterators contained in an array. - * - *

- * This method returns an iterator that will enumerate in order the elements - * returned by a[ offset ], then those returned by - * a[ offset + 1 ], and so on up to - * a[ offset + length - 1 ]. - * - * @param a - * an array of iterators. - * @param offset - * the index of the first iterator to concatenate. - * @param length - * the number of iterators to concatenate. - * @return an iterator obtained by concatenation of length - * elements of a starting at offset. - */ - - public static BooleanIterator concat(final BooleanIterator a[], - final int offset, final int length) { - return new IteratorConcatenator(a, offset, length); - } - - /** An unmodifiable wrapper class for iterators. */ - - public static class UnmodifiableIterator extends AbstractBooleanIterator { - final protected BooleanIterator i; - - public UnmodifiableIterator(final BooleanIterator i) { - this.i = i; - } - - public boolean hasNext() { - return i.hasNext(); - } - - public boolean nextBoolean() { - return i.nextBoolean(); - } - - /** - * {@inheritDoc} - * - * @deprecated Please use the corresponding type-specific method - * instead. - */ - @Deprecated - @Override - public Boolean next() { - return i.next(); - } - - } - - /** - * Returns an unmodifiable iterator backed by the specified iterator. - * - * @param i - * the iterator to be wrapped in an unmodifiable iterator. - * @return an unmodifiable view of the specified iterator. - */ - public static BooleanIterator unmodifiable(final BooleanIterator i) { - return new UnmodifiableIterator(i); - } - - /** An unmodifiable wrapper class for bidirectional iterators. */ - - public static class UnmodifiableBidirectionalIterator - extends - AbstractBooleanBidirectionalIterator { - final protected BooleanBidirectionalIterator i; - - public UnmodifiableBidirectionalIterator( - final BooleanBidirectionalIterator i) { - this.i = i; - } - - public boolean hasNext() { - return i.hasNext(); - } - public boolean hasPrevious() { - return i.hasPrevious(); - } - public boolean nextBoolean() { - return i.nextBoolean(); - } - public boolean previousBoolean() { - return i.previousBoolean(); - } - - /** - * {@inheritDoc} - * - * @deprecated Please use the corresponding type-specific method - * instead. - */ - @Deprecated - @Override - public Boolean next() { - return i.next(); - } - /** - * {@inheritDoc} - * - * @deprecated Please use the corresponding type-specific method - * instead. - */ - @Deprecated - @Override - public Boolean previous() { - return i.previous(); - } - - } - - /** - * Returns an unmodifiable bidirectional iterator backed by the specified - * bidirectional iterator. - * - * @param i - * the bidirectional iterator to be wrapped in an unmodifiable - * bidirectional iterator. - * @return an unmodifiable view of the specified bidirectional iterator. - */ - public static BooleanBidirectionalIterator unmodifiable( - final BooleanBidirectionalIterator i) { - return new UnmodifiableBidirectionalIterator(i); - } - - /** An unmodifiable wrapper class for list iterators. */ - - public static class UnmodifiableListIterator - extends - AbstractBooleanListIterator { - final protected BooleanListIterator i; - - public UnmodifiableListIterator(final BooleanListIterator i) { - this.i = i; - } - - public boolean hasNext() { - return i.hasNext(); - } - public boolean hasPrevious() { - return i.hasPrevious(); - } - public boolean nextBoolean() { - return i.nextBoolean(); - } - public boolean previousBoolean() { - return i.previousBoolean(); - } - public int nextIndex() { - return i.nextIndex(); - } - public int previousIndex() { - return i.previousIndex(); - } - - /** - * {@inheritDoc} - * - * @deprecated Please use the corresponding type-specific method - * instead. - */ - @Deprecated - @Override - public Boolean next() { - return i.next(); - } - /** - * {@inheritDoc} - * - * @deprecated Please use the corresponding type-specific method - * instead. - */ - @Deprecated - @Override - public Boolean previous() { - return i.previous(); - } - - } - - /** - * Returns an unmodifiable list iterator backed by the specified list - * iterator. - * - * @param i - * the list iterator to be wrapped in an unmodifiable list - * iterator. - * @return an unmodifiable view of the specified list iterator. - */ - public static BooleanListIterator unmodifiable(final BooleanListIterator i) { - return new UnmodifiableListIterator(i); - } -} diff --git a/src/main/java/it/unimi/dsi/fastutil/booleans/BooleanList.java b/src/main/java/it/unimi/dsi/fastutil/booleans/BooleanList.java deleted file mode 100644 index 335b74f..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/booleans/BooleanList.java +++ /dev/null @@ -1,269 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Primitive-type-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.booleans; - -import it.unimi.dsi.fastutil.booleans.BooleanCollection; -import it.unimi.dsi.fastutil.booleans.BooleanListIterator; - -import java.util.List; - -/** - * A type-specific {@link List}; provides some additional methods that use - * polymorphism to avoid (un)boxing. - * - *

- * Note that this type-specific interface extends {@link Comparable}: it is - * expected that implementing classes perform a lexicographical comparison using - * the standard operator "less then" for primitive types, and the usual - * {@link Comparable#compareTo(Object) compareTo()} method for objects. - * - *

- * Additionally, this interface strengthens {@link #listIterator()}, - * {@link #listIterator(int)} and {@link #subList(int,int)}. - * - *

- * Besides polymorphic methods, this interfaces specifies methods to copy into - * an array or remove contiguous sublists. Although the abstract implementation - * of this interface provides simple, one-by-one implementations of these - * methods, it is expected that concrete implementation override them with - * optimized versions. - * - * @see List - */ - -public interface BooleanList - extends - List, - Comparable>, - BooleanCollection { - /** - * Returns a type-specific iterator on the elements of this list (in proper - * sequence). - * - * Note that this specification strengthens the one given in - * {@link List#iterator()}. It would not be normally necessary, but - * {@link Iterable#iterator()} is bizarrily re-specified in - * {@link List}. - * - * @return an iterator on the elements of this list (in proper sequence). - */ - BooleanListIterator iterator(); - - /** - * Returns a type-specific list iterator on the list. - * - * @see #listIterator() - * @deprecated As of fastutil 5, replaced by - * {@link #listIterator()}. - */ - @Deprecated - BooleanListIterator booleanListIterator(); - - /** - * Returns a type-specific list iterator on the list starting at a given - * index. - * - * @see #listIterator(int) - * @deprecated As of fastutil 5, replaced by - * {@link #listIterator(int)}. - */ - @Deprecated - BooleanListIterator booleanListIterator(int index); - - /** - * Returns a type-specific list iterator on the list. - * - * @see List#listIterator() - */ - BooleanListIterator listIterator(); - - /** - * Returns a type-specific list iterator on the list starting at a given - * index. - * - * @see List#listIterator(int) - */ - BooleanListIterator listIterator(int index); - - /** - * Returns a type-specific view of the portion of this list from the index - * from, inclusive, to the index to, exclusive. - * - * @see List#subList(int,int) - * @deprecated As of fastutil 5, replaced by - * {@link #subList(int,int)}. - */ - @Deprecated - it.unimi.dsi.fastutil.booleans.BooleanList booleanSubList(int from, int to); - - /** - * Returns a type-specific view of the portion of this list from the index - * from, inclusive, to the index to, exclusive. - * - *

- * Note that this specification strengthens the one given in - * {@link List#subList(int,int)}. - * - * @see List#subList(int,int) - */ - it.unimi.dsi.fastutil.booleans.BooleanList subList(int from, int to); - - /** - * Sets the size of this list. - * - *

- * If the specified size is smaller than the current size, the last elements - * are discarded. Otherwise, they are filled with 0/null/ - * false. - * - * @param size - * the new size. - */ - - void size(int size); - - /** - * Copies (hopefully quickly) elements of this type-specific list into the - * given array. - * - * @param from - * the start index (inclusive). - * @param a - * the destination array. - * @param offset - * the offset into the destination array where to store the first - * element copied. - * @param length - * the number of elements to be copied. - */ - void getElements(int from, boolean a[], int offset, int length); - - /** - * Removes (hopefully quickly) elements of this type-specific list. - * - * @param from - * the start index (inclusive). - * @param to - * the end index (exclusive). - */ - void removeElements(int from, int to); - - /** - * Add (hopefully quickly) elements to this type-specific list. - * - * @param index - * the index at which to add elements. - * @param a - * the array containing the elements. - */ - void addElements(int index, boolean a[]); - - /** - * Add (hopefully quickly) elements to this type-specific list. - * - * @param index - * the index at which to add elements. - * @param a - * the array containing the elements. - * @param offset - * the offset of the first element to add. - * @param length - * the number of elements to add. - */ - void addElements(int index, boolean a[], int offset, int length); - - /** - * @see List#add(Object) - */ - boolean add(boolean key); - - /** - * @see List#add(int,Object) - */ - void add(int index, boolean key); - - /** - * @see List#add(int,Object) - */ - boolean addAll(int index, BooleanCollection c); - - /** - * @see List#add(int,Object) - */ - boolean addAll(int index, it.unimi.dsi.fastutil.booleans.BooleanList c); - - /** - * @see List#add(int,Object) - */ - boolean addAll(it.unimi.dsi.fastutil.booleans.BooleanList c); - - /** - * @see List#get(int) - */ - boolean getBoolean(int index); - - /** - * @see List#indexOf(Object) - */ - int indexOf(boolean k); - - /** - * @see List#lastIndexOf(Object) - */ - int lastIndexOf(boolean k); - - /** - * @see List#remove(int) - */ - boolean removeBoolean(int index); - - /** - * @see List#set(int,Object) - */ - boolean set(int index, boolean k); - -} diff --git a/src/main/java/it/unimi/dsi/fastutil/booleans/BooleanListIterator.java b/src/main/java/it/unimi/dsi/fastutil/booleans/BooleanListIterator.java deleted file mode 100644 index df94804..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/booleans/BooleanListIterator.java +++ /dev/null @@ -1,75 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Primitive-type-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.booleans; - -import it.unimi.dsi.fastutil.booleans.BooleanBidirectionalIterator; - -import java.util.ListIterator; - -/** - * A type-specific bidirectional iterator that is also a {@link ListIterator}. - * - *

- * This interface merges the methods provided by a {@link ListIterator} and a - * type-specific {@link it.unimi.dsi.fastutil.BidirectionalIterator}. Moreover, - * it provides type-specific versions of - * {@link ListIterator#add(Object) add()} and - * {@link ListIterator#set(Object) set()}. - * - * @see ListIterator - * @see it.unimi.dsi.fastutil.BidirectionalIterator - */ - -public interface BooleanListIterator - extends - ListIterator, - BooleanBidirectionalIterator { - - void set(boolean k); - void add(boolean k); - -} diff --git a/src/main/java/it/unimi/dsi/fastutil/booleans/BooleanSet.java b/src/main/java/it/unimi/dsi/fastutil/booleans/BooleanSet.java deleted file mode 100644 index fbfc5a7..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/booleans/BooleanSet.java +++ /dev/null @@ -1,92 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Primitive-type-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.booleans; - -import it.unimi.dsi.fastutil.booleans.BooleanCollection; -import it.unimi.dsi.fastutil.booleans.BooleanIterator; - -import java.util.Set; - -/** - * A type-specific {@link Set}; provides some additional methods that use - * polymorphism to avoid (un)boxing. - * - *

- * Additionally, this interface strengthens (again) {@link #iterator()}. - * - * @see Set - */ - -public interface BooleanSet - extends BooleanCollection, Set { - - /** - * Returns a type-specific iterator on the elements of this set. - * - *

- * Note that this specification strengthens the one given in - * {@link Iterable#iterator()}, which was already strengthened in - * the corresponding type-specific class, but was weakened by the fact that - * this interface extends {@link Set}. - * - * @return a type-specific iterator on the elements of this set. - */ - BooleanIterator iterator(); - - /** - * Removes an element from this set. - * - *

- * Note that the corresponding method of the type-specific collection is - * rem(). This unfortunate situation is caused by the clash - * with the similarly named index-based method in the {@link java.util.List} - * interface. - * - * @see java.util.Collection#remove(Object) - */ - public boolean remove(boolean k); -} diff --git a/src/main/java/it/unimi/dsi/fastutil/booleans/BooleanStack.java b/src/main/java/it/unimi/dsi/fastutil/booleans/BooleanStack.java deleted file mode 100644 index 45743a6..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/booleans/BooleanStack.java +++ /dev/null @@ -1,82 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Primitive-type-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.booleans; - -import it.unimi.dsi.fastutil.Stack; - -/** - * A type-specific {@link Stack}; provides some additional methods that use - * polymorphism to avoid (un)boxing. - */ - -public interface BooleanStack - extends Stack { - - /** - * @see Stack#push(Object) - */ - - void push(boolean k); - - /** - * @see Stack#pop() - */ - boolean popBoolean(); - - /** - * @see Stack#top() - */ - - boolean topBoolean(); - - /** - * @see Stack#peek(int) - */ - - boolean peekBoolean(int i); - -} diff --git a/src/main/java/it/unimi/dsi/fastutil/bytes/ByteIterator.java b/src/main/java/it/unimi/dsi/fastutil/bytes/ByteIterator.java deleted file mode 100644 index 8db699a..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/bytes/ByteIterator.java +++ /dev/null @@ -1,85 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Primitive-type-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.bytes; - -import java.util.Iterator; - -/** - * A type-specific {@link Iterator}; provides an additional method to avoid - * (un)boxing, and the possibility to skip elements. - * - * @see Iterator - */ - -public interface ByteIterator - extends Iterator { - - /** - * Returns the next element as a primitive type. - * - * @return the next element in the iteration. - * @see Iterator#next() - */ - - byte nextByte(); - - /** - * Skips the given number of elements. - * - *

- * The effect of this call is exactly the same as that of calling - * {@link #next()} for n times (possibly stopping if - * {@link #hasNext()} becomes false). - * - * @param n - * the number of elements to skip. - * @return the number of elements actually skipped. - * @see Iterator#next() - */ - - int skip(int n); -} diff --git a/src/main/java/it/unimi/dsi/fastutil/ints/AbstractInt2BooleanFunction.java b/src/main/java/it/unimi/dsi/fastutil/ints/AbstractInt2BooleanFunction.java deleted file mode 100644 index de0d944..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/ints/AbstractInt2BooleanFunction.java +++ /dev/null @@ -1,183 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Primitive-type-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* Primitive-type-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.ints; - -import it.unimi.dsi.fastutil.ints.Int2BooleanFunction; - -/** - * An abstract class providing basic methods for functions implementing a - * type-specific interface. - * - *

- * Optional operations just throw an {@link UnsupportedOperationException}. - * Generic versions of accessors delegate to the corresponding type-specific - * counterparts following the interface rules (they take care of returning - * null on a missing key). - * - *

- * This class handles directly a default return value (including - * {@linkplain #defaultReturnValue() methods to access it}). Instances of classes - * inheriting from this class have just to return defRetValue to - * denote lack of a key in type-specific methods. The value is serialized. - * - *

- * Implementing subclasses have just to provide type-specific get() - * , type-specific containsKey(), and size() methods. - * - */ - -public abstract class AbstractInt2BooleanFunction - implements - Int2BooleanFunction, - java.io.Serializable { - - private static final long serialVersionUID = -4940583368468432370L; - - protected AbstractInt2BooleanFunction() { - } - - /** - * The default return value for get(), put() and - * remove(). - */ - - protected boolean defRetValue; - - public void defaultReturnValue(final boolean rv) { - defRetValue = rv; - } - - public boolean defaultReturnValue() { - return defRetValue; - } - - public boolean put(int key, boolean value) { - throw new UnsupportedOperationException(); - } - - public boolean remove(int key) { - throw new UnsupportedOperationException(); - } - - public void clear() { - throw new UnsupportedOperationException(); - } - - public boolean containsKey(final Object ok) { - if (ok == null) - return false; - return containsKey(((((Integer) (ok)).intValue()))); - } - - /** - * Delegates to the corresponding type-specific method, taking care of - * returning null on a missing key. - * - *

- * This method must check whether the provided key is in the map using - * containsKey(). Thus, it probes the map twice. - * Implementors of subclasses should override it with a more efficient - * method. - * - * @deprecated Please use the corresponding type-specific method instead. - */ - @Deprecated - public Boolean get(final Object ok) { - - if (ok == null) - return null; - - final int k = ((((Integer) (ok)).intValue())); - return containsKey(k) ? (Boolean.valueOf(get(k))) : null; - } - - /** - * Delegates to the corresponding type-specific method, taking care of - * returning null on a missing key. - * - *

- * This method must check whether the provided key is in the map using - * containsKey(). Thus, it probes the map twice. - * Implementors of subclasses should override it with a more efficient - * method. - * - * @deprecated Please use the corresponding type-specific method instead. - */ - @Deprecated - public Boolean put(final Integer ok, final Boolean ov) { - final int k = ((ok).intValue()); - final boolean containsKey = containsKey(k); - final boolean v = put(k, ((ov).booleanValue())); - return containsKey ? (Boolean.valueOf(v)) : null; - } - - /** - * Delegates to the corresponding type-specific method, taking care of - * returning null on a missing key. - * - *

- * This method must check whether the provided key is in the map using - * containsKey(). Thus, it probes the map twice. - * Implementors of subclasses should override it with a more efficient - * method. - * - * @deprecated Please use the corresponding type-specific method instead. - */ - @Deprecated - public Boolean remove(final Object ok) { - - if (ok == null) - return null; - - final int k = ((((Integer) (ok)).intValue())); - final boolean containsKey = containsKey(k); - final boolean v = remove(k); - return containsKey ? (Boolean.valueOf(v)) : null; - } - -} diff --git a/src/main/java/it/unimi/dsi/fastutil/ints/AbstractInt2BooleanMap.java b/src/main/java/it/unimi/dsi/fastutil/ints/AbstractInt2BooleanMap.java deleted file mode 100644 index ae3b8ee..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/ints/AbstractInt2BooleanMap.java +++ /dev/null @@ -1,406 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Primitive-type-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* Primitive-type-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.ints; - -import it.unimi.dsi.fastutil.booleans.AbstractBooleanCollection; -import it.unimi.dsi.fastutil.booleans.AbstractBooleanIterator; -import it.unimi.dsi.fastutil.booleans.BooleanCollection; -import it.unimi.dsi.fastutil.booleans.BooleanIterator; -import it.unimi.dsi.fastutil.ints.AbstractInt2BooleanFunction; -import it.unimi.dsi.fastutil.ints.AbstractIntIterator; -import it.unimi.dsi.fastutil.ints.AbstractIntSet; -import it.unimi.dsi.fastutil.ints.Int2BooleanMap; -import it.unimi.dsi.fastutil.ints.IntIterator; -import it.unimi.dsi.fastutil.ints.IntSet; -import it.unimi.dsi.fastutil.objects.ObjectIterator; -import it.unimi.dsi.fastutil.objects.ObjectSet; - -import java.util.Iterator; -import java.util.Map; - -/** - * An abstract class providing basic methods for maps implementing a - * type-specific interface. - * - *

- * Optional operations just throw an {@link UnsupportedOperationException}. - * Generic versions of accessors delegate to the corresponding type-specific - * counterparts following the interface rules (they take care of returning - * null on a missing key). - * - *

- * As a further help, this class provides a {@link BasicEntry BasicEntry} inner - * class that implements a type-specific version of {@link Map.Entry}; - * it is particularly useful for those classes that do not implement their own - * entries (e.g., most immutable maps). - */ - -public abstract class AbstractInt2BooleanMap - extends - AbstractInt2BooleanFunction - implements - Int2BooleanMap, - java.io.Serializable { - - private static final long serialVersionUID = -4940583368468432370L; - - protected AbstractInt2BooleanMap() { - } - - public boolean containsValue(Object ov) { - if (ov == null) - return false; - return containsValue(((((Boolean) (ov)).booleanValue()))); - } - - /** Checks whether the given value is contained in {@link #values()}. */ - public boolean containsValue(boolean v) { - return values().contains(v); - } - - /** Checks whether the given value is contained in {@link #keySet()}. */ - public boolean containsKey(int k) { - return keySet().contains(k); - } - - /** - * Puts all pairs in the given map. If the map implements the interface of - * this map, it uses the faster iterators. - * - * @param m - * a map. - */ - - @SuppressWarnings("deprecation") - public void putAll(Map m) { - int n = m.size(); - final Iterator> i = m - .entrySet().iterator(); - - if (m instanceof Int2BooleanMap) { - Int2BooleanMap.Entry e; - while (n-- != 0) { - e = (Int2BooleanMap.Entry) i.next(); - put(e.getIntKey(), e.getBooleanValue()); - } - } else { - Map.Entry e; - while (n-- != 0) { - e = i.next(); - put(e.getKey(), e.getValue()); - } - } - } - - public boolean isEmpty() { - return size() == 0; - } - - /** - * This class provides a basic but complete type-specific entry class for - * all those maps implementations that do not have entries on their own - * (e.g., most immutable maps). - * - *

- * This class does not implement - * {@link Map.Entry#setValue(Object) setValue()}, as the - * modification would not be reflected in the base map. - */ - - public static class BasicEntry implements Int2BooleanMap.Entry { - protected int key; - protected boolean value; - - public BasicEntry(final Integer key, final Boolean value) { - this.key = ((key).intValue()); - this.value = ((value).booleanValue()); - } - - public BasicEntry(final int key, final boolean value) { - this.key = key; - this.value = value; - } - - /** - * {@inheritDoc} - * - * @deprecated Please use the corresponding type-specific method - * instead. - */ - @Deprecated - public Integer getKey() { - return (Integer.valueOf(key)); - } - - public int getIntKey() { - return key; - } - - /** - * {@inheritDoc} - * - * @deprecated Please use the corresponding type-specific method - * instead. - */ - @Deprecated - public Boolean getValue() { - return (Boolean.valueOf(value)); - } - - public boolean getBooleanValue() { - return value; - } - - public boolean setValue(final boolean value) { - throw new UnsupportedOperationException(); - } - - /** - * {@inheritDoc} - * - * @deprecated Please use the corresponding type-specific method - * instead. - */ - @Deprecated - public Boolean setValue(final Boolean value) { - return Boolean.valueOf(setValue(value.booleanValue())); - } - - public boolean equals(final Object o) { - if (!(o instanceof Map.Entry)) - return false; - final Map.Entry e = (Map.Entry) o; - - if (e.getKey() == null || !(e.getKey() instanceof Integer)) - return false; - - if (e.getValue() == null || !(e.getValue() instanceof Boolean)) - return false; - - return ((key) == (((((Integer) (e.getKey())).intValue())))) - && ((value) == (((((Boolean) (e.getValue())).booleanValue())))); - } - - public int hashCode() { - return (key) ^ (value ? 1231 : 1237); - } - - public String toString() { - return key + "->" + value; - } - } - - /** - * Returns a type-specific-set view of the keys of this map. - * - *

- * The view is backed by the set returned by {@link #entrySet()}. Note that - * no attempt is made at caching the result of this method, as this - * would require adding some attributes that lightweight implementations - * would not need. Subclasses may easily override this policy by calling - * this method and caching the result, but implementors are encouraged to - * write more efficient ad-hoc implementations. - * - * @return a set view of the keys of this map; it may be safely cast to a - * type-specific interface. - */ - - public IntSet keySet() { - return new AbstractIntSet() { - - public boolean contains(final int k) { - return containsKey(k); - } - - public int size() { - return it.unimi.dsi.fastutil.ints.AbstractInt2BooleanMap.this.size(); - } - public void clear() { - it.unimi.dsi.fastutil.ints.AbstractInt2BooleanMap.this.clear(); - } - - public IntIterator iterator() { - return new AbstractIntIterator() { - final ObjectIterator> i = entrySet() - .iterator(); - @Override - public int nextInt() { - return ((Int2BooleanMap.Entry) i.next()).getIntKey(); - }; - @Override - public boolean hasNext() { - return i.hasNext(); - } - @Override - public void remove() { - i.remove(); - } - }; - } - }; - } - - /** - * Returns a type-specific-set view of the values of this map. - * - *

- * The view is backed by the set returned by {@link #entrySet()}. Note that - * no attempt is made at caching the result of this method, as this - * would require adding some attributes that lightweight implementations - * would not need. Subclasses may easily override this policy by calling - * this method and caching the result, but implementors are encouraged to - * write more efficient ad-hoc implementations. - * - * @return a set view of the values of this map; it may be safely cast to a - * type-specific interface. - */ - - public BooleanCollection values() { - return new AbstractBooleanCollection() { - - public boolean contains(final boolean k) { - return containsValue(k); - } - - public int size() { - return it.unimi.dsi.fastutil.ints.AbstractInt2BooleanMap.this.size(); - } - public void clear() { - it.unimi.dsi.fastutil.ints.AbstractInt2BooleanMap.this.clear(); - } - - public BooleanIterator iterator() { - return new AbstractBooleanIterator() { - final ObjectIterator> i = entrySet() - .iterator(); - - /** - * {@inheritDoc} - * - * @deprecated Please use the corresponding type-specific - * method instead. - */ - @Deprecated - public boolean nextBoolean() { - return ((Int2BooleanMap.Entry) i.next()) - .getBooleanValue(); - }; - - public boolean hasNext() { - return i.hasNext(); - } - }; - } - }; - } - - @SuppressWarnings({"unchecked", "rawtypes"}) - public ObjectSet> entrySet() { - return (ObjectSet) int2BooleanEntrySet(); - } - - /** - * Returns a hash code for this map. - * - * The hash code of a map is computed by summing the hash codes of its - * entries. - * - * @return a hash code for this map. - */ - - public int hashCode() { - int h = 0, n = size(); - final ObjectIterator> i = entrySet() - .iterator(); - - while (n-- != 0) - h += i.next().hashCode(); - return h; - } - - public boolean equals(Object o) { - if (o == this) - return true; - if (!(o instanceof Map)) - return false; - - Map m = (Map) o; - if (m.size() != size()) - return false; - return entrySet().containsAll(m.entrySet()); - } - - public String toString() { - final StringBuilder s = new StringBuilder(); - final ObjectIterator> i = entrySet() - .iterator(); - int n = size(); - Int2BooleanMap.Entry e; - boolean first = true; - - s.append("{"); - - while (n-- != 0) { - if (first) - first = false; - else - s.append(", "); - - e = (Int2BooleanMap.Entry) i.next(); - - s.append(String.valueOf(e.getIntKey())); - s.append("=>"); - - s.append(String.valueOf(e.getBooleanValue())); - } - - s.append("}"); - return s.toString(); - } - -} diff --git a/src/main/java/it/unimi/dsi/fastutil/ints/AbstractInt2IntFunction.java b/src/main/java/it/unimi/dsi/fastutil/ints/AbstractInt2IntFunction.java deleted file mode 100644 index a53bf99..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/ints/AbstractInt2IntFunction.java +++ /dev/null @@ -1,183 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Primitive-type-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* Primitive-type-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.ints; - -import it.unimi.dsi.fastutil.ints.Int2IntFunction; - -/** - * An abstract class providing basic methods for functions implementing a - * type-specific interface. - * - *

- * Optional operations just throw an {@link UnsupportedOperationException}. - * Generic versions of accessors delegate to the corresponding type-specific - * counterparts following the interface rules (they take care of returning - * null on a missing key). - * - *

- * This class handles directly a default return value (including - * {@linkplain #defaultReturnValue() methods to access it}). Instances of classes - * inheriting from this class have just to return defRetValue to - * denote lack of a key in type-specific methods. The value is serialized. - * - *

- * Implementing subclasses have just to provide type-specific get() - * , type-specific containsKey(), and size() methods. - * - */ - -public abstract class AbstractInt2IntFunction - implements - Int2IntFunction, - java.io.Serializable { - - private static final long serialVersionUID = -4940583368468432370L; - - protected AbstractInt2IntFunction() { - } - - /** - * The default return value for get(), put() and - * remove(). - */ - - protected int defRetValue; - - public void defaultReturnValue(final int rv) { - defRetValue = rv; - } - - public int defaultReturnValue() { - return defRetValue; - } - - public int put(int key, int value) { - throw new UnsupportedOperationException(); - } - - public int remove(int key) { - throw new UnsupportedOperationException(); - } - - public void clear() { - throw new UnsupportedOperationException(); - } - - public boolean containsKey(final Object ok) { - if (ok == null) - return false; - return containsKey(((((Integer) (ok)).intValue()))); - } - - /** - * Delegates to the corresponding type-specific method, taking care of - * returning null on a missing key. - * - *

- * This method must check whether the provided key is in the map using - * containsKey(). Thus, it probes the map twice. - * Implementors of subclasses should override it with a more efficient - * method. - * - * @deprecated Please use the corresponding type-specific method instead. - */ - @Deprecated - public Integer get(final Object ok) { - - if (ok == null) - return null; - - final int k = ((((Integer) (ok)).intValue())); - return containsKey(k) ? (Integer.valueOf(get(k))) : null; - } - - /** - * Delegates to the corresponding type-specific method, taking care of - * returning null on a missing key. - * - *

- * This method must check whether the provided key is in the map using - * containsKey(). Thus, it probes the map twice. - * Implementors of subclasses should override it with a more efficient - * method. - * - * @deprecated Please use the corresponding type-specific method instead. - */ - @Deprecated - public Integer put(final Integer ok, final Integer ov) { - final int k = ((ok).intValue()); - final boolean containsKey = containsKey(k); - final int v = put(k, ((ov).intValue())); - return containsKey ? (Integer.valueOf(v)) : null; - } - - /** - * Delegates to the corresponding type-specific method, taking care of - * returning null on a missing key. - * - *

- * This method must check whether the provided key is in the map using - * containsKey(). Thus, it probes the map twice. - * Implementors of subclasses should override it with a more efficient - * method. - * - * @deprecated Please use the corresponding type-specific method instead. - */ - @Deprecated - public Integer remove(final Object ok) { - - if (ok == null) - return null; - - final int k = ((((Integer) (ok)).intValue())); - final boolean containsKey = containsKey(k); - final int v = remove(k); - return containsKey ? (Integer.valueOf(v)) : null; - } - -} diff --git a/src/main/java/it/unimi/dsi/fastutil/ints/AbstractInt2IntMap.java b/src/main/java/it/unimi/dsi/fastutil/ints/AbstractInt2IntMap.java deleted file mode 100644 index 9df5982..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/ints/AbstractInt2IntMap.java +++ /dev/null @@ -1,401 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Primitive-type-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* Primitive-type-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.ints; - -import it.unimi.dsi.fastutil.ints.AbstractInt2IntFunction; -import it.unimi.dsi.fastutil.ints.AbstractIntCollection; -import it.unimi.dsi.fastutil.ints.AbstractIntIterator; -import it.unimi.dsi.fastutil.ints.AbstractIntSet; -import it.unimi.dsi.fastutil.ints.Int2IntMap; -import it.unimi.dsi.fastutil.ints.IntCollection; -import it.unimi.dsi.fastutil.ints.IntIterator; -import it.unimi.dsi.fastutil.ints.IntSet; -import it.unimi.dsi.fastutil.objects.ObjectIterator; -import it.unimi.dsi.fastutil.objects.ObjectSet; - -import java.util.Iterator; -import java.util.Map; - -/** - * An abstract class providing basic methods for maps implementing a - * type-specific interface. - * - *

- * Optional operations just throw an {@link UnsupportedOperationException}. - * Generic versions of accessors delegate to the corresponding type-specific - * counterparts following the interface rules (they take care of returning - * null on a missing key). - * - *

- * As a further help, this class provides a {@link BasicEntry BasicEntry} inner - * class that implements a type-specific version of {@link Map.Entry}; - * it is particularly useful for those classes that do not implement their own - * entries (e.g., most immutable maps). - */ - -public abstract class AbstractInt2IntMap extends AbstractInt2IntFunction - implements - Int2IntMap, - java.io.Serializable { - - private static final long serialVersionUID = -4940583368468432370L; - - protected AbstractInt2IntMap() { - } - - public boolean containsValue(Object ov) { - if (ov == null) - return false; - return containsValue(((((Integer) (ov)).intValue()))); - } - - /** Checks whether the given value is contained in {@link #values()}. */ - public boolean containsValue(int v) { - return values().contains(v); - } - - /** Checks whether the given value is contained in {@link #keySet()}. */ - public boolean containsKey(int k) { - return keySet().contains(k); - } - - /** - * Puts all pairs in the given map. If the map implements the interface of - * this map, it uses the faster iterators. - * - * @param m - * a map. - */ - - @SuppressWarnings("deprecation") - public void putAll(Map m) { - int n = m.size(); - final Iterator> i = m - .entrySet().iterator(); - - if (m instanceof Int2IntMap) { - Int2IntMap.Entry e; - while (n-- != 0) { - e = (Int2IntMap.Entry) i.next(); - put(e.getIntKey(), e.getIntValue()); - } - } else { - Map.Entry e; - while (n-- != 0) { - e = i.next(); - put(e.getKey(), e.getValue()); - } - } - } - - public boolean isEmpty() { - return size() == 0; - } - - /** - * This class provides a basic but complete type-specific entry class for - * all those maps implementations that do not have entries on their own - * (e.g., most immutable maps). - * - *

- * This class does not implement - * {@link Map.Entry#setValue(Object) setValue()}, as the - * modification would not be reflected in the base map. - */ - - public static class BasicEntry implements Int2IntMap.Entry { - protected int key; - protected int value; - - public BasicEntry(final Integer key, final Integer value) { - this.key = ((key).intValue()); - this.value = ((value).intValue()); - } - - public BasicEntry(final int key, final int value) { - this.key = key; - this.value = value; - } - - /** - * {@inheritDoc} - * - * @deprecated Please use the corresponding type-specific method - * instead. - */ - @Deprecated - public Integer getKey() { - return (Integer.valueOf(key)); - } - - public int getIntKey() { - return key; - } - - /** - * {@inheritDoc} - * - * @deprecated Please use the corresponding type-specific method - * instead. - */ - @Deprecated - public Integer getValue() { - return (Integer.valueOf(value)); - } - - public int getIntValue() { - return value; - } - - public int setValue(final int value) { - throw new UnsupportedOperationException(); - } - - /** - * {@inheritDoc} - * - * @deprecated Please use the corresponding type-specific method - * instead. - */ - @Deprecated - public Integer setValue(final Integer value) { - return Integer.valueOf(setValue(value.intValue())); - } - - public boolean equals(final Object o) { - if (!(o instanceof Map.Entry)) - return false; - final Map.Entry e = (Map.Entry) o; - - if (e.getKey() == null || !(e.getKey() instanceof Integer)) - return false; - - if (e.getValue() == null || !(e.getValue() instanceof Integer)) - return false; - - return ((key) == (((((Integer) (e.getKey())).intValue())))) - && ((value) == (((((Integer) (e.getValue())).intValue())))); - } - - public int hashCode() { - return (key) ^ (value); - } - - public String toString() { - return key + "->" + value; - } - } - - /** - * Returns a type-specific-set view of the keys of this map. - * - *

- * The view is backed by the set returned by {@link #entrySet()}. Note that - * no attempt is made at caching the result of this method, as this - * would require adding some attributes that lightweight implementations - * would not need. Subclasses may easily override this policy by calling - * this method and caching the result, but implementors are encouraged to - * write more efficient ad-hoc implementations. - * - * @return a set view of the keys of this map; it may be safely cast to a - * type-specific interface. - */ - - public IntSet keySet() { - return new AbstractIntSet() { - - public boolean contains(final int k) { - return containsKey(k); - } - - public int size() { - return it.unimi.dsi.fastutil.ints.AbstractInt2IntMap.this.size(); - } - public void clear() { - it.unimi.dsi.fastutil.ints.AbstractInt2IntMap.this.clear(); - } - - public IntIterator iterator() { - return new AbstractIntIterator() { - final ObjectIterator> i = entrySet() - .iterator(); - @Override - public int nextInt() { - return ((Int2IntMap.Entry) i.next()).getIntKey(); - }; - @Override - public boolean hasNext() { - return i.hasNext(); - } - @Override - public void remove() { - i.remove(); - } - }; - } - }; - } - - /** - * Returns a type-specific-set view of the values of this map. - * - *

- * The view is backed by the set returned by {@link #entrySet()}. Note that - * no attempt is made at caching the result of this method, as this - * would require adding some attributes that lightweight implementations - * would not need. Subclasses may easily override this policy by calling - * this method and caching the result, but implementors are encouraged to - * write more efficient ad-hoc implementations. - * - * @return a set view of the values of this map; it may be safely cast to a - * type-specific interface. - */ - - public IntCollection values() { - return new AbstractIntCollection() { - - public boolean contains(final int k) { - return containsValue(k); - } - - public int size() { - return it.unimi.dsi.fastutil.ints.AbstractInt2IntMap.this.size(); - } - public void clear() { - it.unimi.dsi.fastutil.ints.AbstractInt2IntMap.this.clear(); - } - - public IntIterator iterator() { - return new AbstractIntIterator() { - final ObjectIterator> i = entrySet() - .iterator(); - - /** - * {@inheritDoc} - * - * @deprecated Please use the corresponding type-specific - * method instead. - */ - @Deprecated - public int nextInt() { - return ((Int2IntMap.Entry) i.next()).getIntValue(); - }; - - public boolean hasNext() { - return i.hasNext(); - } - }; - } - }; - } - - @SuppressWarnings({"unchecked", "rawtypes"}) - public ObjectSet> entrySet() { - return (ObjectSet) int2IntEntrySet(); - } - - /** - * Returns a hash code for this map. - * - * The hash code of a map is computed by summing the hash codes of its - * entries. - * - * @return a hash code for this map. - */ - - public int hashCode() { - int h = 0, n = size(); - final ObjectIterator> i = entrySet() - .iterator(); - - while (n-- != 0) - h += i.next().hashCode(); - return h; - } - - public boolean equals(Object o) { - if (o == this) - return true; - if (!(o instanceof Map)) - return false; - - Map m = (Map) o; - if (m.size() != size()) - return false; - return entrySet().containsAll(m.entrySet()); - } - - public String toString() { - final StringBuilder s = new StringBuilder(); - final ObjectIterator> i = entrySet() - .iterator(); - int n = size(); - Int2IntMap.Entry e; - boolean first = true; - - s.append("{"); - - while (n-- != 0) { - if (first) - first = false; - else - s.append(", "); - - e = (Int2IntMap.Entry) i.next(); - - s.append(String.valueOf(e.getIntKey())); - s.append("=>"); - - s.append(String.valueOf(e.getIntValue())); - } - - s.append("}"); - return s.toString(); - } - -} diff --git a/src/main/java/it/unimi/dsi/fastutil/ints/AbstractInt2ObjectFunction.java b/src/main/java/it/unimi/dsi/fastutil/ints/AbstractInt2ObjectFunction.java deleted file mode 100644 index 72f9a4b..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/ints/AbstractInt2ObjectFunction.java +++ /dev/null @@ -1,176 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Primitive-type-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.ints; - -import it.unimi.dsi.fastutil.ints.Int2ObjectFunction; - -/** - * An abstract class providing basic methods for functions implementing a - * type-specific interface. - * - *

- * Optional operations just throw an {@link UnsupportedOperationException}. - * Generic versions of accessors delegate to the corresponding type-specific - * counterparts following the interface rules (they take care of returning - * null on a missing key). - * - *

- * This class handles directly a default return value (including - * {@linkplain #defaultReturnValue() methods to access it}). Instances of classes - * inheriting from this class have just to return defRetValue to - * denote lack of a key in type-specific methods. The value is serialized. - * - *

- * Implementing subclasses have just to provide type-specific get() - * , type-specific containsKey(), and size() methods. - * - */ - -public abstract class AbstractInt2ObjectFunction - implements - Int2ObjectFunction, - java.io.Serializable { - - private static final long serialVersionUID = -4940583368468432370L; - - protected AbstractInt2ObjectFunction() { - } - - /** - * The default return value for get(), put() and - * remove(). - */ - - protected V defRetValue; - - public void defaultReturnValue(final V rv) { - defRetValue = rv; - } - - public V defaultReturnValue() { - return defRetValue; - } - - public V put(int key, V value) { - throw new UnsupportedOperationException(); - } - - public V remove(int key) { - throw new UnsupportedOperationException(); - } - - public void clear() { - throw new UnsupportedOperationException(); - } - - public boolean containsKey(final Object ok) { - if (ok == null) - return false; - return containsKey(((((Integer) (ok)).intValue()))); - } - /** - * Delegates to the corresponding type-specific method, taking care of - * returning null on a missing key. - * - *

- * This method must check whether the provided key is in the map using - * containsKey(). Thus, it probes the map twice. - * Implementors of subclasses should override it with a more efficient - * method. - */ - - public V get(final Object ok) { - - if (ok == null) - return null; - - final int k = ((((Integer) (ok)).intValue())); - return containsKey(k) ? (get(k)) : null; - } - - /** - * Delegates to the corresponding type-specific method, taking care of - * returning null on a missing key. - * - *

- * This method must check whether the provided key is in the map using - * containsKey(). Thus, it probes the map twice. - * Implementors of subclasses should override it with a more efficient - * method. - * - * @deprecated Please use the corresponding type-specific method instead. - */ - @Deprecated - public V put(final Integer ok, final V ov) { - final int k = ((ok).intValue()); - final boolean containsKey = containsKey(k); - final V v = put(k, (ov)); - return containsKey ? (v) : null; - } - /** - * Delegates to the corresponding type-specific method, taking care of - * returning null on a missing key. - * - *

- * This method must check whether the provided key is in the map using - * containsKey(). Thus, it probes the map twice. - * Implementors of subclasses should override it with a more efficient - * method. - */ - - public V remove(final Object ok) { - - if (ok == null) - return null; - - final int k = ((((Integer) (ok)).intValue())); - final boolean containsKey = containsKey(k); - final V v = remove(k); - return containsKey ? (v) : null; - } - -} diff --git a/src/main/java/it/unimi/dsi/fastutil/ints/AbstractInt2ObjectMap.java b/src/main/java/it/unimi/dsi/fastutil/ints/AbstractInt2ObjectMap.java deleted file mode 100644 index 215ae17..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/ints/AbstractInt2ObjectMap.java +++ /dev/null @@ -1,375 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Primitive-type-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.ints; - -import it.unimi.dsi.fastutil.ints.AbstractInt2ObjectFunction; -import it.unimi.dsi.fastutil.ints.AbstractIntIterator; -import it.unimi.dsi.fastutil.ints.AbstractIntSet; -import it.unimi.dsi.fastutil.ints.Int2ObjectMap; -import it.unimi.dsi.fastutil.ints.IntIterator; -import it.unimi.dsi.fastutil.ints.IntSet; -import it.unimi.dsi.fastutil.objects.AbstractObjectCollection; -import it.unimi.dsi.fastutil.objects.AbstractObjectIterator; -import it.unimi.dsi.fastutil.objects.ObjectCollection; -import it.unimi.dsi.fastutil.objects.ObjectIterator; -import it.unimi.dsi.fastutil.objects.ObjectSet; - -import java.util.Iterator; -import java.util.Map; - -/** - * An abstract class providing basic methods for maps implementing a - * type-specific interface. - * - *

- * Optional operations just throw an {@link UnsupportedOperationException}. - * Generic versions of accessors delegate to the corresponding type-specific - * counterparts following the interface rules (they take care of returning - * null on a missing key). - * - *

- * As a further help, this class provides a {@link BasicEntry BasicEntry} inner - * class that implements a type-specific version of {@link Map.Entry}; - * it is particularly useful for those classes that do not implement their own - * entries (e.g., most immutable maps). - */ - -public abstract class AbstractInt2ObjectMap - extends - AbstractInt2ObjectFunction - implements - Int2ObjectMap, - java.io.Serializable { - - private static final long serialVersionUID = -4940583368468432370L; - - protected AbstractInt2ObjectMap() { - } - /** Checks whether the given value is contained in {@link #values()}. */ - public boolean containsValue(Object v) { - return values().contains(v); - } - - /** Checks whether the given value is contained in {@link #keySet()}. */ - public boolean containsKey(int k) { - return keySet().contains(k); - } - - /** - * Puts all pairs in the given map. If the map implements the interface of - * this map, it uses the faster iterators. - * - * @param m - * a map. - */ - - @SuppressWarnings({"unchecked", "deprecation"}) - public void putAll(Map m) { - int n = m.size(); - final Iterator> i = m - .entrySet().iterator(); - - if (m instanceof Int2ObjectMap) { - Entry e; - while (n-- != 0) { - e = (Entry) i.next(); - put(e.getIntKey(), e.getValue()); - } - } else { - Map.Entry e; - while (n-- != 0) { - e = i.next(); - put(e.getKey(), e.getValue()); - } - } - } - - public boolean isEmpty() { - return size() == 0; - } - - /** - * This class provides a basic but complete type-specific entry class for - * all those maps implementations that do not have entries on their own - * (e.g., most immutable maps). - * - *

- * This class does not implement - * {@link Map.Entry#setValue(Object) setValue()}, as the - * modification would not be reflected in the base map. - */ - - public static class BasicEntry implements Entry { - protected int key; - protected V value; - - public BasicEntry(final Integer key, final V value) { - this.key = ((key).intValue()); - this.value = (value); - } - - public BasicEntry(final int key, final V value) { - this.key = key; - this.value = value; - } - - /** - * {@inheritDoc} - * - * @deprecated Please use the corresponding type-specific method - * instead. - */ - @Deprecated - public Integer getKey() { - return (Integer.valueOf(key)); - } - - public int getIntKey() { - return key; - } - - public V getValue() { - return (value); - } - - public V setValue(final V value) { - throw new UnsupportedOperationException(); - } - public boolean equals(final Object o) { - if (!(o instanceof Map.Entry)) - return false; - final Map.Entry e = (Map.Entry) o; - - if (e.getKey() == null || !(e.getKey() instanceof Integer)) - return false; - - return ((key) == (((((Integer) (e.getKey())).intValue())))) - && ((value) == null ? ((e.getValue())) == null : (value) - .equals((e.getValue()))); - } - - public int hashCode() { - return (key) ^ ((value) == null ? 0 : (value).hashCode()); - } - - public String toString() { - return key + "->" + value; - } - } - - /** - * Returns a type-specific-set view of the keys of this map. - * - *

- * The view is backed by the set returned by {@link #entrySet()}. Note that - * no attempt is made at caching the result of this method, as this - * would require adding some attributes that lightweight implementations - * would not need. Subclasses may easily override this policy by calling - * this method and caching the result, but implementors are encouraged to - * write more efficient ad-hoc implementations. - * - * @return a set view of the keys of this map; it may be safely cast to a - * type-specific interface. - */ - - public IntSet keySet() { - return new AbstractIntSet() { - - public boolean contains(final int k) { - return containsKey(k); - } - - public int size() { - return it.unimi.dsi.fastutil.ints.AbstractInt2ObjectMap.this.size(); - } - public void clear() { - it.unimi.dsi.fastutil.ints.AbstractInt2ObjectMap.this.clear(); - } - - public IntIterator iterator() { - return new AbstractIntIterator() { - final ObjectIterator> i = entrySet() - .iterator(); - @Override - public int nextInt() { - return ((Entry) i.next()).getIntKey(); - }; - @Override - public boolean hasNext() { - return i.hasNext(); - } - @Override - public void remove() { - i.remove(); - } - }; - } - }; - } - - /** - * Returns a type-specific-set view of the values of this map. - * - *

- * The view is backed by the set returned by {@link #entrySet()}. Note that - * no attempt is made at caching the result of this method, as this - * would require adding some attributes that lightweight implementations - * would not need. Subclasses may easily override this policy by calling - * this method and caching the result, but implementors are encouraged to - * write more efficient ad-hoc implementations. - * - * @return a set view of the values of this map; it may be safely cast to a - * type-specific interface. - */ - - public ObjectCollection values() { - return new AbstractObjectCollection() { - - public boolean contains(final Object k) { - return containsValue(k); - } - - public int size() { - return it.unimi.dsi.fastutil.ints.AbstractInt2ObjectMap.this.size(); - } - public void clear() { - it.unimi.dsi.fastutil.ints.AbstractInt2ObjectMap.this.clear(); - } - - public ObjectIterator iterator() { - return new AbstractObjectIterator() { - final ObjectIterator> i = entrySet() - .iterator(); - - /** - * {@inheritDoc} - * - * @deprecated Please use the corresponding type-specific - * method instead. - */ - @Deprecated - public V next() { - return ((Entry) i.next()).getValue(); - }; - - public boolean hasNext() { - return i.hasNext(); - } - }; - } - }; - } - - @SuppressWarnings({"unchecked", "rawtypes"}) - public ObjectSet> entrySet() { - return (ObjectSet) int2ObjectEntrySet(); - } - - /** - * Returns a hash code for this map. - * - * The hash code of a map is computed by summing the hash codes of its - * entries. - * - * @return a hash code for this map. - */ - - public int hashCode() { - int h = 0, n = size(); - final ObjectIterator> i = entrySet() - .iterator(); - - while (n-- != 0) - h += i.next().hashCode(); - return h; - } - - public boolean equals(Object o) { - if (o == this) - return true; - if (!(o instanceof Map)) - return false; - - Map m = (Map) o; - if (m.size() != size()) - return false; - return entrySet().containsAll(m.entrySet()); - } - - public String toString() { - final StringBuilder s = new StringBuilder(); - final ObjectIterator> i = entrySet() - .iterator(); - int n = size(); - Entry e; - boolean first = true; - - s.append("{"); - - while (n-- != 0) { - if (first) - first = false; - else - s.append(", "); - - e = (Entry) i.next(); - - s.append(String.valueOf(e.getIntKey())); - s.append("=>"); - - if (this == e.getValue()) - s.append("(this map)"); - else - - s.append(String.valueOf(e.getValue())); - } - - s.append("}"); - return s.toString(); - } - -} diff --git a/src/main/java/it/unimi/dsi/fastutil/ints/AbstractIntBidirectionalIterator.java b/src/main/java/it/unimi/dsi/fastutil/ints/AbstractIntBidirectionalIterator.java deleted file mode 100644 index 0a94428..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/ints/AbstractIntBidirectionalIterator.java +++ /dev/null @@ -1,98 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Primitive-type-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.ints; - -import it.unimi.dsi.fastutil.ints.AbstractIntIterator; -import it.unimi.dsi.fastutil.ints.IntBidirectionalIterator; - -/** - * An abstract class facilitating the creation of type-specific - * {@linkplain it.unimi.dsi.fastutil.BidirectionalIterator bidirectional - * iterators}. - * - *

- * To create a type-specific bidirectional iterator, besides what is needed for - * an iterator you need both a method returning the previous element as - * primitive type and a method returning the previous element as an object. - * However, if you inherit from this class you need just one (anyone). - * - *

- * This class implements also a trivial version of {@link #back(int)} that uses - * type-specific methods. - */ - -public abstract class AbstractIntBidirectionalIterator - extends - AbstractIntIterator - implements IntBidirectionalIterator { - - protected AbstractIntBidirectionalIterator() { - } - - /** Delegates to the corresponding generic method. */ - public int previousInt() { - return previous().intValue(); - } - - /** Delegates to the corresponding type-specific method. */ - public Integer previous() { - return Integer.valueOf(previousInt()); - } - - /** - * This method just iterates the type-specific version of - * {@link #previous()} for at most n times, stopping if - * {@link #hasPrevious()} becomes false. - */ - public int back(final int n) { - int i = n; - while (i-- != 0 && hasPrevious()) - previousInt(); - return n - i - 1; - } - -} diff --git a/src/main/java/it/unimi/dsi/fastutil/ints/AbstractIntCollection.java b/src/main/java/it/unimi/dsi/fastutil/ints/AbstractIntCollection.java deleted file mode 100644 index cea3f44..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/ints/AbstractIntCollection.java +++ /dev/null @@ -1,368 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Primitive-type-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.ints; - -import it.unimi.dsi.fastutil.ints.IntCollection; -import it.unimi.dsi.fastutil.ints.IntIterator; -import it.unimi.dsi.fastutil.ints.IntIterators; - -import java.util.AbstractCollection; -import java.util.Collection; -import java.util.Iterator; - -/** - * An abstract class providing basic methods for collections implementing a - * type-specific interface. - * - *

- * In particular, this class provide {@link #iterator()}, add(), - * {@link #remove(Object)} and {@link #contains(Object)} methods that just call - * the type-specific counterpart. - */ - -public abstract class AbstractIntCollection extends AbstractCollection - implements - IntCollection { - - protected AbstractIntCollection() { - } - - public int[] toArray(int a[]) { - return toIntArray(a); - } - - public int[] toIntArray() { - return toIntArray(null); - } - - public int[] toIntArray(int a[]) { - if (a == null || a.length < size()) - a = new int[size()]; - IntIterators.unwrap(iterator(), a); - return a; - } - - /** - * Adds all elements of the given type-specific collection to this - * collection. - * - * @param c - * a type-specific collection. - * @return true if this collection changed as a result of the - * call. - */ - - public boolean addAll(IntCollection c) { - boolean retVal = false; - final IntIterator i = c.iterator(); - int n = c.size(); - - while (n-- != 0) - if (add(i.nextInt())) - retVal = true; - return retVal; - } - - /** - * Checks whether this collection contains all elements from the given - * type-specific collection. - * - * @param c - * a type-specific collection. - * @return true if this collection contains all elements of the - * argument. - */ - - public boolean containsAll(IntCollection c) { - final IntIterator i = c.iterator(); - int n = c.size(); - - while (n-- != 0) - if (!contains(i.nextInt())) - return false; - - return true; - } - - /** - * Retains in this collection only elements from the given type-specific - * collection. - * - * @param c - * a type-specific collection. - * @return true if this collection changed as a result of the - * call. - */ - - public boolean retainAll(IntCollection c) { - boolean retVal = false; - int n = size(); - - final IntIterator i = iterator(); - - while (n-- != 0) { - if (!c.contains(i.nextInt())) { - i.remove(); - retVal = true; - } - } - - return retVal; - } - - /** - * Remove from this collection all elements in the given type-specific - * collection. - * - * @param c - * a type-specific collection. - * @return true if this collection changed as a result of the - * call. - */ - - public boolean removeAll(IntCollection c) { - boolean retVal = false; - int n = c.size(); - - final IntIterator i = c.iterator(); - - while (n-- != 0) - if (rem(i.nextInt())) - retVal = true; - - return retVal; - } - - public Object[] toArray() { - final Object[] a = new Object[size()]; - it.unimi.dsi.fastutil.objects.ObjectIterators.unwrap(iterator(), a); - return a; - } - - @SuppressWarnings("unchecked") - public T[] toArray(T[] a) { - final int size = size(); - if (a.length < size) - a = (T[]) java.lang.reflect.Array.newInstance(a.getClass() - .getComponentType(), size); - it.unimi.dsi.fastutil.objects.ObjectIterators.unwrap(iterator(), a); - if (size < a.length) - a[size] = null; - return a; - } - - /** - * Adds all elements of the given collection to this collection. - * - * @param c - * a collection. - * @return true if this collection changed as a result of the - * call. - */ - - public boolean addAll(Collection c) { - boolean retVal = false; - final Iterator i = c.iterator(); - int n = c.size(); - - while (n-- != 0) - if (add(i.next())) - retVal = true; - return retVal; - } - - public boolean add(int k) { - throw new UnsupportedOperationException(); - } - - /** Delegates to the new covariantly stronger generic method. */ - - @Deprecated - public IntIterator intIterator() { - return iterator(); - } - - public abstract IntIterator iterator(); - - /** Delegates to the type-specific rem() method. */ - public boolean remove(Object ok) { - if (ok == null) - return false; - return rem(((((Integer) (ok)).intValue()))); - } - - /** Delegates to the corresponding type-specific method. */ - public boolean add(final Integer o) { - return add(o.intValue()); - } - - /** Delegates to the corresponding type-specific method. */ - public boolean rem(final Object o) { - if (o == null) - return false; - return rem(((((Integer) (o)).intValue()))); - } - - /** Delegates to the corresponding type-specific method. */ - public boolean contains(final Object o) { - if (o == null) - return false; - return contains(((((Integer) (o)).intValue()))); - } - - public boolean contains(final int k) { - final IntIterator iterator = iterator(); - while (iterator.hasNext()) - if (k == iterator.nextInt()) - return true; - return false; - } - - public boolean rem(final int k) { - final IntIterator iterator = iterator(); - while (iterator.hasNext()) - if (k == iterator.nextInt()) { - iterator.remove(); - return true; - } - return false; - } - - /** - * Checks whether this collection contains all elements from the given - * collection. - * - * @param c - * a collection. - * @return true if this collection contains all elements of the - * argument. - */ - - public boolean containsAll(Collection c) { - int n = c.size(); - - final Iterator i = c.iterator(); - while (n-- != 0) - if (!contains(i.next())) - return false; - - return true; - } - - /** - * Retains in this collection only elements from the given collection. - * - * @param c - * a collection. - * @return true if this collection changed as a result of the - * call. - */ - - public boolean retainAll(Collection c) { - boolean retVal = false; - int n = size(); - - final Iterator i = iterator(); - while (n-- != 0) { - if (!c.contains(i.next())) { - i.remove(); - retVal = true; - } - } - - return retVal; - } - - /** - * Remove from this collection all elements in the given collection. If the - * collection is an instance of this class, it uses faster iterators. - * - * @param c - * a collection. - * @return true if this collection changed as a result of the - * call. - */ - - public boolean removeAll(Collection c) { - boolean retVal = false; - int n = c.size(); - - final Iterator i = c.iterator(); - while (n-- != 0) - if (remove(i.next())) - retVal = true; - - return retVal; - } - - public boolean isEmpty() { - return size() == 0; - } - - public String toString() { - final StringBuilder s = new StringBuilder(); - final IntIterator i = iterator(); - int n = size(); - int k; - boolean first = true; - - s.append("{"); - - while (n-- != 0) { - if (first) - first = false; - else - s.append(", "); - k = i.nextInt(); - - s.append(String.valueOf(k)); - } - - s.append("}"); - return s.toString(); - } -} diff --git a/src/main/java/it/unimi/dsi/fastutil/ints/AbstractIntIterator.java b/src/main/java/it/unimi/dsi/fastutil/ints/AbstractIntIterator.java deleted file mode 100644 index c88a9d2..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/ints/AbstractIntIterator.java +++ /dev/null @@ -1,105 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Primitive-type-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.ints; - -import it.unimi.dsi.fastutil.ints.IntIterator; - -/** - * An abstract class facilitating the creation of type-specific iterators. - * - *

- * To create a type-specific iterator you need both a method returning the next - * element as primitive type and a method returning the next element as an - * object. However, if you inherit from this class you need just one (anyone). - * - *

- * This class implements also a trivial version of {@link #skip(int)} that uses - * type-specific methods; moreover, {@link #remove()} will throw an - * {@link UnsupportedOperationException}. - * - * @see java.util.Iterator - */ - -public abstract class AbstractIntIterator - implements IntIterator { - - protected AbstractIntIterator() { - } - - /** Delegates to the corresponding generic method. */ - public int nextInt() { - return next().intValue(); - } - - /** - * Delegates to the corresponding type-specific method. - * - * @deprecated Please use the corresponding type-specific method instead. - */ - @Deprecated - public Integer next() { - return Integer.valueOf(nextInt()); - } - - /** This method just throws an {@link UnsupportedOperationException}. */ - public void remove() { - throw new UnsupportedOperationException(); - } - - /** - * This method just iterates the type-specific version of {@link #next()} - * for at most n times, stopping if {@link #hasNext()} becomes - * false. - */ - - public int skip(final int n) { - int i = n; - while (i-- != 0 && hasNext()) - nextInt(); - return n - i - 1; - } -} diff --git a/src/main/java/it/unimi/dsi/fastutil/ints/AbstractIntList.java b/src/main/java/it/unimi/dsi/fastutil/ints/AbstractIntList.java deleted file mode 100644 index 8b1800d..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/ints/AbstractIntList.java +++ /dev/null @@ -1,840 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Primitive-type-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.ints; - -import it.unimi.dsi.fastutil.ints.AbstractIntCollection; -import it.unimi.dsi.fastutil.ints.AbstractIntListIterator; -import it.unimi.dsi.fastutil.ints.IntCollection; -import it.unimi.dsi.fastutil.ints.IntIterator; -import it.unimi.dsi.fastutil.ints.IntList; -import it.unimi.dsi.fastutil.ints.IntListIterator; -import it.unimi.dsi.fastutil.ints.IntStack; - -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; -import java.util.NoSuchElementException; - -/** - * An abstract class providing basic methods for lists implementing a - * type-specific list interface. - * - *

- * As an additional bonus, this class implements on top of the list operations a - * type-specific stack. - */ - -public abstract class AbstractIntList extends AbstractIntCollection - implements - IntList, - IntStack { - - protected AbstractIntList() { - } - - /** - * Ensures that the given index is nonnegative and not greater than the list - * size. - * - * @param index - * an index. - * @throws IndexOutOfBoundsException - * if the given index is negative or greater than the list size. - */ - protected void ensureIndex(final int index) { - if (index < 0) - throw new IndexOutOfBoundsException("Index (" + index - + ") is negative"); - if (index > size()) - throw new IndexOutOfBoundsException("Index (" + index - + ") is greater than list size (" + (size()) + ")"); - } - - /** - * Ensures that the given index is nonnegative and smaller than the list - * size. - * - * @param index - * an index. - * @throws IndexOutOfBoundsException - * if the given index is negative or not smaller than the list - * size. - */ - protected void ensureRestrictedIndex(final int index) { - if (index < 0) - throw new IndexOutOfBoundsException("Index (" + index - + ") is negative"); - if (index >= size()) - throw new IndexOutOfBoundsException("Index (" + index - + ") is greater than or equal to list size (" + (size()) - + ")"); - } - - public void add(final int index, final int k) { - throw new UnsupportedOperationException(); - } - - public boolean add(final int k) { - add(size(), k); - return true; - } - - public int removeInt(int i) { - throw new UnsupportedOperationException(); - } - - public int set(final int index, final int k) { - throw new UnsupportedOperationException(); - } - - public boolean addAll(int index, final Collection c) { - ensureIndex(index); - int n = c.size(); - if (n == 0) - return false; - Iterator i = c.iterator(); - while (n-- != 0) - add(index++, i.next()); - return true; - } - - /** Delegates to a more generic method. */ - public boolean addAll(final Collection c) { - return addAll(size(), c); - } - - /** Delegates to the new covariantly stronger generic method. */ - - @Deprecated - public IntListIterator intListIterator() { - return listIterator(); - } - - /** Delegates to the new covariantly stronger generic method. */ - - @Deprecated - public IntListIterator intListIterator(final int index) { - return listIterator(index); - } - - public IntListIterator iterator() { - return listIterator(); - } - - public IntListIterator listIterator() { - return listIterator(0); - } - - public IntListIterator listIterator(final int index) { - ensureIndex(index); - - return new AbstractIntListIterator() { - int pos = index, last = -1; - - public boolean hasNext() { - return pos < it.unimi.dsi.fastutil.ints.AbstractIntList.this.size(); - } - public boolean hasPrevious() { - return pos > 0; - } - public int nextInt() { - if (!hasNext()) - throw new NoSuchElementException(); - return it.unimi.dsi.fastutil.ints.AbstractIntList.this.getInt(last = pos++); - } - public int previousInt() { - if (!hasPrevious()) - throw new NoSuchElementException(); - return it.unimi.dsi.fastutil.ints.AbstractIntList.this.getInt(last = --pos); - } - public int nextIndex() { - return pos; - } - public int previousIndex() { - return pos - 1; - } - public void add(int k) { - it.unimi.dsi.fastutil.ints.AbstractIntList.this.add(pos++, k); - last = -1; - } - public void set(int k) { - if (last == -1) - throw new IllegalStateException(); - it.unimi.dsi.fastutil.ints.AbstractIntList.this.set(last, k); - } - public void remove() { - if (last == -1) - throw new IllegalStateException(); - it.unimi.dsi.fastutil.ints.AbstractIntList.this.removeInt(last); - /* - * If the last operation was a next(), we are removing an - * element *before* us, and we must decrease pos - * correspondingly. - */ - if (last < pos) - pos--; - last = -1; - } - }; - } - - public boolean contains(final int k) { - return indexOf(k) >= 0; - } - - public int indexOf(final int k) { - final IntListIterator i = listIterator(); - int e; - while (i.hasNext()) { - e = i.nextInt(); - if (((k) == (e))) - return i.previousIndex(); - } - return -1; - } - - public int lastIndexOf(final int k) { - IntListIterator i = listIterator(size()); - int e; - while (i.hasPrevious()) { - e = i.previousInt(); - if (((k) == (e))) - return i.nextIndex(); - } - return -1; - } - - public void size(final int size) { - int i = size(); - if (size > i) - while (i++ < size) - add((0)); - else - while (i-- != size) - remove(i); - } - - public IntList subList(final int from, final int to) { - ensureIndex(from); - ensureIndex(to); - if (from > to) - throw new IndexOutOfBoundsException("Start index (" + from - + ") is greater than end index (" + to + ")"); - - return new IntSubList(this, from, to); - } - - /** Delegates to the new covariantly stronger generic method. */ - - @Deprecated - public IntList intSubList(final int from, final int to) { - return subList(from, to); - } - - /** - * Removes elements of this type-specific list one-by-one. - * - *

- * This is a trivial iterator-based implementation. It is expected that - * implementations will override this method with a more optimized version. - * - * - * @param from - * the start index (inclusive). - * @param to - * the end index (exclusive). - */ - - public void removeElements(final int from, final int to) { - ensureIndex(to); - IntListIterator i = listIterator(from); - int n = to - from; - if (n < 0) - throw new IllegalArgumentException("Start index (" + from - + ") is greater than end index (" + to + ")"); - while (n-- != 0) { - i.nextInt(); - i.remove(); - } - } - - /** - * Adds elements to this type-specific list one-by-one. - * - *

- * This is a trivial iterator-based implementation. It is expected that - * implementations will override this method with a more optimized version. - * - * @param index - * the index at which to add elements. - * @param a - * the array containing the elements. - * @param offset - * the offset of the first element to add. - * @param length - * the number of elements to add. - */ - - public void addElements(int index, final int a[], int offset, int length) { - ensureIndex(index); - if (offset < 0) - throw new ArrayIndexOutOfBoundsException("Offset (" + offset - + ") is negative"); - if (offset + length > a.length) - throw new ArrayIndexOutOfBoundsException("End index (" - + (offset + length) + ") is greater than array length (" - + a.length + ")"); - while (length-- != 0) - add(index++, a[offset++]); - } - - public void addElements(final int index, final int a[]) { - addElements(index, a, 0, a.length); - } - - /** - * Copies element of this type-specific list into the given array - * one-by-one. - * - *

- * This is a trivial iterator-based implementation. It is expected that - * implementations will override this method with a more optimized version. - * - * @param from - * the start index (inclusive). - * @param a - * the destination array. - * @param offset - * the offset into the destination array where to store the first - * element copied. - * @param length - * the number of elements to be copied. - */ - - public void getElements(final int from, final int a[], int offset, - int length) { - IntListIterator i = listIterator(from); - if (offset < 0) - throw new ArrayIndexOutOfBoundsException("Offset (" + offset - + ") is negative"); - if (offset + length > a.length) - throw new ArrayIndexOutOfBoundsException("End index (" - + (offset + length) + ") is greater than array length (" - + a.length + ")"); - if (from + length > size()) - throw new IndexOutOfBoundsException("End index (" + (from + length) - + ") is greater than list size (" + size() + ")"); - while (length-- != 0) - a[offset++] = i.nextInt(); - } - - private boolean valEquals(final Object a, final Object b) { - return a == null ? b == null : a.equals(b); - } - - public boolean equals(final Object o) { - if (o == this) - return true; - if (!(o instanceof List)) - return false; - - final List l = (List) o; - int s = size(); - if (s != l.size()) - return false; - - if (l instanceof IntList) { - final IntListIterator i1 = listIterator(), i2 = ((IntList) l) - .listIterator(); - while (s-- != 0) - if (i1.nextInt() != i2.nextInt()) - return false; - return true; - } - - final ListIterator i1 = listIterator(), i2 = l.listIterator(); - - while (s-- != 0) - if (!valEquals(i1.next(), i2.next())) - return false; - - return true; - } - - /** - * Compares this list to another object. If the argument is a - * {@link List}, this method performs a lexicographical - * comparison; otherwise, it throws a ClassCastException. - * - * @param l - * a list. - * @return if the argument is a {@link List}, a negative integer, - * zero, or a positive integer as this list is lexicographically - * less than, equal to, or greater than the argument. - * @throws ClassCastException - * if the argument is not a list. - */ - - public int compareTo(final List l) { - if (l == this) - return 0; - - if (l instanceof IntList) { - - final IntListIterator i1 = listIterator(), i2 = ((IntList) l) - .listIterator(); - int r; - int e1, e2; - - while (i1.hasNext() && i2.hasNext()) { - e1 = i1.nextInt(); - e2 = i2.nextInt(); - if ((r = (Integer.compare((e1), (e2)))) != 0) - return r; - } - return i2.hasNext() ? -1 : (i1.hasNext() ? 1 : 0); - } - - ListIterator i1 = listIterator(), i2 = l - .listIterator(); - int r; - - while (i1.hasNext() && i2.hasNext()) { - if ((r = ((Comparable) i1.next()).compareTo(i2 - .next())) != 0) - return r; - } - return i2.hasNext() ? -1 : (i1.hasNext() ? 1 : 0); - } - - /** - * Returns the hash code for this list, which is identical to - * {@link List#hashCode()}. - * - * @return the hash code for this list. - */ - public int hashCode() { - IntIterator i = iterator(); - int h = 1, s = size(); - while (s-- != 0) { - int k = i.nextInt(); - h = 31 * h + (k); - } - return h; - } - - public void push(int o) { - add(o); - } - - public int popInt() { - if (isEmpty()) - throw new NoSuchElementException(); - return removeInt(size() - 1); - } - - public int topInt() { - if (isEmpty()) - throw new NoSuchElementException(); - return getInt(size() - 1); - } - - public int peekInt(int i) { - return getInt(size() - 1 - i); - } - - public boolean rem(int k) { - int index = indexOf(k); - if (index == -1) - return false; - removeInt(index); - return true; - } - - /** Delegates to rem(). */ - public boolean remove(final Object o) { - return rem(((((Integer) (o)).intValue()))); - } - - /** Delegates to a more generic method. */ - public boolean addAll(final int index, final IntCollection c) { - return addAll(index, (Collection) c); - } - - /** Delegates to a more generic method. */ - public boolean addAll(final int index, final IntList l) { - return addAll(index, (IntCollection) l); - } - - public boolean addAll(final IntCollection c) { - return addAll(size(), c); - } - - public boolean addAll(final IntList l) { - return addAll(size(), l); - } - - /** Delegates to the corresponding type-specific method. */ - public void add(final int index, final Integer ok) { - add(index, ok.intValue()); - } - - /** - * Delegates to the corresponding type-specific method. - * - * @deprecated Please use the corresponding type-specific method instead. - */ - @Deprecated - public Integer set(final int index, final Integer ok) { - return (Integer.valueOf(set(index, ok.intValue()))); - } - - /** - * Delegates to the corresponding type-specific method. - * - * @deprecated Please use the corresponding type-specific method instead. - */ - @Deprecated - public Integer get(final int index) { - return (Integer.valueOf(getInt(index))); - } - - /** Delegates to the corresponding type-specific method. */ - public int indexOf(final Object ok) { - return indexOf(((((Integer) (ok)).intValue()))); - } - - /** Delegates to the corresponding type-specific method. */ - public int lastIndexOf(final Object ok) { - return lastIndexOf(((((Integer) (ok)).intValue()))); - } - - /** - * Delegates to the corresponding type-specific method. - * - * @deprecated Please use the corresponding type-specific method instead. - */ - @Deprecated - public Integer remove(final int index) { - return (Integer.valueOf(removeInt(index))); - } - - /** Delegates to the corresponding type-specific method. */ - public void push(Integer o) { - push(o.intValue()); - } - - /** - * Delegates to the corresponding type-specific method. - * - * @deprecated Please use the corresponding type-specific method instead. - */ - @Deprecated - public Integer pop() { - return Integer.valueOf(popInt()); - } - - /** - * Delegates to the corresponding type-specific method. - * - * @deprecated Please use the corresponding type-specific method instead. - */ - @Deprecated - public Integer top() { - return Integer.valueOf(topInt()); - } - - /** - * Delegates to the corresponding type-specific method. - * - * @deprecated Please use the corresponding type-specific method instead. - */ - @Deprecated - public Integer peek(int i) { - return Integer.valueOf(peekInt(i)); - } - - public String toString() { - final StringBuilder s = new StringBuilder(); - final IntIterator i = iterator(); - int n = size(); - int k; - boolean first = true; - - s.append("["); - - while (n-- != 0) { - if (first) - first = false; - else - s.append(", "); - k = i.nextInt(); - - s.append(String.valueOf(k)); - } - - s.append("]"); - return s.toString(); - } - - public static class IntSubList extends it.unimi.dsi.fastutil.ints.AbstractIntList - implements - java.io.Serializable { - private static final long serialVersionUID = -7046029254386353129L; - /** The list this sublist restricts. */ - protected final IntList l; - /** Initial (inclusive) index of this sublist. */ - protected final int from; - /** Final (exclusive) index of this sublist. */ - protected int to; - - private static final boolean ASSERTS = false; - - public IntSubList(final IntList l, final int from, final int to) { - this.l = l; - this.from = from; - this.to = to; - } - - private void assertRange() { - if (ASSERTS) { - assert from <= l.size(); - assert to <= l.size(); - assert to >= from; - } - } - - public boolean add(final int k) { - l.add(to, k); - to++; - if (ASSERTS) - assertRange(); - return true; - } - - public void add(final int index, final int k) { - ensureIndex(index); - l.add(from + index, k); - to++; - if (ASSERTS) - assertRange(); - } - - public boolean addAll(final int index, - final Collection c) { - ensureIndex(index); - to += c.size(); - if (ASSERTS) { - boolean retVal = l.addAll(from + index, c); - assertRange(); - return retVal; - } - return l.addAll(from + index, c); - } - - public int getInt(int index) { - ensureRestrictedIndex(index); - return l.getInt(from + index); - } - - public int removeInt(int index) { - ensureRestrictedIndex(index); - to--; - return l.removeInt(from + index); - } - - public int set(int index, int k) { - ensureRestrictedIndex(index); - return l.set(from + index, k); - } - - public void clear() { - removeElements(0, size()); - if (ASSERTS) - assertRange(); - } - - public int size() { - return to - from; - } - - public void getElements(final int from, final int[] a, - final int offset, final int length) { - ensureIndex(from); - if (from + length > size()) - throw new IndexOutOfBoundsException("End index (" + from - + length + ") is greater than list size (" + size() - + ")"); - l.getElements(this.from + from, a, offset, length); - } - - public void removeElements(final int from, final int to) { - ensureIndex(from); - ensureIndex(to); - l.removeElements(this.from + from, this.from + to); - this.to -= (to - from); - if (ASSERTS) - assertRange(); - } - - public void addElements(int index, final int a[], int offset, int length) { - ensureIndex(index); - l.addElements(this.from + index, a, offset, length); - this.to += length; - if (ASSERTS) - assertRange(); - } - - public IntListIterator listIterator(final int index) { - ensureIndex(index); - - return new AbstractIntListIterator() { - int pos = index, last = -1; - - public boolean hasNext() { - return pos < size(); - } - public boolean hasPrevious() { - return pos > 0; - } - public int nextInt() { - if (!hasNext()) - throw new NoSuchElementException(); - return l.getInt(from + (last = pos++)); - } - public int previousInt() { - if (!hasPrevious()) - throw new NoSuchElementException(); - return l.getInt(from + (last = --pos)); - } - public int nextIndex() { - return pos; - } - public int previousIndex() { - return pos - 1; - } - public void add(int k) { - if (last == -1) - throw new IllegalStateException(); - IntSubList.this.add(pos++, k); - last = -1; - if (ASSERTS) - assertRange(); - } - public void set(int k) { - if (last == -1) - throw new IllegalStateException(); - IntSubList.this.set(last, k); - } - public void remove() { - if (last == -1) - throw new IllegalStateException(); - IntSubList.this.removeInt(last); - /* - * If the last operation was a next(), we are removing an - * element *before* us, and we must decrease pos - * correspondingly. - */ - if (last < pos) - pos--; - last = -1; - if (ASSERTS) - assertRange(); - } - }; - } - - public IntList subList(final int from, final int to) { - ensureIndex(from); - ensureIndex(to); - if (from > to) - throw new IllegalArgumentException("Start index (" + from - + ") is greater than end index (" + to + ")"); - - return new IntSubList(this, from, to); - } - - public boolean rem(int k) { - int index = indexOf(k); - if (index == -1) - return false; - to--; - l.removeInt(from + index); - if (ASSERTS) - assertRange(); - return true; - } - - public boolean remove(final Object o) { - return rem(((((Integer) (o)).intValue()))); - } - - public boolean addAll(final int index, final IntCollection c) { - ensureIndex(index); - to += c.size(); - if (ASSERTS) { - boolean retVal = l.addAll(from + index, c); - assertRange(); - return retVal; - } - return l.addAll(from + index, c); - } - - public boolean addAll(final int index, final IntList l) { - ensureIndex(index); - to += l.size(); - if (ASSERTS) { - boolean retVal = this.l.addAll(from + index, l); - assertRange(); - return retVal; - } - return this.l.addAll(from + index, l); - } - } - -} diff --git a/src/main/java/it/unimi/dsi/fastutil/ints/AbstractIntListIterator.java b/src/main/java/it/unimi/dsi/fastutil/ints/AbstractIntListIterator.java deleted file mode 100644 index f1970db..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/ints/AbstractIntListIterator.java +++ /dev/null @@ -1,94 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Primitive-type-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.ints; - -import it.unimi.dsi.fastutil.ints.AbstractIntBidirectionalIterator; -import it.unimi.dsi.fastutil.ints.IntListIterator; - -/** - * An abstract class facilitating the creation of type-specific - * {@linkplain java.util.ListIterator list iterators}. - * - *

- * This class provides trivial type-specific implementations of - * {@link java.util.ListIterator#set(Object) set()} and - * {@link java.util.ListIterator#add(Object) add()} which throw an - * {@link UnsupportedOperationException}. For primitive types, it also provides - * a trivial implementation of {@link java.util.ListIterator#set(Object) set()} - * and {@link java.util.ListIterator#add(Object) add()} that just invokes the - * type-specific one. - * - * - * @see java.util.ListIterator - */ - -public abstract class AbstractIntListIterator - extends - AbstractIntBidirectionalIterator - implements IntListIterator { - - protected AbstractIntListIterator() { - } - - /** Delegates to the corresponding type-specific method. */ - public void set(Integer ok) { - set(ok.intValue()); - } - /** Delegates to the corresponding type-specific method. */ - public void add(Integer ok) { - add(ok.intValue()); - } - - /** This method just throws an {@link UnsupportedOperationException}. */ - public void set(int k) { - throw new UnsupportedOperationException(); - } - /** This method just throws an {@link UnsupportedOperationException}. */ - public void add(int k) { - throw new UnsupportedOperationException(); - } -} diff --git a/src/main/java/it/unimi/dsi/fastutil/ints/AbstractIntSet.java b/src/main/java/it/unimi/dsi/fastutil/ints/AbstractIntSet.java deleted file mode 100644 index 9bb6d7e..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/ints/AbstractIntSet.java +++ /dev/null @@ -1,113 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Primitive-type-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.ints; - -import it.unimi.dsi.fastutil.ints.AbstractIntCollection; -import it.unimi.dsi.fastutil.ints.IntIterator; -import it.unimi.dsi.fastutil.ints.IntSet; - -import java.util.Set; - -/** - * An abstract class providing basic methods for sets implementing a - * type-specific interface. - */ - -public abstract class AbstractIntSet extends AbstractIntCollection - implements - Cloneable, - IntSet { - - protected AbstractIntSet() { - } - - public abstract IntIterator iterator(); - - public boolean equals(final Object o) { - if (o == this) - return true; - if (!(o instanceof Set)) - return false; - - Set s = (Set) o; - if (s.size() != size()) - return false; - return containsAll(s); - } - - /** - * Returns a hash code for this set. - * - * The hash code of a set is computed by summing the hash codes of its - * elements. - * - * @return a hash code for this set. - */ - - public int hashCode() { - int h = 0, n = size(); - IntIterator i = iterator(); - int k; - - while (n-- != 0) { - k = i.nextInt(); // We need k because KEY2JAVAHASH() is a macro with - // repeated evaluation. - h += (k); - } - return h; - } - - public boolean remove(int k) { - return rem(k); - } - - /** Delegates to the corresponding type-specific method. */ - public boolean remove(final Object o) { - return remove(((((Integer) (o)).intValue()))); - } - -} diff --git a/src/main/java/it/unimi/dsi/fastutil/ints/Int2BooleanArrayMap.java b/src/main/java/it/unimi/dsi/fastutil/ints/Int2BooleanArrayMap.java deleted file mode 100644 index d8a1e53..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/ints/Int2BooleanArrayMap.java +++ /dev/null @@ -1,441 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Primitive-type-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* Primitive-type-only definitions (values) */ -/* - * Copyright (C) 2007-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.ints; - -import it.unimi.dsi.fastutil.booleans.BooleanArraySet; -import it.unimi.dsi.fastutil.booleans.BooleanArrays; -import it.unimi.dsi.fastutil.booleans.BooleanCollection; -import it.unimi.dsi.fastutil.booleans.BooleanCollections; -import it.unimi.dsi.fastutil.ints.AbstractInt2BooleanMap; -import it.unimi.dsi.fastutil.ints.Int2BooleanMap; -import it.unimi.dsi.fastutil.ints.IntArraySet; -import it.unimi.dsi.fastutil.ints.IntArrays; -import it.unimi.dsi.fastutil.ints.IntSet; -import it.unimi.dsi.fastutil.objects.AbstractObjectIterator; -import it.unimi.dsi.fastutil.objects.AbstractObjectSet; -import it.unimi.dsi.fastutil.objects.ObjectIterator; - -import java.util.Map; -import java.util.NoSuchElementException; - -/** - * A simple, brute-force implementation of a map based on two parallel backing - * arrays. - * - *

- * The main purpose of this implementation is that of wrapping cleanly the - * brute-force approach to the storage of a very small number of pairs: just put - * them into two parallel arrays and scan linearly to find an item. - */ - -public class Int2BooleanArrayMap extends AbstractInt2BooleanMap - implements - java.io.Serializable, - Cloneable { - - private static final long serialVersionUID = 1L; - /** The keys (valid up to {@link #size}, excluded). */ - private transient int[] key; - /** The values (parallel to {@link #key}). */ - private transient boolean[] value; - /** The number of valid entries in {@link #key} and {@link #value}. */ - private int size; - - /** - * Creates a new empty array map with given key and value backing arrays. - * The resulting map will have as many entries as the given arrays. - * - *

- * It is responsibility of the caller that the elements of key - * are distinct. - * - * @param key - * the key array. - * @param value - * the value array (it must have the same length as - * key). - */ - public Int2BooleanArrayMap(final int[] key, final boolean[] value) { - this.key = key; - this.value = value; - size = key.length; - if (key.length != value.length) - throw new IllegalArgumentException( - "Keys and values have different lengths (" + key.length - + ", " + value.length + ")"); - } - - /** - * Creates a new empty array map. - */ - public Int2BooleanArrayMap() { - this.key = IntArrays.EMPTY_ARRAY; - this.value = BooleanArrays.EMPTY_ARRAY; - } - - /** - * Creates a new empty array map of given capacity. - * - * @param capacity - * the initial capacity. - */ - public Int2BooleanArrayMap(final int capacity) { - this.key = new int[capacity]; - this.value = new boolean[capacity]; - } - - /** - * Creates a new empty array map copying the entries of a given map. - * - * @param m - * a map. - */ - public Int2BooleanArrayMap(final Int2BooleanMap m) { - this(m.size()); - putAll(m); - } - - /** - * Creates a new empty array map copying the entries of a given map. - * - * @param m - * a map. - */ - public Int2BooleanArrayMap(final Map m) { - this(m.size()); - putAll(m); - } - - /** - * Creates a new array map with given key and value backing arrays, using - * the given number of elements. - * - *

- * It is responsibility of the caller that the first size - * elements of key are distinct. - * - * @param key - * the key array. - * @param value - * the value array (it must have the same length as - * key). - * @param size - * the number of valid elements in key and - * value. - */ - public Int2BooleanArrayMap(final int[] key, final boolean[] value, - final int size) { - this.key = key; - this.value = value; - this.size = size; - if (key.length != value.length) - throw new IllegalArgumentException( - "Keys and values have different lengths (" + key.length - + ", " + value.length + ")"); - if (size > key.length) - throw new IllegalArgumentException("The provided size (" + size - + ") is larger than or equal to the backing-arrays size (" - + key.length + ")"); - } - - private final class EntrySet - extends - AbstractObjectSet - implements Int2BooleanMap.FastEntrySet { - - @Override - public ObjectIterator iterator() { - return new AbstractObjectIterator() { - int curr = -1, next = 0; - - public boolean hasNext() { - return next < size; - } - - public Int2BooleanMap.Entry next() { - if (!hasNext()) - throw new NoSuchElementException(); - return new AbstractInt2BooleanMap.BasicEntry( - key[curr = next], value[next++]); - } - - public void remove() { - if (curr == -1) - throw new IllegalStateException(); - curr = -1; - final int tail = size-- - next--; - System.arraycopy(key, next + 1, key, next, tail); - System.arraycopy(value, next + 1, value, next, tail); - - } - }; - } - - public ObjectIterator fastIterator() { - return new AbstractObjectIterator() { - int next = 0, curr = -1; - final BasicEntry entry = new BasicEntry((0), (false)); - - public boolean hasNext() { - return next < size; - } - - public Int2BooleanMap.Entry next() { - if (!hasNext()) - throw new NoSuchElementException(); - entry.key = key[curr = next]; - entry.value = value[next++]; - return entry; - } - - public void remove() { - if (curr == -1) - throw new IllegalStateException(); - curr = -1; - final int tail = size-- - next--; - System.arraycopy(key, next + 1, key, next, tail); - System.arraycopy(value, next + 1, value, next, tail); - - } - }; - } - - public int size() { - return size; - } - - public boolean contains(Object o) { - if (!(o instanceof Map.Entry)) - return false; - final Map.Entry e = (Map.Entry) o; - - if (e.getKey() == null || !(e.getKey() instanceof Integer)) - return false; - - if (e.getValue() == null || !(e.getValue() instanceof Boolean)) - return false; - - final int k = ((((Integer) (e.getKey())).intValue())); - return it.unimi.dsi.fastutil.ints.Int2BooleanArrayMap.this.containsKey(k) - && ((it.unimi.dsi.fastutil.ints.Int2BooleanArrayMap.this.get(k)) == (((((Boolean) (e - .getValue())).booleanValue())))); - } - - @Override - public boolean remove(final Object o) { - if (!(o instanceof Map.Entry)) - return false; - final Map.Entry e = (Map.Entry) o; - - if (e.getKey() == null || !(e.getKey() instanceof Integer)) - return false; - - if (e.getValue() == null || !(e.getValue() instanceof Boolean)) - return false; - - final int k = ((((Integer) (e.getKey())).intValue())); - final boolean v = ((((Boolean) (e.getValue())).booleanValue())); - - final int oldPos = it.unimi.dsi.fastutil.ints.Int2BooleanArrayMap.this.findKey(k); - if (oldPos == -1 - || !((v) == (it.unimi.dsi.fastutil.ints.Int2BooleanArrayMap.this.value[oldPos]))) - return false; - final int tail = size - oldPos - 1; - System.arraycopy( - it.unimi.dsi.fastutil.ints.Int2BooleanArrayMap.this.key, oldPos + 1, - it.unimi.dsi.fastutil.ints.Int2BooleanArrayMap.this.key, oldPos, tail); - System.arraycopy( - it.unimi.dsi.fastutil.ints.Int2BooleanArrayMap.this.value, oldPos + 1, - it.unimi.dsi.fastutil.ints.Int2BooleanArrayMap.this.value, oldPos, tail); - it.unimi.dsi.fastutil.ints.Int2BooleanArrayMap.this.size--; - - return true; - } - } - - public Int2BooleanMap.FastEntrySet int2BooleanEntrySet() { - return new EntrySet(); - } - - private int findKey(final int k) { - final int[] key = this.key; - for (int i = size; i-- != 0;) - if (((key[i]) == (k))) - return i; - return -1; - } - - public boolean get(final int k) { - - final int[] key = this.key; - for (int i = size; i-- != 0;) - if (((key[i]) == (k))) - return value[i]; - return defRetValue; - } - - public int size() { - return size; - } - - @Override - public void clear() { - size = 0; - } - - @Override - public boolean containsKey(final int k) { - return findKey(k) != -1; - } - - @Override - public boolean containsValue(boolean v) { - for (int i = size; i-- != 0;) - if (((value[i]) == (v))) - return true; - return false; - } - - @Override - public boolean isEmpty() { - return size == 0; - } - - @Override - public boolean put(int k, boolean v) { - final int oldKey = findKey(k); - if (oldKey != -1) { - final boolean oldValue = value[oldKey]; - value[oldKey] = v; - return oldValue; - } - if (size == key.length) { - final int[] newKey = new int[size == 0 ? 2 : size * 2]; - final boolean[] newValue = new boolean[size == 0 ? 2 : size * 2]; - for (int i = size; i-- != 0;) { - newKey[i] = key[i]; - newValue[i] = value[i]; - } - key = newKey; - value = newValue; - } - key[size] = k; - value[size] = v; - size++; - return defRetValue; - } - - @Override - public boolean remove(final int k) { - - final int oldPos = findKey(k); - if (oldPos == -1) - return defRetValue; - final boolean oldValue = value[oldPos]; - final int tail = size - oldPos - 1; - System.arraycopy(key, oldPos + 1, key, oldPos, tail); - System.arraycopy(value, oldPos + 1, value, oldPos, tail); - size--; - - return oldValue; - } - - @Override - public IntSet keySet() { - return new IntArraySet(key, size); - } - - @Override - public BooleanCollection values() { - return BooleanCollections - .unmodifiable(new BooleanArraySet(value, size)); - } - - /** - * Returns a deep copy of this map. - * - *

- * This method performs a deep copy of this hash map; the data stored in the - * map, however, is not cloned. Note that this makes a difference only for - * object keys. - * - * @return a deep copy of this map. - */ - - public it.unimi.dsi.fastutil.ints.Int2BooleanArrayMap clone() { - it.unimi.dsi.fastutil.ints.Int2BooleanArrayMap c; - try { - c = (it.unimi.dsi.fastutil.ints.Int2BooleanArrayMap) super.clone(); - } catch (CloneNotSupportedException cantHappen) { - throw new InternalError(); - } - c.key = key.clone(); - c.value = value.clone(); - return c; - } - - private void writeObject(java.io.ObjectOutputStream s) - throws java.io.IOException { - s.defaultWriteObject(); - for (int i = 0; i < size; i++) { - s.writeInt(key[i]); - s.writeBoolean(value[i]); - } - } - - private void readObject(java.io.ObjectInputStream s) - throws java.io.IOException, ClassNotFoundException { - s.defaultReadObject(); - key = new int[size]; - value = new boolean[size]; - for (int i = 0; i < size; i++) { - key[i] = s.readInt(); - value[i] = s.readBoolean(); - } - } -} diff --git a/src/main/java/it/unimi/dsi/fastutil/ints/Int2BooleanFunction.java b/src/main/java/it/unimi/dsi/fastutil/ints/Int2BooleanFunction.java deleted file mode 100644 index 90b630c..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/ints/Int2BooleanFunction.java +++ /dev/null @@ -1,151 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Primitive-type-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* Primitive-type-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.ints; - -import it.unimi.dsi.fastutil.Function; - -/** - * A type-specific {@link Function}; provides some additional methods that use - * polymorphism to avoid (un)boxing. - * - *

- * Type-specific versions of get(), put() and - * remove() cannot rely on null to denote absence of a - * key. Rather, they return a {@linkplain #defaultReturnValue() default return - * value}, which is set to 0 cast to the return type (false for - * booleans) at creation, but can be changed using the - * defaultReturnValue() method. - * - *

- * For uniformity reasons, even maps returning objects implement the default - * return value (of course, in this case the default return value is initialized - * to null). - * - *

- * Warning: to fall in line as much as possible with the - * {@linkplain java.util.Map standard map interface}, it is strongly suggested - * that standard versions of get(), put() and - * remove() for maps with primitive-type values return - * null to denote missing keys rather than wrap the default - * return value in an object (of course, for maps with object keys and values - * this is not possible, as there is no type-specific version). - * - * @see Function - */ - -public interface Int2BooleanFunction extends Function { - - /** - * Adds a pair to the map. - * - * @param key - * the key. - * @param value - * the value. - * @return the old value, or the {@linkplain #defaultReturnValue() default - * return value} if no value was present for the given key. - * @see Function#put(Object,Object) - */ - - boolean put(int key, boolean value); - - /** - * Returns the value to which the given key is mapped. - * - * @param key - * the key. - * @return the corresponding value, or the - * {@linkplain #defaultReturnValue() default return value} if no - * value was present for the given key. - * @see Function#get(Object) - */ - - boolean get(int key); - - /** - * Removes the mapping with the given key. - * - * @param key - * the key. - * @return the old value, or the {@linkplain #defaultReturnValue() default - * return value} if no value was present for the given key. - * @see Function#remove(Object) - */ - - boolean remove(int key); - - /** - * @see Function#containsKey(Object) - */ - - boolean containsKey(int key); - - /** - * Sets the default return value. - * - * This value must be returned by type-specific versions of - * get(), put() and remove() to - * denote that the map does not contain the specified key. It must be 0/ - * false/null by default. - * - * @param rv - * the new default return value. - * @see #defaultReturnValue() - */ - - void defaultReturnValue(boolean rv); - - /** - * Gets the default return value. - * - * @return the current default return value. - */ - - boolean defaultReturnValue(); - -} diff --git a/src/main/java/it/unimi/dsi/fastutil/ints/Int2BooleanMap.java b/src/main/java/it/unimi/dsi/fastutil/ints/Int2BooleanMap.java deleted file mode 100644 index 12f265e..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/ints/Int2BooleanMap.java +++ /dev/null @@ -1,211 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Primitive-type-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* Primitive-type-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.ints; - -import it.unimi.dsi.fastutil.booleans.BooleanCollection; -import it.unimi.dsi.fastutil.ints.Int2BooleanFunction; -import it.unimi.dsi.fastutil.ints.IntSet; -import it.unimi.dsi.fastutil.objects.ObjectIterator; -import it.unimi.dsi.fastutil.objects.ObjectSet; - -import java.util.Map; - -/** - * A type-specific {@link Map}; provides some additional methods that use - * polymorphism to avoid (un)boxing, and handling of a default return value. - * - *

- * Besides extending the corresponding type-specific - * {@linkplain it.unimi.dsi.fastutil.Function function}, this interface - * strengthens {@link #entrySet()}, {@link #keySet()} and {@link #values()}. - * Maps returning entry sets of type {@link FastEntrySet} support also fast - * iteration. - * - *

- * A submap or subset may or may not have an independent default return value - * (which however must be initialized to the default return value of the - * originator). - * - * @see Map - */ - -public interface Int2BooleanMap - extends - Int2BooleanFunction, - Map { - - /** - * An entry set providing fast iteration. - * - *

- * In some cases (e.g., hash-based classes) iteration over an entry set - * requires the creation of a large number of {@link Map.Entry} - * objects. Some fastutil maps might return - * {@linkplain #entrySet() entry set} objects of type - * FastEntrySet: in this case, {@link #fastIterator() - * fastIterator()} will return an iterator that is guaranteed not to create a - * large number of objects, possibly - * by returning always the same entry (of course, mutated). - */ - - public interface FastEntrySet extends ObjectSet { - /** - * Returns a fast iterator over this entry set; the iterator might - * return always the same entry object, suitably mutated. - * - * @return a fast iterator over this entry set; the iterator might - * return always the same {@link Map.Entry} object, - * suitably mutated. - */ - public ObjectIterator fastIterator(); - } - - /** - * Returns a set view of the mappings contained in this map. - *

- * Note that this specification strengthens the one given in - * {@link Map#entrySet()}. - * - * @return a set view of the mappings contained in this map. - * @see Map#entrySet() - */ - - ObjectSet> entrySet(); - - /** - * Returns a type-specific set view of the mappings contained in this map. - * - *

- * This method is necessary because there is no inheritance along type - * parameters: it is thus impossible to strengthen {@link #entrySet()} so - * that it returns an {@link it.unimi.dsi.fastutil.objects.ObjectSet} of - * type-specific entries (the latter makes it possible to access keys and - * values with type-specific methods). - * - * @return a type-specific set view of the mappings contained in this map. - * @see #entrySet() - */ - - ObjectSet int2BooleanEntrySet(); - - /** - * Returns a set view of the keys contained in this map. - *

- * Note that this specification strengthens the one given in - * {@link Map#keySet()}. - * - * @return a set view of the keys contained in this map. - * @see Map#keySet() - */ - - IntSet keySet(); - - /** - * Returns a set view of the values contained in this map. - *

- * Note that this specification strengthens the one given in - * {@link Map#values()}. - * - * @return a set view of the values contained in this map. - * @see Map#values() - */ - - BooleanCollection values(); - - /** - * @see Map#containsValue(Object) - */ - - boolean containsValue(boolean value); - - /** - * A type-specific {@link Map.Entry}; provides some additional - * methods that use polymorphism to avoid (un)boxing. - * - * @see Map.Entry - */ - - interface Entry extends Map.Entry { - - /** - * {@inheritDoc} - * - * @deprecated Please use the corresponding type-specific method - * instead. - */ - @Deprecated - @Override - Integer getKey(); - - /** - * @see Map.Entry#getKey() - */ - int getIntKey(); - - /** - * {@inheritDoc} - * - * @deprecated Please use the corresponding type-specific method - * instead. - */ - @Deprecated - @Override - Boolean getValue(); - - /** - * @see Map.Entry#setValue(Object) - */ - boolean setValue(boolean value); - - /** - * @see Map.Entry#getValue() - */ - boolean getBooleanValue(); - - } -} diff --git a/src/main/java/it/unimi/dsi/fastutil/ints/Int2IntFunction.java b/src/main/java/it/unimi/dsi/fastutil/ints/Int2IntFunction.java deleted file mode 100644 index 3434085..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/ints/Int2IntFunction.java +++ /dev/null @@ -1,151 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Primitive-type-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* Primitive-type-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.ints; - -import it.unimi.dsi.fastutil.Function; - -/** - * A type-specific {@link Function}; provides some additional methods that use - * polymorphism to avoid (un)boxing. - * - *

- * Type-specific versions of get(), put() and - * remove() cannot rely on null to denote absence of a - * key. Rather, they return a {@linkplain #defaultReturnValue() default return - * value}, which is set to 0 cast to the return type (false for - * booleans) at creation, but can be changed using the - * defaultReturnValue() method. - * - *

- * For uniformity reasons, even maps returning objects implement the default - * return value (of course, in this case the default return value is initialized - * to null). - * - *

- * Warning: to fall in line as much as possible with the - * {@linkplain java.util.Map standard map interface}, it is strongly suggested - * that standard versions of get(), put() and - * remove() for maps with primitive-type values return - * null to denote missing keys rather than wrap the default - * return value in an object (of course, for maps with object keys and values - * this is not possible, as there is no type-specific version). - * - * @see Function - */ - -public interface Int2IntFunction extends Function { - - /** - * Adds a pair to the map. - * - * @param key - * the key. - * @param value - * the value. - * @return the old value, or the {@linkplain #defaultReturnValue() default - * return value} if no value was present for the given key. - * @see Function#put(Object,Object) - */ - - int put(int key, int value); - - /** - * Returns the value to which the given key is mapped. - * - * @param key - * the key. - * @return the corresponding value, or the - * {@linkplain #defaultReturnValue() default return value} if no - * value was present for the given key. - * @see Function#get(Object) - */ - - int get(int key); - - /** - * Removes the mapping with the given key. - * - * @param key - * the key. - * @return the old value, or the {@linkplain #defaultReturnValue() default - * return value} if no value was present for the given key. - * @see Function#remove(Object) - */ - - int remove(int key); - - /** - * @see Function#containsKey(Object) - */ - - boolean containsKey(int key); - - /** - * Sets the default return value. - * - * This value must be returned by type-specific versions of - * get(), put() and remove() to - * denote that the map does not contain the specified key. It must be 0/ - * false/null by default. - * - * @param rv - * the new default return value. - * @see #defaultReturnValue() - */ - - void defaultReturnValue(int rv); - - /** - * Gets the default return value. - * - * @return the current default return value. - */ - - int defaultReturnValue(); - -} diff --git a/src/main/java/it/unimi/dsi/fastutil/ints/Int2IntMap.java b/src/main/java/it/unimi/dsi/fastutil/ints/Int2IntMap.java deleted file mode 100644 index 6dd4c89..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/ints/Int2IntMap.java +++ /dev/null @@ -1,208 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Primitive-type-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* Primitive-type-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.ints; - -import it.unimi.dsi.fastutil.ints.Int2IntFunction; -import it.unimi.dsi.fastutil.ints.IntCollection; -import it.unimi.dsi.fastutil.ints.IntSet; -import it.unimi.dsi.fastutil.objects.ObjectIterator; -import it.unimi.dsi.fastutil.objects.ObjectSet; - -import java.util.Map; - -/** - * A type-specific {@link Map}; provides some additional methods that use - * polymorphism to avoid (un)boxing, and handling of a default return value. - * - *

- * Besides extending the corresponding type-specific - * {@linkplain it.unimi.dsi.fastutil.Function function}, this interface - * strengthens {@link #entrySet()}, {@link #keySet()} and {@link #values()}. - * Maps returning entry sets of type {@link FastEntrySet} support also fast - * iteration. - * - *

- * A submap or subset may or may not have an independent default return value - * (which however must be initialized to the default return value of the - * originator). - * - * @see Map - */ - -public interface Int2IntMap extends Int2IntFunction, Map { - - /** - * An entry set providing fast iteration. - * - *

- * In some cases (e.g., hash-based classes) iteration over an entry set - * requires the creation of a large number of {@link Map.Entry} - * objects. Some fastutil maps might return - * {@linkplain #entrySet() entry set} objects of type - * FastEntrySet: in this case, {@link #fastIterator() - * fastIterator()} will return an iterator that is guaranteed not to create a - * large number of objects, possibly - * by returning always the same entry (of course, mutated). - */ - - public interface FastEntrySet extends ObjectSet { - /** - * Returns a fast iterator over this entry set; the iterator might - * return always the same entry object, suitably mutated. - * - * @return a fast iterator over this entry set; the iterator might - * return always the same {@link Map.Entry} object, - * suitably mutated. - */ - public ObjectIterator fastIterator(); - } - - /** - * Returns a set view of the mappings contained in this map. - *

- * Note that this specification strengthens the one given in - * {@link Map#entrySet()}. - * - * @return a set view of the mappings contained in this map. - * @see Map#entrySet() - */ - - ObjectSet> entrySet(); - - /** - * Returns a type-specific set view of the mappings contained in this map. - * - *

- * This method is necessary because there is no inheritance along type - * parameters: it is thus impossible to strengthen {@link #entrySet()} so - * that it returns an {@link it.unimi.dsi.fastutil.objects.ObjectSet} of - * type-specific entries (the latter makes it possible to access keys and - * values with type-specific methods). - * - * @return a type-specific set view of the mappings contained in this map. - * @see #entrySet() - */ - - ObjectSet int2IntEntrySet(); - - /** - * Returns a set view of the keys contained in this map. - *

- * Note that this specification strengthens the one given in - * {@link Map#keySet()}. - * - * @return a set view of the keys contained in this map. - * @see Map#keySet() - */ - - IntSet keySet(); - - /** - * Returns a set view of the values contained in this map. - *

- * Note that this specification strengthens the one given in - * {@link Map#values()}. - * - * @return a set view of the values contained in this map. - * @see Map#values() - */ - - IntCollection values(); - - /** - * @see Map#containsValue(Object) - */ - - boolean containsValue(int value); - - /** - * A type-specific {@link Map.Entry}; provides some additional - * methods that use polymorphism to avoid (un)boxing. - * - * @see Map.Entry - */ - - interface Entry extends Map.Entry { - - /** - * {@inheritDoc} - * - * @deprecated Please use the corresponding type-specific method - * instead. - */ - @Deprecated - @Override - Integer getKey(); - - /** - * @see Map.Entry#getKey() - */ - int getIntKey(); - - /** - * {@inheritDoc} - * - * @deprecated Please use the corresponding type-specific method - * instead. - */ - @Deprecated - @Override - Integer getValue(); - - /** - * @see Map.Entry#setValue(Object) - */ - int setValue(int value); - - /** - * @see Map.Entry#getValue() - */ - int getIntValue(); - - } -} diff --git a/src/main/java/it/unimi/dsi/fastutil/ints/Int2IntOpenHashMap.java b/src/main/java/it/unimi/dsi/fastutil/ints/Int2IntOpenHashMap.java deleted file mode 100644 index 4e45fff..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/ints/Int2IntOpenHashMap.java +++ /dev/null @@ -1,1366 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Primitive-type-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* Primitive-type-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.ints; - -import it.unimi.dsi.fastutil.Hash; -import it.unimi.dsi.fastutil.HashCommon; -import it.unimi.dsi.fastutil.ints.AbstractInt2IntMap; -import it.unimi.dsi.fastutil.ints.AbstractIntCollection; -import it.unimi.dsi.fastutil.ints.AbstractIntSet; -import it.unimi.dsi.fastutil.ints.Int2IntMap; -import it.unimi.dsi.fastutil.ints.IntArrayList; -import it.unimi.dsi.fastutil.ints.IntCollection; -import it.unimi.dsi.fastutil.ints.IntIterator; -import it.unimi.dsi.fastutil.ints.IntSet; -import it.unimi.dsi.fastutil.objects.AbstractObjectSet; -import it.unimi.dsi.fastutil.objects.ObjectIterator; - -import java.util.Arrays; -import java.util.Map; -import java.util.NoSuchElementException; - -import static it.unimi.dsi.fastutil.HashCommon.arraySize; -import static it.unimi.dsi.fastutil.HashCommon.maxFill; - -/** - * A type-specific hash map with a fast, small-footprint implementation. - * - *

- * Instances of this class use a hash table to represent a map. The table is - * filled up to a specified load factor, and then doubled in size to - * accommodate new entries. If the table is emptied below one fourth of - * the load factor, it is halved in size. However, halving is not performed when - * deleting entries from an iterator, as it would interfere with the iteration - * process. - * - *

- * Note that {@link #clear()} does not modify the hash table size. Rather, a - * family of {@linkplain #trim() trimming methods} lets you control the size of - * the table; this is particularly useful if you reuse instances of this class. - * - * @see Hash - * @see HashCommon - */ - -public class Int2IntOpenHashMap extends AbstractInt2IntMap - implements - java.io.Serializable, - Cloneable, - Hash { - - private static final long serialVersionUID = 0L; - private static final boolean ASSERTS = false; - - /** The array of keys. */ - protected transient int[] key; - - /** The array of values. */ - protected transient int[] value; - - /** The mask for wrapping a position counter. */ - protected transient int mask; - - /** Whether this set contains the key zero. */ - protected transient boolean containsNullKey; - /** The current table size. */ - protected transient int n; - - /** - * Threshold after which we rehash. It must be the table size times - * {@link #f}. - */ - protected transient int maxFill; - - /** Number of entries in the set (including the key zero, if present). */ - protected int size; - - /** The acceptable load factor. */ - protected final float f; - /** Cached set of entries. */ - protected transient FastEntrySet entries; - - /** Cached set of keys. */ - protected transient IntSet keys; - - /** Cached collection of values. */ - protected transient IntCollection values; - /** - * Creates a new hash map. - * - *

- * The actual table size will be the least power of two greater than - * expected/f. - * - * @param expected - * the expected number of elements in the hash set. - * @param f - * the load factor. - */ - - public Int2IntOpenHashMap(final int expected, final float f) { - - if (f <= 0 || f > 1) - throw new IllegalArgumentException( - "Load factor must be greater than 0 and smaller than or equal to 1"); - if (expected < 0) - throw new IllegalArgumentException( - "The expected number of elements must be nonnegative"); - - this.f = f; - - n = arraySize(expected, f); - mask = n - 1; - maxFill = maxFill(n, f); - key = new int[n + 1]; - value = new int[n + 1]; - - } - /** - * Creates a new hash map with {@link Hash#DEFAULT_LOAD_FACTOR} as load - * factor. - * - * @param expected - * the expected number of elements in the hash map. - */ - - public Int2IntOpenHashMap(final int expected) { - this(expected, DEFAULT_LOAD_FACTOR); - } - /** - * Creates a new hash map with initial expected - * {@link Hash#DEFAULT_INITIAL_SIZE} entries and - * {@link Hash#DEFAULT_LOAD_FACTOR} as load factor. - */ - - public Int2IntOpenHashMap() { - this(DEFAULT_INITIAL_SIZE, DEFAULT_LOAD_FACTOR); - } - /** - * Creates a new hash map copying a given one. - * - * @param m - * a {@link Map} to be copied into the new hash map. - * @param f - * the load factor. - */ - - public Int2IntOpenHashMap( - final Map m, final float f) { - this(m.size(), f); - putAll(m); - } - /** - * Creates a new hash map with {@link Hash#DEFAULT_LOAD_FACTOR} as load - * factor copying a given one. - * - * @param m - * a {@link Map} to be copied into the new hash map. - */ - - public Int2IntOpenHashMap(final Map m) { - this(m, DEFAULT_LOAD_FACTOR); - } - /** - * Creates a new hash map copying a given type-specific one. - * - * @param m - * a type-specific map to be copied into the new hash map. - * @param f - * the load factor. - */ - - public Int2IntOpenHashMap(final Int2IntMap m, final float f) { - this(m.size(), f); - putAll(m); - } - /** - * Creates a new hash map with {@link Hash#DEFAULT_LOAD_FACTOR} as load - * factor copying a given type-specific one. - * - * @param m - * a type-specific map to be copied into the new hash map. - */ - - public Int2IntOpenHashMap(final Int2IntMap m) { - this(m, DEFAULT_LOAD_FACTOR); - } - /** - * Creates a new hash map using the elements of two parallel arrays. - * - * @param k - * the array of keys of the new hash map. - * @param v - * the array of corresponding values in the new hash map. - * @param f - * the load factor. - * @throws IllegalArgumentException - * if k and v have different lengths. - */ - - public Int2IntOpenHashMap(final int[] k, final int[] v, final float f) { - this(k.length, f); - if (k.length != v.length) - throw new IllegalArgumentException( - "The key array and the value array have different lengths (" - + k.length + " and " + v.length + ")"); - for (int i = 0; i < k.length; i++) - this.put(k[i], v[i]); - } - /** - * Creates a new hash map with {@link Hash#DEFAULT_LOAD_FACTOR} as load - * factor using the elements of two parallel arrays. - * - * @param k - * the array of keys of the new hash map. - * @param v - * the array of corresponding values in the new hash map. - * @throws IllegalArgumentException - * if k and v have different lengths. - */ - - public Int2IntOpenHashMap(final int[] k, final int[] v) { - this(k, v, DEFAULT_LOAD_FACTOR); - } - private int realSize() { - return containsNullKey ? size - 1 : size; - } - - private void ensureCapacity(final int capacity) { - final int needed = arraySize(capacity, f); - if (needed > n) - rehash(needed); - } - - private void tryCapacity(final long capacity) { - final int needed = (int) Math.min( - 1 << 30, - Math.max(2, HashCommon.nextPowerOfTwo((long) Math.ceil(capacity - / f)))); - if (needed > n) - rehash(needed); - } - - private int removeEntry(final int pos) { - final int oldValue = value[pos]; - - size--; - - shiftKeys(pos); - if (size < maxFill / 4 && n > DEFAULT_INITIAL_SIZE) - rehash(n / 2); - return oldValue; - } - - private int removeNullEntry() { - containsNullKey = false; - - final int oldValue = value[n]; - - size--; - - if (size < maxFill / 4 && n > DEFAULT_INITIAL_SIZE) - rehash(n / 2); - return oldValue; - } - - /** {@inheritDoc} */ - public void putAll(Map m) { - if (f <= .5) - ensureCapacity(m.size()); // The resulting map will be sized for - // m.size() elements - else - tryCapacity(size() + m.size()); // The resulting map will be - // tentatively sized for size() + - // m.size() elements - super.putAll(m); - } - - private int insert(final int k, final int v) { - int pos; - - if (((k) == (0))) { - if (containsNullKey) - return n; - containsNullKey = true; - pos = n; - } else { - int curr; - final int[] key = this.key; - - // The starting point. - if (!((curr = key[pos = (it.unimi.dsi.fastutil.HashCommon.mix((k))) - & mask]) == (0))) { - if (((curr) == (k))) - return pos; - while (!((curr = key[pos = (pos + 1) & mask]) == (0))) - if (((curr) == (k))) - return pos; - } - } - - key[pos] = k; - value[pos] = v; - if (size++ >= maxFill) - rehash(arraySize(size + 1, f)); - if (ASSERTS) - checkTable(); - return -1; - } - - public int put(final int k, final int v) { - final int pos = insert(k, v); - if (pos < 0) - return defRetValue; - final int oldValue = value[pos]; - value[pos] = v; - return oldValue; - } - - /** - * {@inheritDoc} - * - * @deprecated Please use the corresponding type-specific method instead. - */ - @Deprecated - @Override - public Integer put(final Integer ok, final Integer ov) { - final int v = ((ov).intValue()); - - final int pos = insert(((ok).intValue()), v); - if (pos < 0) - return (null); - final int oldValue = value[pos]; - value[pos] = v; - return (Integer.valueOf(oldValue)); - } - - private int addToValue(final int pos, final int incr) { - final int oldValue = value[pos]; - - value[pos] = oldValue + incr; - - return oldValue; - } - - /** - * Adds an increment to value currently associated with a key. - * - *

- * Note that this method respects the {@linkplain #defaultReturnValue() - * default return value} semantics: when called with a key that does not - * currently appears in the map, the key will be associated with the default - * return value plus the given increment. - * - * @param k - * the key. - * @param incr - * the increment. - * @return the old value, or the {@linkplain #defaultReturnValue() default - * return value} if no value was present for the given key. - */ - public int addTo(final int k, final int incr) { - int pos; - - if (((k) == (0))) { - if (containsNullKey) - return addToValue(n, incr); - pos = n; - containsNullKey = true; - } else { - int curr; - final int[] key = this.key; - - // The starting point. - if (!((curr = key[pos = (it.unimi.dsi.fastutil.HashCommon.mix((k))) - & mask]) == (0))) { - if (((curr) == (k))) - return addToValue(pos, incr); - while (!((curr = key[pos = (pos + 1) & mask]) == (0))) - if (((curr) == (k))) - return addToValue(pos, incr); - } - } - - key[pos] = k; - - value[pos] = defRetValue + incr; - if (size++ >= maxFill) - rehash(arraySize(size + 1, f)); - if (ASSERTS) - checkTable(); - return defRetValue; - } - - /** - * Shifts left entries with the specified hash code, starting at the - * specified position, and empties the resulting free entry. - * - * @param pos - * a starting position. - */ - protected final void shiftKeys(int pos) { - // Shift entries with the same hash. - int last, slot; - int curr; - final int[] key = this.key; - - for (;;) { - pos = ((last = pos) + 1) & mask; - - for (;;) { - if (((curr = key[pos]) == (0))) { - key[last] = (0); - - return; - } - slot = (it.unimi.dsi.fastutil.HashCommon.mix((curr))) & mask; - if (last <= pos ? last >= slot || slot > pos : last >= slot - && slot > pos) - break; - pos = (pos + 1) & mask; - } - - key[last] = curr; - value[last] = value[pos]; - - } - } - - public int remove(final int k) { - if (((k) == (0))) { - if (containsNullKey) - return removeNullEntry(); - return defRetValue; - } - - int curr; - final int[] key = this.key; - int pos; - - // The starting point. - if (((curr = key[pos = (it.unimi.dsi.fastutil.HashCommon.mix((k))) - & mask]) == (0))) - return defRetValue; - if (((k) == (curr))) - return removeEntry(pos); - while (true) { - if (((curr = key[pos = (pos + 1) & mask]) == (0))) - return defRetValue; - if (((k) == (curr))) - return removeEntry(pos); - } - } - - /** - * {@inheritDoc} - * - * @deprecated Please use the corresponding type-specific method instead. - */ - @Deprecated - @Override - public Integer remove(final Object ok) { - final int k = ((((Integer) (ok)).intValue())); - if (((k) == (0))) { - if (containsNullKey) - return (Integer.valueOf(removeNullEntry())); - return (null); - } - - int curr; - final int[] key = this.key; - int pos; - - // The starting point. - if (((curr = key[pos = (it.unimi.dsi.fastutil.HashCommon.mix((k))) - & mask]) == (0))) - return (null); - if (((curr) == (k))) - return (Integer.valueOf(removeEntry(pos))); - while (true) { - if (((curr = key[pos = (pos + 1) & mask]) == (0))) - return (null); - if (((curr) == (k))) - return (Integer.valueOf(removeEntry(pos))); - } - } - /** @deprecated Please use the corresponding type-specific method instead. */ - @Deprecated - public Integer get(final Integer ok) { - if (ok == null) - return null; - final int k = ((ok).intValue()); - if (((k) == (0))) - return containsNullKey ? (Integer.valueOf(value[n])) : (null); - - int curr; - final int[] key = this.key; - int pos; - - // The starting point. - if (((curr = key[pos = (it.unimi.dsi.fastutil.HashCommon.mix((k))) - & mask]) == (0))) - return (null); - if (((k) == (curr))) - return (Integer.valueOf(value[pos])); - - // There's always an unused entry. - while (true) { - if (((curr = key[pos = (pos + 1) & mask]) == (0))) - return (null); - if (((k) == (curr))) - return (Integer.valueOf(value[pos])); - } - } - - public int get(final int k) { - if (((k) == (0))) - return containsNullKey ? value[n] : defRetValue; - - int curr; - final int[] key = this.key; - int pos; - - // The starting point. - if (((curr = key[pos = (it.unimi.dsi.fastutil.HashCommon.mix((k))) - & mask]) == (0))) - return defRetValue; - if (((k) == (curr))) - return value[pos]; - // There's always an unused entry. - while (true) { - if (((curr = key[pos = (pos + 1) & mask]) == (0))) - return defRetValue; - if (((k) == (curr))) - return value[pos]; - } - } - - public boolean containsKey(final int k) { - if (((k) == (0))) - return containsNullKey; - - int curr; - final int[] key = this.key; - int pos; - - // The starting point. - if (((curr = key[pos = (it.unimi.dsi.fastutil.HashCommon.mix((k))) - & mask]) == (0))) - return false; - if (((k) == (curr))) - return true; - // There's always an unused entry. - while (true) { - if (((curr = key[pos = (pos + 1) & mask]) == (0))) - return false; - if (((k) == (curr))) - return true; - } - } - - public boolean containsValue(final int v) { - final int value[] = this.value; - final int key[] = this.key; - if (containsNullKey && ((value[n]) == (v))) - return true; - for (int i = n; i-- != 0;) - if (!((key[i]) == (0)) && ((value[i]) == (v))) - return true; - return false; - } - - /* - * Removes all elements from this map. - * - *

To increase object reuse, this method does not change the table size. - * If you want to reduce the table size, you must use {@link #trim()}. - */ - public void clear() { - if (size == 0) - return; - size = 0; - containsNullKey = false; - - Arrays.fill(key, (0)); - - } - - public int size() { - return size; - } - - public boolean isEmpty() { - return size == 0; - } - - /** - * A no-op for backward compatibility. - * - * @param growthFactor - * unused. - * @deprecated Since fastutil 6.1.0, hash tables are doubled - * when they are too full. - */ - @Deprecated - public void growthFactor(int growthFactor) { - } - - /** - * Gets the growth factor (2). - * - * @return the growth factor of this set, which is fixed (2). - * @see #growthFactor(int) - * @deprecated Since fastutil 6.1.0, hash tables are doubled - * when they are too full. - */ - @Deprecated - public int growthFactor() { - return 16; - } - - /** - * The entry class for a hash map does not record key and value, but rather - * the position in the hash table of the corresponding entry. This is - * necessary so that calls to {@link Map.Entry#setValue(Object)} - * are reflected in the map - */ - - final class MapEntry - implements - Int2IntMap.Entry, - Map.Entry { - // The table index this entry refers to, or -1 if this entry has been - // deleted. - int index; - - MapEntry(final int index) { - this.index = index; - } - - MapEntry() { - } - - /** - * {@inheritDoc} - * - * @deprecated Please use the corresponding type-specific method - * instead. - */ - @Deprecated - public Integer getKey() { - return (Integer.valueOf(key[index])); - } - - public int getIntKey() { - return key[index]; - } - - /** - * {@inheritDoc} - * - * @deprecated Please use the corresponding type-specific method - * instead. - */ - @Deprecated - public Integer getValue() { - return (Integer.valueOf(value[index])); - } - - public int getIntValue() { - return value[index]; - } - - public int setValue(final int v) { - final int oldValue = value[index]; - value[index] = v; - return oldValue; - } - - public Integer setValue(final Integer v) { - return (Integer.valueOf(setValue(((v).intValue())))); - } - - @SuppressWarnings("unchecked") - public boolean equals(final Object o) { - if (!(o instanceof Map.Entry)) - return false; - Map.Entry e = (Map.Entry) o; - - return ((key[index]) == (((e.getKey()).intValue()))) - && ((value[index]) == (((e.getValue()).intValue()))); - } - - public int hashCode() { - return (key[index]) ^ (value[index]); - } - - public String toString() { - return key[index] + "=>" + value[index]; - } - } - /** An iterator over a hash map. */ - - private class MapIterator { - /** - * The index of the last entry returned, if positive or zero; initially, - * {@link #n}. If negative, the last entry returned was that of the key - * of index {@code - pos - 1} from the {@link #wrapped} list. - */ - int pos = n; - /** - * The index of the last entry that has been returned (more precisely, - * the value of {@link #pos} if {@link #pos} is positive, or - * {@link Integer#MIN_VALUE} if {@link #pos} is negative). It is -1 if - * either we did not return an entry yet, or the last returned entry has - * been removed. - */ - int last = -1; - /** - * A downward counter measuring how many entries must still be returned. - */ - int c = size; - /** - * A boolean telling us whether we should return the entry with the null - * key. - */ - boolean mustReturnNullKey = it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap.this.containsNullKey; - /** - * A lazily allocated list containing keys of entries that have wrapped - * around the table because of removals. - */ - IntArrayList wrapped; - - public boolean hasNext() { - return c != 0; - } - - public int nextEntry() { - if (!hasNext()) - throw new NoSuchElementException(); - - c--; - if (mustReturnNullKey) { - mustReturnNullKey = false; - return last = n; - } - - final int key[] = it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap.this.key; - - for (;;) { - if (--pos < 0) { - // We are just enumerating elements from the wrapped list. - last = Integer.MIN_VALUE; - final int k = wrapped.getInt(-pos - 1); - int p = (it.unimi.dsi.fastutil.HashCommon.mix((k))) & mask; - while (!((k) == (key[p]))) - p = (p + 1) & mask; - return p; - } - if (!((key[pos]) == (0))) - return last = pos; - } - } - - /** - * Shifts left entries with the specified hash code, starting at the - * specified position, and empties the resulting free entry. - * - * @param pos - * a starting position. - */ - private final void shiftKeys(int pos) { - // Shift entries with the same hash. - int last, slot; - int curr; - final int[] key = it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap.this.key; - - for (;;) { - pos = ((last = pos) + 1) & mask; - - for (;;) { - if (((curr = key[pos]) == (0))) { - key[last] = (0); - - return; - } - slot = (it.unimi.dsi.fastutil.HashCommon.mix((curr))) - & mask; - if (last <= pos ? last >= slot || slot > pos : last >= slot - && slot > pos) - break; - pos = (pos + 1) & mask; - } - - if (pos < last) { // Wrapped entry. - if (wrapped == null) - wrapped = new IntArrayList(2); - wrapped.add(key[pos]); - } - - key[last] = curr; - value[last] = value[pos]; - } - } - - public void remove() { - if (last == -1) - throw new IllegalStateException(); - if (last == n) { - containsNullKey = false; - - } else if (pos >= 0) - shiftKeys(last); - else { - // We're removing wrapped entries. - - it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap.this.remove(wrapped.getInt(-pos - 1)); - - last = -1; // Note that we must not decrement size - return; - } - - size--; - last = -1; // You can no longer remove this entry. - if (ASSERTS) - checkTable(); - } - - public int skip(final int n) { - int i = n; - while (i-- != 0 && hasNext()) - nextEntry(); - return n - i - 1; - } - } - - private class EntryIterator extends MapIterator - implements - ObjectIterator { - private MapEntry entry; - - public Int2IntMap.Entry next() { - return entry = new MapEntry(nextEntry()); - } - - @Override - public void remove() { - super.remove(); - entry.index = -1; // You cannot use a deleted entry. - } - } - - private class FastEntryIterator extends MapIterator - implements - ObjectIterator { - private final MapEntry entry = new MapEntry(); - public MapEntry next() { - entry.index = nextEntry(); - return entry; - } - } - private final class MapEntrySet extends AbstractObjectSet - implements - FastEntrySet { - - public ObjectIterator iterator() { - return new EntryIterator(); - } - - public ObjectIterator fastIterator() { - return new FastEntryIterator(); - } - - public boolean contains(final Object o) { - if (!(o instanceof Map.Entry)) - return false; - final Map.Entry e = (Map.Entry) o; - - if (e.getKey() == null || !(e.getKey() instanceof Integer)) - return false; - - if (e.getValue() == null || !(e.getValue() instanceof Integer)) - return false; - - final int k = ((((Integer) (e.getKey())).intValue())); - final int v = ((((Integer) (e.getValue())).intValue())); - - if (((k) == (0))) - return it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap.this.containsNullKey - && ((value[n]) == (v)); - - int curr; - final int[] key = it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap.this.key; - int pos; - - // The starting point. - if (((curr = key[pos = (it.unimi.dsi.fastutil.HashCommon.mix((k))) - & mask]) == (0))) - return false; - if (((k) == (curr))) - return ((value[pos]) == (v)); - // There's always an unused entry. - while (true) { - if (((curr = key[pos = (pos + 1) & mask]) == (0))) - return false; - if (((k) == (curr))) - return ((value[pos]) == (v)); - } - } - - public boolean remove(final Object o) { - if (!(o instanceof Map.Entry)) - return false; - final Map.Entry e = (Map.Entry) o; - - if (e.getKey() == null || !(e.getKey() instanceof Integer)) - return false; - - if (e.getValue() == null || !(e.getValue() instanceof Integer)) - return false; - - final int k = ((((Integer) (e.getKey())).intValue())); - final int v = ((((Integer) (e.getValue())).intValue())); - - if (((k) == (0))) { - if (containsNullKey && ((value[n]) == (v))) { - removeNullEntry(); - return true; - } - return false; - } - - int curr; - final int[] key = it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap.this.key; - int pos; - - // The starting point. - if (((curr = key[pos = (it.unimi.dsi.fastutil.HashCommon.mix((k))) - & mask]) == (0))) - return false; - if (((curr) == (k))) { - if (((value[pos]) == (v))) { - removeEntry(pos); - return true; - } - return false; - } - - while (true) { - if (((curr = key[pos = (pos + 1) & mask]) == (0))) - return false; - if (((curr) == (k))) { - if (((value[pos]) == (v))) { - removeEntry(pos); - return true; - } - } - } - } - - public int size() { - return size; - } - - public void clear() { - it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap.this.clear(); - } - } - - public FastEntrySet int2IntEntrySet() { - if (entries == null) - entries = new MapEntrySet(); - - return entries; - } - - /** - * An iterator on keys. - * - *

- * We simply override the {@link java.util.ListIterator#next()}/ - * {@link java.util.ListIterator#previous()} methods (and possibly their - * type-specific counterparts) so that they return keys instead of entries. - */ - private final class KeyIterator extends MapIterator implements IntIterator { - - public KeyIterator() { - super(); - } - public int nextInt() { - return key[nextEntry()]; - } - - public Integer next() { - return (Integer.valueOf(key[nextEntry()])); - } - - } - private final class KeySet extends AbstractIntSet { - - public IntIterator iterator() { - return new KeyIterator(); - } - - public int size() { - return size; - } - - public boolean contains(int k) { - return containsKey(k); - } - - public boolean remove(int k) { - final int oldSize = size; - it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap.this.remove(k); - return size != oldSize; - } - - public void clear() { - it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap.this.clear(); - } - } - - public IntSet keySet() { - - if (keys == null) - keys = new KeySet(); - return keys; - } - - /** - * An iterator on values. - * - *

- * We simply override the {@link java.util.ListIterator#next()}/ - * {@link java.util.ListIterator#previous()} methods (and possibly their - * type-specific counterparts) so that they return values instead of - * entries. - */ - private final class ValueIterator extends MapIterator - implements - IntIterator { - - public ValueIterator() { - super(); - } - public int nextInt() { - return value[nextEntry()]; - } - - /** - * {@inheritDoc} - * - * @deprecated Please use the corresponding type-specific method - * instead. - */ - @Deprecated - @Override - public Integer next() { - return (Integer.valueOf(value[nextEntry()])); - } - - } - - public IntCollection values() { - if (values == null) - values = new AbstractIntCollection() { - - public IntIterator iterator() { - return new ValueIterator(); - } - - public int size() { - return size; - } - - public boolean contains(int v) { - return containsValue(v); - } - - public void clear() { - it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap.this.clear(); - } - }; - - return values; - } - - /** - * A no-op for backward compatibility. The kind of tables implemented by - * this class never need rehashing. - * - *

- * If you need to reduce the table size to fit exactly this set, use - * {@link #trim()}. - * - * @return true. - * @see #trim() - * @deprecated A no-op. - */ - - @Deprecated - public boolean rehash() { - return true; - } - - /** - * Rehashes the map, making the table as small as possible. - * - *

- * This method rehashes the table to the smallest size satisfying the load - * factor. It can be used when the set will not be changed anymore, so to - * optimize access speed and size. - * - *

- * If the table size is already the minimum possible, this method does - * nothing. - * - * @return true if there was enough memory to trim the map. - * @see #trim(int) - */ - - public boolean trim() { - final int l = arraySize(size, f); - if (l >= n || size > maxFill(l, f)) - return true; - try { - rehash(l); - } catch (OutOfMemoryError cantDoIt) { - return false; - } - return true; - } - - /** - * Rehashes this map if the table is too large. - * - *

- * Let N be the smallest table size that can hold - * max(n,{@link #size()}) entries, still satisfying the load - * factor. If the current table size is smaller than or equal to - * N, this method does nothing. Otherwise, it rehashes this map - * in a table of size N. - * - *

- * This method is useful when reusing maps. {@linkplain #clear() Clearing a - * map} leaves the table size untouched. If you are reusing a map many times, - * you can call this method with a typical size to avoid keeping around a - * very large table just because of a few large transient maps. - * - * @param n - * the threshold for the trimming. - * @return true if there was enough memory to trim the map. - * @see #trim() - */ - - public boolean trim(final int n) { - final int l = HashCommon.nextPowerOfTwo((int) Math.ceil(n / f)); - if (l >= n || size > maxFill(l, f)) - return true; - try { - rehash(l); - } catch (OutOfMemoryError cantDoIt) { - return false; - } - return true; - } - - /** - * Rehashes the map. - * - *

- * This method implements the basic rehashing strategy, and may be overriden - * by subclasses implementing different rehashing strategies (e.g., - * disk-based rehashing). However, you should not override this method - * unless you understand the internal workings of this class. - * - * @param newN - * the new size - */ - - protected void rehash(final int newN) { - final int key[] = this.key; - final int value[] = this.value; - - final int mask = newN - 1; // Note that this is used by the hashing - // macro - final int newKey[] = new int[newN + 1]; - final int newValue[] = new int[newN + 1]; - int i = n, pos; - - for (int j = realSize(); j-- != 0;) { - while (((key[--i]) == (0))); - - if (!((newKey[pos = (it.unimi.dsi.fastutil.HashCommon.mix((key[i]))) - & mask]) == (0))) - while (!((newKey[pos = (pos + 1) & mask]) == (0))); - - newKey[pos] = key[i]; - newValue[pos] = value[i]; - } - - newValue[newN] = value[n]; - - n = newN; - this.mask = mask; - maxFill = maxFill(n, f); - this.key = newKey; - this.value = newValue; - } - - /** - * Returns a deep copy of this map. - * - *

- * This method performs a deep copy of this hash map; the data stored in the - * map, however, is not cloned. Note that this makes a difference only for - * object keys. - * - * @return a deep copy of this map. - */ - - public it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap clone() { - it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap c; - try { - c = (it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap) super.clone(); - } catch (CloneNotSupportedException cantHappen) { - throw new InternalError(); - } - - c.keys = null; - c.values = null; - c.entries = null; - c.containsNullKey = containsNullKey; - - c.key = key.clone(); - c.value = value.clone(); - - return c; - } - - /** - * Returns a hash code for this map. - * - * This method overrides the generic method provided by the superclass. - * Since equals() is not overriden, it is important that the - * value returned by this method is the same value as the one returned by - * the overriden method. - * - * @return a hash code for this map. - */ - - public int hashCode() { - int h = 0; - for (int j = realSize(), i = 0, t = 0; j-- != 0;) { - while (((key[i]) == (0))) - i++; - - t = (key[i]); - - t ^= (value[i]); - h += t; - i++; - } - // Zero / null keys have hash zero. - if (containsNullKey) - h += (value[n]); - return h; - } - - private void writeObject(java.io.ObjectOutputStream s) - throws java.io.IOException { - final int key[] = this.key; - final int value[] = this.value; - final MapIterator i = new MapIterator(); - - s.defaultWriteObject(); - - for (int j = size, e; j-- != 0;) { - e = i.nextEntry(); - s.writeInt(key[e]); - s.writeInt(value[e]); - } - } - - private void readObject(java.io.ObjectInputStream s) - throws java.io.IOException, ClassNotFoundException { - s.defaultReadObject(); - - n = arraySize(size, f); - maxFill = maxFill(n, f); - mask = n - 1; - - final int key[] = this.key = new int[n + 1]; - final int value[] = this.value = new int[n + 1]; - - int k; - int v; - - for (int i = size, pos; i-- != 0;) { - - k = s.readInt(); - v = s.readInt(); - - if (((k) == (0))) { - pos = n; - containsNullKey = true; - } else { - pos = (it.unimi.dsi.fastutil.HashCommon.mix((k))) & mask; - while (!((key[pos]) == (0))) - pos = (pos + 1) & mask; - } - - key[pos] = k; - value[pos] = v; - } - if (ASSERTS) - checkTable(); - } - private void checkTable() { - } -} diff --git a/src/main/java/it/unimi/dsi/fastutil/ints/Int2ObjectFunction.java b/src/main/java/it/unimi/dsi/fastutil/ints/Int2ObjectFunction.java deleted file mode 100644 index b71b8b8..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/ints/Int2ObjectFunction.java +++ /dev/null @@ -1,150 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Primitive-type-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.ints; - -import it.unimi.dsi.fastutil.Function; - -/** - * A type-specific {@link Function}; provides some additional methods that use - * polymorphism to avoid (un)boxing. - * - *

- * Type-specific versions of get(), put() and - * remove() cannot rely on null to denote absence of a - * key. Rather, they return a {@linkplain #defaultReturnValue() default return - * value}, which is set to 0 cast to the return type (false for - * booleans) at creation, but can be changed using the - * defaultReturnValue() method. - * - *

- * For uniformity reasons, even maps returning objects implement the default - * return value (of course, in this case the default return value is initialized - * to null). - * - *

- * Warning: to fall in line as much as possible with the - * {@linkplain java.util.Map standard map interface}, it is strongly suggested - * that standard versions of get(), put() and - * remove() for maps with primitive-type values return - * null to denote missing keys rather than wrap the default - * return value in an object (of course, for maps with object keys and values - * this is not possible, as there is no type-specific version). - * - * @see Function - */ - -public interface Int2ObjectFunction extends Function { - - /** - * Adds a pair to the map. - * - * @param key - * the key. - * @param value - * the value. - * @return the old value, or the {@linkplain #defaultReturnValue() default - * return value} if no value was present for the given key. - * @see Function#put(Object,Object) - */ - - V put(int key, V value); - - /** - * Returns the value to which the given key is mapped. - * - * @param key - * the key. - * @return the corresponding value, or the - * {@linkplain #defaultReturnValue() default return value} if no - * value was present for the given key. - * @see Function#get(Object) - */ - - V get(int key); - - /** - * Removes the mapping with the given key. - * - * @param key - * the key. - * @return the old value, or the {@linkplain #defaultReturnValue() default - * return value} if no value was present for the given key. - * @see Function#remove(Object) - */ - - V remove(int key); - - /** - * @see Function#containsKey(Object) - */ - - boolean containsKey(int key); - - /** - * Sets the default return value. - * - * This value must be returned by type-specific versions of - * get(), put() and remove() to - * denote that the map does not contain the specified key. It must be 0/ - * false/null by default. - * - * @param rv - * the new default return value. - * @see #defaultReturnValue() - */ - - void defaultReturnValue(V rv); - - /** - * Gets the default return value. - * - * @return the current default return value. - */ - - V defaultReturnValue(); - -} diff --git a/src/main/java/it/unimi/dsi/fastutil/ints/Int2ObjectMap.java b/src/main/java/it/unimi/dsi/fastutil/ints/Int2ObjectMap.java deleted file mode 100644 index 62c5c59..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/ints/Int2ObjectMap.java +++ /dev/null @@ -1,182 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Primitive-type-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.ints; - -import it.unimi.dsi.fastutil.ints.Int2ObjectFunction; -import it.unimi.dsi.fastutil.ints.IntSet; -import it.unimi.dsi.fastutil.objects.ObjectCollection; -import it.unimi.dsi.fastutil.objects.ObjectIterator; -import it.unimi.dsi.fastutil.objects.ObjectSet; - -import java.util.Map; - -/** - * A type-specific {@link Map}; provides some additional methods that use - * polymorphism to avoid (un)boxing, and handling of a default return value. - * - *

- * Besides extending the corresponding type-specific - * {@linkplain it.unimi.dsi.fastutil.Function function}, this interface - * strengthens {@link #entrySet()}, {@link #keySet()} and {@link #values()}. - * Maps returning entry sets of type {@link FastEntrySet} support also fast - * iteration. - * - *

- * A submap or subset may or may not have an independent default return value - * (which however must be initialized to the default return value of the - * originator). - * - * @see Map - */ - -public interface Int2ObjectMap - extends - Int2ObjectFunction, - Map { - - /** - * An entry set providing fast iteration. - * - *

- * In some cases (e.g., hash-based classes) iteration over an entry set - * requires the creation of a large number of {@link Map.Entry} - * objects. Some fastutil maps might return - * {@linkplain #entrySet() entry set} objects of type - * FastEntrySet: in this case, {@link #fastIterator() - * fastIterator()} will return an iterator that is guaranteed not to create a - * large number of objects, possibly - * by returning always the same entry (of course, mutated). - */ - - public interface FastEntrySet extends ObjectSet> { - /** - * Returns a fast iterator over this entry set; the iterator might - * return always the same entry object, suitably mutated. - * - * @return a fast iterator over this entry set; the iterator might - * return always the same {@link Map.Entry} object, - * suitably mutated. - */ - public ObjectIterator> fastIterator(); - } - - /** - * Returns a set view of the mappings contained in this map. - *

- * Note that this specification strengthens the one given in - * {@link Map#entrySet()}. - * - * @return a set view of the mappings contained in this map. - * @see Map#entrySet() - */ - - ObjectSet> entrySet(); - - /** - * Returns a type-specific set view of the mappings contained in this map. - * - *

- * This method is necessary because there is no inheritance along type - * parameters: it is thus impossible to strengthen {@link #entrySet()} so - * that it returns an {@link ObjectSet} of - * type-specific entries (the latter makes it possible to access keys and - * values with type-specific methods). - * - * @return a type-specific set view of the mappings contained in this map. - * @see #entrySet() - */ - - ObjectSet> int2ObjectEntrySet(); - - /** - * Returns a set view of the keys contained in this map. - *

- * Note that this specification strengthens the one given in - * {@link Map#keySet()}. - * - * @return a set view of the keys contained in this map. - * @see Map#keySet() - */ - - IntSet keySet(); - - /** - * Returns a set view of the values contained in this map. - *

- * Note that this specification strengthens the one given in - * {@link Map#values()}. - * - * @return a set view of the values contained in this map. - * @see Map#values() - */ - - ObjectCollection values(); - /** - * A type-specific {@link Map.Entry}; provides some additional - * methods that use polymorphism to avoid (un)boxing. - * - * @see Map.Entry - */ - - interface Entry extends Map.Entry { - - /** - * {@inheritDoc} - * - * @deprecated Please use the corresponding type-specific method - * instead. - */ - @Deprecated - @Override - Integer getKey(); - - /** - * @see Map.Entry#getKey() - */ - int getIntKey(); - } -} diff --git a/src/main/java/it/unimi/dsi/fastutil/ints/Int2ObjectOpenHashMap.java b/src/main/java/it/unimi/dsi/fastutil/ints/Int2ObjectOpenHashMap.java deleted file mode 100644 index 971443a..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/ints/Int2ObjectOpenHashMap.java +++ /dev/null @@ -1,1306 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Primitive-type-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.ints; - -import it.unimi.dsi.fastutil.Hash; -import it.unimi.dsi.fastutil.HashCommon; -import it.unimi.dsi.fastutil.ints.AbstractInt2ObjectMap; -import it.unimi.dsi.fastutil.ints.AbstractIntSet; -import it.unimi.dsi.fastutil.ints.Int2ObjectMap; -import it.unimi.dsi.fastutil.ints.IntArrayList; -import it.unimi.dsi.fastutil.ints.IntIterator; -import it.unimi.dsi.fastutil.ints.IntSet; -import it.unimi.dsi.fastutil.objects.AbstractObjectCollection; -import it.unimi.dsi.fastutil.objects.AbstractObjectSet; -import it.unimi.dsi.fastutil.objects.ObjectCollection; -import it.unimi.dsi.fastutil.objects.ObjectIterator; - -import java.util.Arrays; -import java.util.Map; -import java.util.NoSuchElementException; - -import static it.unimi.dsi.fastutil.HashCommon.arraySize; -import static it.unimi.dsi.fastutil.HashCommon.maxFill; - -/** - * A type-specific hash map with a fast, small-footprint implementation. - * - *

- * Instances of this class use a hash table to represent a map. The table is - * filled up to a specified load factor, and then doubled in size to - * accommodate new entries. If the table is emptied below one fourth of - * the load factor, it is halved in size. However, halving is not performed when - * deleting entries from an iterator, as it would interfere with the iteration - * process. - * - *

- * Note that {@link #clear()} does not modify the hash table size. Rather, a - * family of {@linkplain #trim() trimming methods} lets you control the size of - * the table; this is particularly useful if you reuse instances of this class. - * - * @see Hash - * @see HashCommon - */ - -public class Int2ObjectOpenHashMap extends AbstractInt2ObjectMap - implements - java.io.Serializable, - Cloneable, - Hash { - - private static final long serialVersionUID = 0L; - private static final boolean ASSERTS = false; - - /** The array of keys. */ - protected transient int[] key; - - /** The array of values. */ - protected transient V[] value; - - /** The mask for wrapping a position counter. */ - protected transient int mask; - - /** Whether this set contains the key zero. */ - protected transient boolean containsNullKey; - /** The current table size. */ - protected transient int n; - - /** - * Threshold after which we rehash. It must be the table size times - * {@link #f}. - */ - protected transient int maxFill; - - /** Number of entries in the set (including the key zero, if present). */ - protected int size; - - /** The acceptable load factor. */ - protected final float f; - /** Cached set of entries. */ - protected transient FastEntrySet entries; - - /** Cached set of keys. */ - protected transient IntSet keys; - - /** Cached collection of values. */ - protected transient ObjectCollection values; - /** - * Creates a new hash map. - * - *

- * The actual table size will be the least power of two greater than - * expected/f. - * - * @param expected - * the expected number of elements in the hash set. - * @param f - * the load factor. - */ - @SuppressWarnings("unchecked") - public Int2ObjectOpenHashMap(final int expected, final float f) { - - if (f <= 0 || f > 1) - throw new IllegalArgumentException( - "Load factor must be greater than 0 and smaller than or equal to 1"); - if (expected < 0) - throw new IllegalArgumentException( - "The expected number of elements must be nonnegative"); - - this.f = f; - - n = arraySize(expected, f); - mask = n - 1; - maxFill = maxFill(n, f); - key = new int[n + 1]; - value = (V[]) new Object[n + 1]; - - } - /** - * Creates a new hash map with {@link Hash#DEFAULT_LOAD_FACTOR} as load - * factor. - * - * @param expected - * the expected number of elements in the hash map. - */ - - public Int2ObjectOpenHashMap(final int expected) { - this(expected, DEFAULT_LOAD_FACTOR); - } - /** - * Creates a new hash map with initial expected - * {@link Hash#DEFAULT_INITIAL_SIZE} entries and - * {@link Hash#DEFAULT_LOAD_FACTOR} as load factor. - */ - - public Int2ObjectOpenHashMap() { - this(DEFAULT_INITIAL_SIZE, DEFAULT_LOAD_FACTOR); - } - /** - * Creates a new hash map copying a given one. - * - * @param m - * a {@link Map} to be copied into the new hash map. - * @param f - * the load factor. - */ - - public Int2ObjectOpenHashMap(final Map m, - final float f) { - this(m.size(), f); - putAll(m); - } - /** - * Creates a new hash map with {@link Hash#DEFAULT_LOAD_FACTOR} as load - * factor copying a given one. - * - * @param m - * a {@link Map} to be copied into the new hash map. - */ - - public Int2ObjectOpenHashMap(final Map m) { - this(m, DEFAULT_LOAD_FACTOR); - } - /** - * Creates a new hash map copying a given type-specific one. - * - * @param m - * a type-specific map to be copied into the new hash map. - * @param f - * the load factor. - */ - - public Int2ObjectOpenHashMap(final Int2ObjectMap m, final float f) { - this(m.size(), f); - putAll(m); - } - /** - * Creates a new hash map with {@link Hash#DEFAULT_LOAD_FACTOR} as load - * factor copying a given type-specific one. - * - * @param m - * a type-specific map to be copied into the new hash map. - */ - - public Int2ObjectOpenHashMap(final Int2ObjectMap m) { - this(m, DEFAULT_LOAD_FACTOR); - } - /** - * Creates a new hash map using the elements of two parallel arrays. - * - * @param k - * the array of keys of the new hash map. - * @param v - * the array of corresponding values in the new hash map. - * @param f - * the load factor. - * @throws IllegalArgumentException - * if k and v have different lengths. - */ - - public Int2ObjectOpenHashMap(final int[] k, final V[] v, final float f) { - this(k.length, f); - if (k.length != v.length) - throw new IllegalArgumentException( - "The key array and the value array have different lengths (" - + k.length + " and " + v.length + ")"); - for (int i = 0; i < k.length; i++) - this.put(k[i], v[i]); - } - /** - * Creates a new hash map with {@link Hash#DEFAULT_LOAD_FACTOR} as load - * factor using the elements of two parallel arrays. - * - * @param k - * the array of keys of the new hash map. - * @param v - * the array of corresponding values in the new hash map. - * @throws IllegalArgumentException - * if k and v have different lengths. - */ - - public Int2ObjectOpenHashMap(final int[] k, final V[] v) { - this(k, v, DEFAULT_LOAD_FACTOR); - } - private int realSize() { - return containsNullKey ? size - 1 : size; - } - - private void ensureCapacity(final int capacity) { - final int needed = arraySize(capacity, f); - if (needed > n) - rehash(needed); - } - - private void tryCapacity(final long capacity) { - final int needed = (int) Math.min( - 1 << 30, - Math.max(2, HashCommon.nextPowerOfTwo((long) Math.ceil(capacity - / f)))); - if (needed > n) - rehash(needed); - } - - private V removeEntry(final int pos) { - final V oldValue = value[pos]; - - value[pos] = null; - - size--; - - shiftKeys(pos); - if (size < maxFill / 4 && n > DEFAULT_INITIAL_SIZE) - rehash(n / 2); - return oldValue; - } - - private V removeNullEntry() { - containsNullKey = false; - - final V oldValue = value[n]; - - value[n] = null; - - size--; - - if (size < maxFill / 4 && n > DEFAULT_INITIAL_SIZE) - rehash(n / 2); - return oldValue; - } - - /** {@inheritDoc} */ - public void putAll(Map m) { - if (f <= .5) - ensureCapacity(m.size()); // The resulting map will be sized for - // m.size() elements - else - tryCapacity(size() + m.size()); // The resulting map will be - // tentatively sized for size() + - // m.size() elements - super.putAll(m); - } - - private int insert(final int k, final V v) { - int pos; - - if (((k) == (0))) { - if (containsNullKey) - return n; - containsNullKey = true; - pos = n; - } else { - int curr; - final int[] key = this.key; - - // The starting point. - if (!((curr = key[pos = (HashCommon.mix((k))) - & mask]) == (0))) { - if (((curr) == (k))) - return pos; - while (!((curr = key[pos = (pos + 1) & mask]) == (0))) - if (((curr) == (k))) - return pos; - } - } - - key[pos] = k; - value[pos] = v; - if (size++ >= maxFill) - rehash(arraySize(size + 1, f)); - if (ASSERTS) - checkTable(); - return -1; - } - - public V put(final int k, final V v) { - final int pos = insert(k, v); - if (pos < 0) - return defRetValue; - final V oldValue = value[pos]; - value[pos] = v; - return oldValue; - } - - /** - * {@inheritDoc} - * - * @deprecated Please use the corresponding type-specific method instead. - */ - @Deprecated - @Override - public V put(final Integer ok, final V ov) { - final V v = (ov); - - final int pos = insert(((ok).intValue()), v); - if (pos < 0) - return (this.defRetValue); - final V oldValue = value[pos]; - value[pos] = v; - return (oldValue); - } - /** - * Shifts left entries with the specified hash code, starting at the - * specified position, and empties the resulting free entry. - * - * @param pos - * a starting position. - */ - protected final void shiftKeys(int pos) { - // Shift entries with the same hash. - int last, slot; - int curr; - final int[] key = this.key; - - for (;;) { - pos = ((last = pos) + 1) & mask; - - for (;;) { - if (((curr = key[pos]) == (0))) { - key[last] = (0); - - value[last] = null; - - return; - } - slot = (HashCommon.mix((curr))) & mask; - if (last <= pos ? last >= slot || slot > pos : last >= slot - && slot > pos) - break; - pos = (pos + 1) & mask; - } - - key[last] = curr; - value[last] = value[pos]; - - } - } - - public V remove(final int k) { - if (((k) == (0))) { - if (containsNullKey) - return removeNullEntry(); - return defRetValue; - } - - int curr; - final int[] key = this.key; - int pos; - - // The starting point. - if (((curr = key[pos = (HashCommon.mix((k))) - & mask]) == (0))) - return defRetValue; - if (((k) == (curr))) - return removeEntry(pos); - while (true) { - if (((curr = key[pos = (pos + 1) & mask]) == (0))) - return defRetValue; - if (((k) == (curr))) - return removeEntry(pos); - } - } - - /** - * {@inheritDoc} - * - * @deprecated Please use the corresponding type-specific method instead. - */ - @Deprecated - @Override - public V remove(final Object ok) { - final int k = ((((Integer) (ok)).intValue())); - if (((k) == (0))) { - if (containsNullKey) - return (removeNullEntry()); - return (this.defRetValue); - } - - int curr; - final int[] key = this.key; - int pos; - - // The starting point. - if (((curr = key[pos = (HashCommon.mix((k))) - & mask]) == (0))) - return (this.defRetValue); - if (((curr) == (k))) - return (removeEntry(pos)); - while (true) { - if (((curr = key[pos = (pos + 1) & mask]) == (0))) - return (this.defRetValue); - if (((curr) == (k))) - return (removeEntry(pos)); - } - } - /** @deprecated Please use the corresponding type-specific method instead. */ - @Deprecated - public V get(final Integer ok) { - if (ok == null) - return null; - final int k = ((ok).intValue()); - if (((k) == (0))) - return containsNullKey ? (value[n]) : (this.defRetValue); - - int curr; - final int[] key = this.key; - int pos; - - // The starting point. - if (((curr = key[pos = (HashCommon.mix((k))) - & mask]) == (0))) - return (this.defRetValue); - if (((k) == (curr))) - return (value[pos]); - - // There's always an unused entry. - while (true) { - if (((curr = key[pos = (pos + 1) & mask]) == (0))) - return (this.defRetValue); - if (((k) == (curr))) - return (value[pos]); - } - } - - public V get(final int k) { - if (((k) == (0))) - return containsNullKey ? value[n] : defRetValue; - - int curr; - final int[] key = this.key; - int pos; - - // The starting point. - if (((curr = key[pos = (HashCommon.mix((k))) - & mask]) == (0))) - return defRetValue; - if (((k) == (curr))) - return value[pos]; - // There's always an unused entry. - while (true) { - if (((curr = key[pos = (pos + 1) & mask]) == (0))) - return defRetValue; - if (((k) == (curr))) - return value[pos]; - } - } - - public boolean containsKey(final int k) { - if (((k) == (0))) - return containsNullKey; - - int curr; - final int[] key = this.key; - int pos; - - // The starting point. - if (((curr = key[pos = (HashCommon.mix((k))) - & mask]) == (0))) - return false; - if (((k) == (curr))) - return true; - // There's always an unused entry. - while (true) { - if (((curr = key[pos = (pos + 1) & mask]) == (0))) - return false; - if (((k) == (curr))) - return true; - } - } - - public boolean containsValue(final Object v) { - final V value[] = this.value; - final int key[] = this.key; - if (containsNullKey - && ((value[n]) == null ? (v) == null : (value[n]).equals(v))) - return true; - for (int i = n; i-- != 0;) - if (!((key[i]) == (0)) - && ((value[i]) == null ? (v) == null : (value[i]).equals(v))) - return true; - return false; - } - - /* - * Removes all elements from this map. - * - *

To increase object reuse, this method does not change the table size. - * If you want to reduce the table size, you must use {@link #trim()}. - */ - public void clear() { - if (size == 0) - return; - size = 0; - containsNullKey = false; - - Arrays.fill(key, (0)); - - Arrays.fill(value, null); - - } - - public int size() { - return size; - } - - public boolean isEmpty() { - return size == 0; - } - - /** - * A no-op for backward compatibility. - * - * @param growthFactor - * unused. - * @deprecated Since fastutil 6.1.0, hash tables are doubled - * when they are too full. - */ - @Deprecated - public void growthFactor(int growthFactor) { - } - - /** - * Gets the growth factor (2). - * - * @return the growth factor of this set, which is fixed (2). - * @see #growthFactor(int) - * @deprecated Since fastutil 6.1.0, hash tables are doubled - * when they are too full. - */ - @Deprecated - public int growthFactor() { - return 16; - } - - /** - * The entry class for a hash map does not record key and value, but rather - * the position in the hash table of the corresponding entry. This is - * necessary so that calls to {@link Map.Entry#setValue(Object)} - * are reflected in the map - */ - - final class MapEntry - implements - Int2ObjectMap.Entry, - Map.Entry { - // The table index this entry refers to, or -1 if this entry has been - // deleted. - int index; - - MapEntry(final int index) { - this.index = index; - } - - MapEntry() { - } - - /** - * {@inheritDoc} - * - * @deprecated Please use the corresponding type-specific method - * instead. - */ - @Deprecated - public Integer getKey() { - return (Integer.valueOf(key[index])); - } - - public int getIntKey() { - return key[index]; - } - - public V getValue() { - return (value[index]); - } - - public V setValue(final V v) { - final V oldValue = value[index]; - value[index] = v; - return oldValue; - } - @SuppressWarnings("unchecked") - public boolean equals(final Object o) { - if (!(o instanceof Map.Entry)) - return false; - Map.Entry e = (Map.Entry) o; - - return ((key[index]) == (((e.getKey()).intValue()))) - && ((value[index]) == null - ? ((e.getValue())) == null - : (value[index]).equals((e.getValue()))); - } - - public int hashCode() { - return (key[index]) - ^ ((value[index]) == null ? 0 : (value[index]).hashCode()); - } - - public String toString() { - return key[index] + "=>" + value[index]; - } - } - /** An iterator over a hash map. */ - - private class MapIterator { - /** - * The index of the last entry returned, if positive or zero; initially, - * {@link #n}. If negative, the last entry returned was that of the key - * of index {@code - pos - 1} from the {@link #wrapped} list. - */ - int pos = n; - /** - * The index of the last entry that has been returned (more precisely, - * the value of {@link #pos} if {@link #pos} is positive, or - * {@link Integer#MIN_VALUE} if {@link #pos} is negative). It is -1 if - * either we did not return an entry yet, or the last returned entry has - * been removed. - */ - int last = -1; - /** - * A downward counter measuring how many entries must still be returned. - */ - int c = size; - /** - * A boolean telling us whether we should return the entry with the null - * key. - */ - boolean mustReturnNullKey = it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap.this.containsNullKey; - /** - * A lazily allocated list containing keys of entries that have wrapped - * around the table because of removals. - */ - IntArrayList wrapped; - - public boolean hasNext() { - return c != 0; - } - - public int nextEntry() { - if (!hasNext()) - throw new NoSuchElementException(); - - c--; - if (mustReturnNullKey) { - mustReturnNullKey = false; - return last = n; - } - - final int key[] = it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap.this.key; - - for (;;) { - if (--pos < 0) { - // We are just enumerating elements from the wrapped list. - last = Integer.MIN_VALUE; - final int k = wrapped.getInt(-pos - 1); - int p = (HashCommon.mix((k))) & mask; - while (!((k) == (key[p]))) - p = (p + 1) & mask; - return p; - } - if (!((key[pos]) == (0))) - return last = pos; - } - } - - /** - * Shifts left entries with the specified hash code, starting at the - * specified position, and empties the resulting free entry. - * - * @param pos - * a starting position. - */ - private final void shiftKeys(int pos) { - // Shift entries with the same hash. - int last, slot; - int curr; - final int[] key = it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap.this.key; - - for (;;) { - pos = ((last = pos) + 1) & mask; - - for (;;) { - if (((curr = key[pos]) == (0))) { - key[last] = (0); - - value[last] = null; - - return; - } - slot = (HashCommon.mix((curr))) - & mask; - if (last <= pos ? last >= slot || slot > pos : last >= slot - && slot > pos) - break; - pos = (pos + 1) & mask; - } - - if (pos < last) { // Wrapped entry. - if (wrapped == null) - wrapped = new IntArrayList(2); - wrapped.add(key[pos]); - } - - key[last] = curr; - value[last] = value[pos]; - } - } - - public void remove() { - if (last == -1) - throw new IllegalStateException(); - if (last == n) { - containsNullKey = false; - - value[n] = null; - - } else if (pos >= 0) - shiftKeys(last); - else { - // We're removing wrapped entries. - - it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap.this.remove(wrapped.getInt(-pos - 1)); - - last = -1; // Note that we must not decrement size - return; - } - - size--; - last = -1; // You can no longer remove this entry. - if (ASSERTS) - checkTable(); - } - - public int skip(final int n) { - int i = n; - while (i-- != 0 && hasNext()) - nextEntry(); - return n - i - 1; - } - } - - private class EntryIterator extends MapIterator - implements - ObjectIterator> { - private MapEntry entry; - - public Int2ObjectMap.Entry next() { - return entry = new MapEntry(nextEntry()); - } - - @Override - public void remove() { - super.remove(); - entry.index = -1; // You cannot use a deleted entry. - } - } - - private class FastEntryIterator extends MapIterator - implements - ObjectIterator> { - private final MapEntry entry = new MapEntry(); - public MapEntry next() { - entry.index = nextEntry(); - return entry; - } - } - private final class MapEntrySet - extends - AbstractObjectSet> - implements - FastEntrySet { - - public ObjectIterator> iterator() { - return new EntryIterator(); - } - - public ObjectIterator> fastIterator() { - return new FastEntryIterator(); - } - - @SuppressWarnings("unchecked") - public boolean contains(final Object o) { - if (!(o instanceof Map.Entry)) - return false; - final Map.Entry e = (Map.Entry) o; - - if (e.getKey() == null || !(e.getKey() instanceof Integer)) - return false; - - final int k = ((((Integer) (e.getKey())).intValue())); - final V v = ((V) e.getValue()); - - if (((k) == (0))) - return it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap.this.containsNullKey - && ((value[n]) == null ? (v) == null : (value[n]) - .equals(v)); - - int curr; - final int[] key = it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap.this.key; - int pos; - - // The starting point. - if (((curr = key[pos = (HashCommon.mix((k))) - & mask]) == (0))) - return false; - if (((k) == (curr))) - return ((value[pos]) == null ? (v) == null : (value[pos]) - .equals(v)); - // There's always an unused entry. - while (true) { - if (((curr = key[pos = (pos + 1) & mask]) == (0))) - return false; - if (((k) == (curr))) - return ((value[pos]) == null ? (v) == null : (value[pos]) - .equals(v)); - } - } - - @SuppressWarnings("unchecked") - public boolean remove(final Object o) { - if (!(o instanceof Map.Entry)) - return false; - final Map.Entry e = (Map.Entry) o; - - if (e.getKey() == null || !(e.getKey() instanceof Integer)) - return false; - - final int k = ((((Integer) (e.getKey())).intValue())); - final V v = ((V) e.getValue()); - - if (((k) == (0))) { - if (containsNullKey - && ((value[n]) == null ? (v) == null : (value[n]) - .equals(v))) { - removeNullEntry(); - return true; - } - return false; - } - - int curr; - final int[] key = it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap.this.key; - int pos; - - // The starting point. - if (((curr = key[pos = (HashCommon.mix((k))) - & mask]) == (0))) - return false; - if (((curr) == (k))) { - if (((value[pos]) == null ? (v) == null : (value[pos]) - .equals(v))) { - removeEntry(pos); - return true; - } - return false; - } - - while (true) { - if (((curr = key[pos = (pos + 1) & mask]) == (0))) - return false; - if (((curr) == (k))) { - if (((value[pos]) == null ? (v) == null : (value[pos]) - .equals(v))) { - removeEntry(pos); - return true; - } - } - } - } - - public int size() { - return size; - } - - public void clear() { - it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap.this.clear(); - } - } - - public FastEntrySet int2ObjectEntrySet() { - if (entries == null) - entries = new MapEntrySet(); - - return entries; - } - - /** - * An iterator on keys. - * - *

- * We simply override the {@link java.util.ListIterator#next()}/ - * {@link java.util.ListIterator#previous()} methods (and possibly their - * type-specific counterparts) so that they return keys instead of entries. - */ - private final class KeyIterator extends MapIterator implements IntIterator { - - public KeyIterator() { - super(); - } - public int nextInt() { - return key[nextEntry()]; - } - - public Integer next() { - return (Integer.valueOf(key[nextEntry()])); - } - - } - private final class KeySet extends AbstractIntSet { - - public IntIterator iterator() { - return new KeyIterator(); - } - - public int size() { - return size; - } - - public boolean contains(int k) { - return containsKey(k); - } - - public boolean remove(int k) { - final int oldSize = size; - it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap.this.remove(k); - return size != oldSize; - } - - public void clear() { - it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap.this.clear(); - } - } - - public IntSet keySet() { - - if (keys == null) - keys = new KeySet(); - return keys; - } - - /** - * An iterator on values. - * - *

- * We simply override the {@link java.util.ListIterator#next()}/ - * {@link java.util.ListIterator#previous()} methods (and possibly their - * type-specific counterparts) so that they return values instead of - * entries. - */ - private final class ValueIterator extends MapIterator - implements - ObjectIterator { - - public ValueIterator() { - super(); - } - public V next() { - return value[nextEntry()]; - } - - } - - public ObjectCollection values() { - if (values == null) - values = new AbstractObjectCollection() { - - public ObjectIterator iterator() { - return new ValueIterator(); - } - - public int size() { - return size; - } - - public boolean contains(Object v) { - return containsValue(v); - } - - public void clear() { - it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap.this.clear(); - } - }; - - return values; - } - - /** - * A no-op for backward compatibility. The kind of tables implemented by - * this class never need rehashing. - * - *

- * If you need to reduce the table size to fit exactly this set, use - * {@link #trim()}. - * - * @return true. - * @see #trim() - * @deprecated A no-op. - */ - - @Deprecated - public boolean rehash() { - return true; - } - - /** - * Rehashes the map, making the table as small as possible. - * - *

- * This method rehashes the table to the smallest size satisfying the load - * factor. It can be used when the set will not be changed anymore, so to - * optimize access speed and size. - * - *

- * If the table size is already the minimum possible, this method does - * nothing. - * - * @return true if there was enough memory to trim the map. - * @see #trim(int) - */ - - public boolean trim() { - final int l = arraySize(size, f); - if (l >= n || size > maxFill(l, f)) - return true; - try { - rehash(l); - } catch (OutOfMemoryError cantDoIt) { - return false; - } - return true; - } - - /** - * Rehashes this map if the table is too large. - * - *

- * Let N be the smallest table size that can hold - * max(n,{@link #size()}) entries, still satisfying the load - * factor. If the current table size is smaller than or equal to - * N, this method does nothing. Otherwise, it rehashes this map - * in a table of size N. - * - *

- * This method is useful when reusing maps. {@linkplain #clear() Clearing a - * map} leaves the table size untouched. If you are reusing a map many times, - * you can call this method with a typical size to avoid keeping around a - * very large table just because of a few large transient maps. - * - * @param n - * the threshold for the trimming. - * @return true if there was enough memory to trim the map. - * @see #trim() - */ - - public boolean trim(final int n) { - final int l = HashCommon.nextPowerOfTwo((int) Math.ceil(n / f)); - if (l >= n || size > maxFill(l, f)) - return true; - try { - rehash(l); - } catch (OutOfMemoryError cantDoIt) { - return false; - } - return true; - } - - /** - * Rehashes the map. - * - *

- * This method implements the basic rehashing strategy, and may be overriden - * by subclasses implementing different rehashing strategies (e.g., - * disk-based rehashing). However, you should not override this method - * unless you understand the internal workings of this class. - * - * @param newN - * the new size - */ - - @SuppressWarnings("unchecked") - protected void rehash(final int newN) { - final int key[] = this.key; - final V value[] = this.value; - - final int mask = newN - 1; // Note that this is used by the hashing - // macro - final int newKey[] = new int[newN + 1]; - final V newValue[] = (V[]) new Object[newN + 1]; - int i = n, pos; - - for (int j = realSize(); j-- != 0;) { - while (((key[--i]) == (0))); - - if (!((newKey[pos = (HashCommon.mix((key[i]))) - & mask]) == (0))) - while (!((newKey[pos = (pos + 1) & mask]) == (0))); - - newKey[pos] = key[i]; - newValue[pos] = value[i]; - } - - newValue[newN] = value[n]; - - n = newN; - this.mask = mask; - maxFill = maxFill(n, f); - this.key = newKey; - this.value = newValue; - } - - /** - * Returns a deep copy of this map. - * - *

- * This method performs a deep copy of this hash map; the data stored in the - * map, however, is not cloned. Note that this makes a difference only for - * object keys. - * - * @return a deep copy of this map. - */ - - @SuppressWarnings("unchecked") - public it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap clone() { - it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap c; - try { - c = (it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap) super.clone(); - } catch (CloneNotSupportedException cantHappen) { - throw new InternalError(); - } - - c.keys = null; - c.values = null; - c.entries = null; - c.containsNullKey = containsNullKey; - - c.key = key.clone(); - c.value = value.clone(); - - return c; - } - - /** - * Returns a hash code for this map. - * - * This method overrides the generic method provided by the superclass. - * Since equals() is not overriden, it is important that the - * value returned by this method is the same value as the one returned by - * the overriden method. - * - * @return a hash code for this map. - */ - - public int hashCode() { - int h = 0; - for (int j = realSize(), i = 0, t = 0; j-- != 0;) { - while (((key[i]) == (0))) - i++; - - t = (key[i]); - - if (this != value[i]) - - t ^= ((value[i]) == null ? 0 : (value[i]).hashCode()); - h += t; - i++; - } - // Zero / null keys have hash zero. - if (containsNullKey) - h += ((value[n]) == null ? 0 : (value[n]).hashCode()); - return h; - } - - private void writeObject(java.io.ObjectOutputStream s) - throws java.io.IOException { - final int key[] = this.key; - final V value[] = this.value; - final MapIterator i = new MapIterator(); - - s.defaultWriteObject(); - - for (int j = size, e; j-- != 0;) { - e = i.nextEntry(); - s.writeInt(key[e]); - s.writeObject(value[e]); - } - } - - @SuppressWarnings("unchecked") - private void readObject(java.io.ObjectInputStream s) - throws java.io.IOException, ClassNotFoundException { - s.defaultReadObject(); - - n = arraySize(size, f); - maxFill = maxFill(n, f); - mask = n - 1; - - final int key[] = this.key = new int[n + 1]; - final V value[] = this.value = (V[]) new Object[n + 1]; - - int k; - V v; - - for (int i = size, pos; i-- != 0;) { - - k = s.readInt(); - v = (V) s.readObject(); - - if (((k) == (0))) { - pos = n; - containsNullKey = true; - } else { - pos = (HashCommon.mix((k))) & mask; - while (!((key[pos]) == (0))) - pos = (pos + 1) & mask; - } - - key[pos] = k; - value[pos] = v; - } - if (ASSERTS) - checkTable(); - } - private void checkTable() { - } -} diff --git a/src/main/java/it/unimi/dsi/fastutil/ints/IntArrayList.java b/src/main/java/it/unimi/dsi/fastutil/ints/IntArrayList.java deleted file mode 100644 index 493f334..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/ints/IntArrayList.java +++ /dev/null @@ -1,714 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Primitive-type-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.ints; - -import it.unimi.dsi.fastutil.ints.AbstractIntList; -import it.unimi.dsi.fastutil.ints.AbstractIntListIterator; -import it.unimi.dsi.fastutil.ints.IntArrays; -import it.unimi.dsi.fastutil.ints.IntCollection; -import it.unimi.dsi.fastutil.ints.IntIterator; -import it.unimi.dsi.fastutil.ints.IntIterators; -import it.unimi.dsi.fastutil.ints.IntList; -import it.unimi.dsi.fastutil.ints.IntListIterator; - -import java.util.Arrays; -import java.util.Collection; -import java.util.Iterator; -import java.util.NoSuchElementException; -import java.util.RandomAccess; - -/** - * A type-specific array-based list; provides some additional methods that use - * polymorphism to avoid (un)boxing. - * - *

- * This class implements a lightweight, fast, open, optimized, reuse-oriented - * version of array-based lists. Instances of this class represent a list with - * an array that is enlarged as needed when new entries are created (by doubling - * its current length), but is never made smaller (even on a - * {@link #clear()}). A family of {@linkplain #trim() trimming methods} lets you - * control the size of the backing array; this is particularly useful if you - * reuse instances of this class. Range checks are equivalent to those of - * {@link java.util}'s classes, but they are delayed as much as possible. The - * backing array is exposed by the {@link #elements()} method. - * - *

- * This class implements the bulk methods removeElements(), - * addElements() and getElements() using - * high-performance system calls (e.g., - * {@link System#arraycopy(Object,int,Object,int,int) System.arraycopy()} instead - * of expensive loops. - * - * @see java.util.ArrayList - */ - -public class IntArrayList extends AbstractIntList - implements - RandomAccess, - Cloneable, - java.io.Serializable { - private static final long serialVersionUID = -7046029254386353130L; - /** The initial default capacity of an array list. */ - public final static int DEFAULT_INITIAL_CAPACITY = 16; - - /** The backing array. */ - protected transient int a[]; - - /** - * The current actual size of the list (never greater than the backing-array - * length). - */ - protected int size; - - private static final boolean ASSERTS = false; - - /** - * Creates a new array list using a given array. - * - *

- * This constructor is only meant to be used by the wrapping methods. - * - * @param a - * the array that will be used to back this array list. - */ - - @SuppressWarnings("unused") - protected IntArrayList(final int a[], boolean dummy) { - this.a = a; - - } - - /** - * Creates a new array list with given capacity. - * - * @param capacity - * the initial capacity of the array list (may be 0). - */ - - public IntArrayList(final int capacity) { - if (capacity < 0) - throw new IllegalArgumentException("Initial capacity (" + capacity - + ") is negative"); - - a = new int[capacity]; - - } - - /** - * Creates a new array list with {@link #DEFAULT_INITIAL_CAPACITY} capacity. - */ - - public IntArrayList() { - this(DEFAULT_INITIAL_CAPACITY); - } - - /** - * Creates a new array list and fills it with a given collection. - * - * @param c - * a collection that will be used to fill the array list. - */ - - public IntArrayList(final Collection c) { - this(c.size()); - - size = IntIterators.unwrap(IntIterators.asIntIterator(c.iterator()), a); - - } - - /** - * Creates a new array list and fills it with a given type-specific - * collection. - * - * @param c - * a type-specific collection that will be used to fill the array - * list. - */ - - public IntArrayList(final IntCollection c) { - this(c.size()); - size = IntIterators.unwrap(c.iterator(), a); - } - - /** - * Creates a new array list and fills it with a given type-specific list. - * - * @param l - * a type-specific list that will be used to fill the array list. - */ - - public IntArrayList(final IntList l) { - this(l.size()); - l.getElements(0, a, 0, size = l.size()); - } - - /** - * Creates a new array list and fills it with the elements of a given array. - * - * @param a - * an array whose elements will be used to fill the array list. - */ - - public IntArrayList(final int a[]) { - this(a, 0, a.length); - } - - /** - * Creates a new array list and fills it with the elements of a given array. - * - * @param a - * an array whose elements will be used to fill the array list. - * @param offset - * the first element to use. - * @param length - * the number of elements to use. - */ - - public IntArrayList(final int a[], final int offset, final int length) { - this(length); - System.arraycopy(a, offset, this.a, 0, length); - size = length; - } - - /** - * Creates a new array list and fills it with the elements returned by an - * iterator.. - * - * @param i - * an iterator whose returned elements will fill the array list. - */ - - public IntArrayList(final Iterator i) { - this(); - while (i.hasNext()) - this.add(i.next()); - } - - /** - * Creates a new array list and fills it with the elements returned by a - * type-specific iterator.. - * - * @param i - * a type-specific iterator whose returned elements will fill the - * array list. - */ - - public IntArrayList(final IntIterator i) { - this(); - while (i.hasNext()) - this.add(i.nextInt()); - } - - /** - * Returns the backing array of this list. - * - * @return the backing array. - */ - - public int[] elements() { - return a; - } - /** - * Wraps a given array into an array list of given size. - * - *

- * Note it is guaranteed that the type of the array returned by - * {@link #elements()} will be the same (see the comments in the class - * documentation). - * - * @param a - * an array to wrap. - * @param length - * the length of the resulting array list. - * @return a new array list of the given size, wrapping the given array. - */ - - public static it.unimi.dsi.fastutil.ints.IntArrayList wrap(final int a[], final int length) { - if (length > a.length) - throw new IllegalArgumentException("The specified length (" - + length + ") is greater than the array size (" + a.length - + ")"); - final it.unimi.dsi.fastutil.ints.IntArrayList l = new it.unimi.dsi.fastutil.ints.IntArrayList(a, false); - l.size = length; - return l; - } - - /** - * Wraps a given array into an array list. - * - *

- * Note it is guaranteed that the type of the array returned by - * {@link #elements()} will be the same (see the comments in the class - * documentation). - * - * @param a - * an array to wrap. - * @return a new array list wrapping the given array. - */ - - public static it.unimi.dsi.fastutil.ints.IntArrayList wrap(final int a[]) { - return wrap(a, a.length); - } - - /** - * Ensures that this array list can contain the given number of entries - * without resizing. - * - * @param capacity - * the new minimum capacity for this array list. - */ - - public void ensureCapacity(final int capacity) { - - a = IntArrays.ensureCapacity(a, capacity, size); - if (ASSERTS) - assert size <= a.length; - } - - /** - * Grows this array list, ensuring that it can contain the given number of - * entries without resizing, and in case enlarging it at least by a factor - * of two. - * - * @param capacity - * the new minimum capacity for this array list. - */ - - private void grow(final int capacity) { - - a = IntArrays.grow(a, capacity, size); - if (ASSERTS) - assert size <= a.length; - } - - public void add(final int index, final int k) { - ensureIndex(index); - grow(size + 1); - if (index != size) - System.arraycopy(a, index, a, index + 1, size - index); - a[index] = k; - size++; - if (ASSERTS) - assert size <= a.length; - } - - public boolean add(final int k) { - grow(size + 1); - a[size++] = k; - if (ASSERTS) - assert size <= a.length; - return true; - } - - public int getInt(final int index) { - if (index >= size) - throw new IndexOutOfBoundsException("Index (" + index - + ") is greater than or equal to list size (" + size + ")"); - return a[index]; - } - - public int indexOf(final int k) { - for (int i = 0; i < size; i++) - if (((k) == (a[i]))) - return i; - return -1; - } - - public int lastIndexOf(final int k) { - for (int i = size; i-- != 0;) - if (((k) == (a[i]))) - return i; - return -1; - } - - public int removeInt(final int index) { - if (index >= size) - throw new IndexOutOfBoundsException("Index (" + index - + ") is greater than or equal to list size (" + size + ")"); - final int old = a[index]; - size--; - if (index != size) - System.arraycopy(a, index + 1, a, index, size - index); - - if (ASSERTS) - assert size <= a.length; - return old; - } - - public boolean rem(final int k) { - int index = indexOf(k); - if (index == -1) - return false; - removeInt(index); - if (ASSERTS) - assert size <= a.length; - return true; - } - - public int set(final int index, final int k) { - if (index >= size) - throw new IndexOutOfBoundsException("Index (" + index - + ") is greater than or equal to list size (" + size + ")"); - int old = a[index]; - a[index] = k; - return old; - } - - public void clear() { - - size = 0; - if (ASSERTS) - assert size <= a.length; - } - - public int size() { - return size; - } - - public void size(final int size) { - if (size > a.length) - ensureCapacity(size); - if (size > this.size) - Arrays.fill(a, this.size, size, (0)); - - this.size = size; - } - - public boolean isEmpty() { - return size == 0; - } - - /** - * Trims this array list so that the capacity is equal to the size. - * - * @see java.util.ArrayList#trimToSize() - */ - public void trim() { - trim(0); - } - - /** - * Trims the backing array if it is too large. - * - * If the current array length is smaller than or equal to n, - * this method does nothing. Otherwise, it trims the array length to the - * maximum between n and {@link #size()}. - * - *

- * This method is useful when reusing lists. {@linkplain #clear() Clearing a - * list} leaves the array length untouched. If you are reusing a list many - * times, you can call this method with a typical size to avoid keeping - * around a very large array just because of a few large transient lists. - * - * @param n - * the threshold for the trimming. - */ - - public void trim(final int n) { - // TODO: use Arrays.trim() and preserve type only if necessary - if (n >= a.length || size == a.length) - return; - final int t[] = new int[Math.max(n, size)]; - System.arraycopy(a, 0, t, 0, size); - a = t; - if (ASSERTS) - assert size <= a.length; - } - - /** - * Copies element of this type-specific list into the given array using - * optimized system calls. - * - * @param from - * the start index (inclusive). - * @param a - * the destination array. - * @param offset - * the offset into the destination array where to store the first - * element copied. - * @param length - * the number of elements to be copied. - */ - - public void getElements(final int from, final int[] a, final int offset, - final int length) { - IntArrays.ensureOffsetLength(a, offset, length); - System.arraycopy(this.a, from, a, offset, length); - } - - /** - * Removes elements of this type-specific list using optimized system calls. - * - * @param from - * the start index (inclusive). - * @param to - * the end index (exclusive). - */ - public void removeElements(final int from, final int to) { - it.unimi.dsi.fastutil.Arrays.ensureFromTo(size, from, to); - System.arraycopy(a, to, a, from, size - to); - size -= (to - from); - - } - - /** - * Adds elements to this type-specific list using optimized system calls. - * - * @param index - * the index at which to add elements. - * @param a - * the array containing the elements. - * @param offset - * the offset of the first element to add. - * @param length - * the number of elements to add. - */ - public void addElements(final int index, final int a[], final int offset, - final int length) { - ensureIndex(index); - IntArrays.ensureOffsetLength(a, offset, length); - grow(size + length); - System.arraycopy(this.a, index, this.a, index + length, size - index); - System.arraycopy(a, offset, this.a, index, length); - size += length; - } - - public int[] toIntArray(int a[]) { - if (a == null || a.length < size) - a = new int[size]; - System.arraycopy(this.a, 0, a, 0, size); - return a; - } - - public boolean addAll(int index, final IntCollection c) { - ensureIndex(index); - int n = c.size(); - if (n == 0) - return false; - grow(size + n); - if (index != size) - System.arraycopy(a, index, a, index + n, size - index); - final IntIterator i = c.iterator(); - size += n; - while (n-- != 0) - a[index++] = i.nextInt(); - if (ASSERTS) - assert size <= a.length; - return true; - } - - public boolean addAll(final int index, final IntList l) { - ensureIndex(index); - final int n = l.size(); - if (n == 0) - return false; - grow(size + n); - if (index != size) - System.arraycopy(a, index, a, index + n, size - index); - l.getElements(0, a, index, n); - size += n; - if (ASSERTS) - assert size <= a.length; - return true; - } - - @Override - public boolean removeAll(final IntCollection c) { - final int[] a = this.a; - int j = 0; - for (int i = 0; i < size; i++) - if (!c.contains(a[i])) - a[j++] = a[i]; - final boolean modified = size != j; - size = j; - return modified; - } - - @Override - public boolean removeAll(final Collection c) { - final int[] a = this.a; - int j = 0; - for (int i = 0; i < size; i++) - if (!c.contains((Integer.valueOf(a[i])))) - a[j++] = a[i]; - final boolean modified = size != j; - size = j; - return modified; - } - public IntListIterator listIterator(final int index) { - ensureIndex(index); - - return new AbstractIntListIterator() { - int pos = index, last = -1; - - public boolean hasNext() { - return pos < size; - } - public boolean hasPrevious() { - return pos > 0; - } - public int nextInt() { - if (!hasNext()) - throw new NoSuchElementException(); - return a[last = pos++]; - } - public int previousInt() { - if (!hasPrevious()) - throw new NoSuchElementException(); - return a[last = --pos]; - } - public int nextIndex() { - return pos; - } - public int previousIndex() { - return pos - 1; - } - public void add(int k) { - it.unimi.dsi.fastutil.ints.IntArrayList.this.add(pos++, k); - last = -1; - } - public void set(int k) { - if (last == -1) - throw new IllegalStateException(); - it.unimi.dsi.fastutil.ints.IntArrayList.this.set(last, k); - } - public void remove() { - if (last == -1) - throw new IllegalStateException(); - it.unimi.dsi.fastutil.ints.IntArrayList.this.removeInt(last); - /* - * If the last operation was a next(), we are removing an - * element *before* us, and we must decrease pos - * correspondingly. - */ - if (last < pos) - pos--; - last = -1; - } - }; - } - - public it.unimi.dsi.fastutil.ints.IntArrayList clone() { - it.unimi.dsi.fastutil.ints.IntArrayList c = new it.unimi.dsi.fastutil.ints.IntArrayList(size); - System.arraycopy(a, 0, c.a, 0, size); - c.size = size; - return c; - } - - /** - * Compares this type-specific array list to another one. - * - *

- * This method exists only for sake of efficiency. The implementation - * inherited from the abstract implementation would already work. - * - * @param l - * a type-specific array list. - * @return true if the argument contains the same elements of this - * type-specific array list. - */ - public boolean equals(final it.unimi.dsi.fastutil.ints.IntArrayList l) { - if (l == this) - return true; - int s = size(); - if (s != l.size()) - return false; - final int[] a1 = a; - final int[] a2 = l.a; - - while (s-- != 0) - if (a1[s] != a2[s]) - return false; - - return true; - } - - /** - * Compares this array list to another array list. - * - *

- * This method exists only for sake of efficiency. The implementation - * inherited from the abstract implementation would already work. - * - * @param l - * an array list. - * @return a negative integer, zero, or a positive integer as this list is - * lexicographically less than, equal to, or greater than the - * argument. - */ - - public int compareTo(final it.unimi.dsi.fastutil.ints.IntArrayList l) { - final int s1 = size(), s2 = l.size(); - final int a1[] = a, a2[] = l.a; - int e1, e2; - int r, i; - - for (i = 0; i < s1 && i < s2; i++) { - e1 = a1[i]; - e2 = a2[i]; - if ((r = (Integer.compare((e1), (e2)))) != 0) - return r; - } - - return i < s2 ? -1 : (i < s1 ? 1 : 0); - } - - private void writeObject(java.io.ObjectOutputStream s) - throws java.io.IOException { - s.defaultWriteObject(); - for (int i = 0; i < size; i++) - s.writeInt(a[i]); - } - - private void readObject(java.io.ObjectInputStream s) - throws java.io.IOException, ClassNotFoundException { - s.defaultReadObject(); - a = new int[size]; - for (int i = 0; i < size; i++) - a[i] = s.readInt(); - } -} diff --git a/src/main/java/it/unimi/dsi/fastutil/ints/IntArraySet.java b/src/main/java/it/unimi/dsi/fastutil/ints/IntArraySet.java deleted file mode 100644 index 75fea96..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/ints/IntArraySet.java +++ /dev/null @@ -1,269 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Primitive-type-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2007-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.ints; - -import it.unimi.dsi.fastutil.ints.AbstractIntIterator; -import it.unimi.dsi.fastutil.ints.AbstractIntSet; -import it.unimi.dsi.fastutil.ints.IntArrays; -import it.unimi.dsi.fastutil.ints.IntCollection; -import it.unimi.dsi.fastutil.ints.IntIterator; - -import java.util.Collection; -import java.util.NoSuchElementException; - -/** - * A simple, brute-force implementation of a set based on a backing array. - * - *

- * The main purpose of this implementation is that of wrapping cleanly the - * brute-force approach to the storage of a very small number of items: just put - * them into an array and scan linearly to find an item. - */ - -public class IntArraySet extends AbstractIntSet - implements - java.io.Serializable, - Cloneable { - - private static final long serialVersionUID = 1L; - /** The backing array (valid up to {@link #size}, excluded). */ - private transient int[] a; - /** The number of valid entries in {@link #a}. */ - private int size; - - /** - * Creates a new array set using the given backing array. The resulting set - * will have as many elements as the array. - * - *

- * It is responsibility of the caller that the elements of a - * are distinct. - * - * @param a - * the backing array. - */ - public IntArraySet(final int[] a) { - this.a = a; - size = a.length; - } - - /** - * Creates a new empty array set. - */ - public IntArraySet() { - this.a = IntArrays.EMPTY_ARRAY; - } - - /** - * Creates a new empty array set of given initial capacity. - * - * @param capacity - * the initial capacity. - */ - public IntArraySet(final int capacity) { - this.a = new int[capacity]; - } - - /** - * Creates a new array set copying the contents of a given collection. - * - * @param c - * a collection. - */ - public IntArraySet(IntCollection c) { - this(c.size()); - addAll(c); - } - - /** - * Creates a new array set copying the contents of a given set. - * - * @param c - * a collection. - */ - public IntArraySet(final Collection c) { - this(c.size()); - addAll(c); - } - - /** - * Creates a new array set using the given backing array and the given - * number of elements of the array. - * - *

- * It is responsibility of the caller that the first size - * elements of a are distinct. - * - * @param a - * the backing array. - * @param size - * the number of valid elements in a. - */ - public IntArraySet(final int[] a, final int size) { - this.a = a; - this.size = size; - if (size > a.length) - throw new IllegalArgumentException("The provided size (" + size - + ") is larger than or equal to the array size (" - + a.length + ")"); - } - - private int findKey(final int o) { - for (int i = size; i-- != 0;) - if (((a[i]) == (o))) - return i; - return -1; - } - - @Override - public IntIterator iterator() { - return new AbstractIntIterator() { - int next = 0; - - public boolean hasNext() { - return next < size; - } - - public int nextInt() { - if (!hasNext()) - throw new NoSuchElementException(); - return a[next++]; - } - - public void remove() { - final int tail = size-- - next--; - System.arraycopy(a, next + 1, a, next, tail); - - } - }; - } - - public boolean contains(final int k) { - return findKey(k) != -1; - } - - public int size() { - return size; - } - - @Override - public boolean remove(final int k) { - final int pos = findKey(k); - if (pos == -1) - return false; - final int tail = size - pos - 1; - for (int i = 0; i < tail; i++) - a[pos + i] = a[pos + i + 1]; - size--; - - return true; - } - - @Override - public boolean add(final int k) { - final int pos = findKey(k); - if (pos != -1) - return false; - if (size == a.length) { - final int[] b = new int[size == 0 ? 2 : size * 2]; - for (int i = size; i-- != 0;) - b[i] = a[i]; - a = b; - } - a[size++] = k; - return true; - } - - @Override - public void clear() { - - size = 0; - } - - @Override - public boolean isEmpty() { - return size == 0; - } - - /** - * Returns a deep copy of this set. - * - *

- * This method performs a deep copy of this hash set; the data stored in the - * set, however, is not cloned. Note that this makes a difference only for - * object keys. - * - * @return a deep copy of this set. - */ - - public it.unimi.dsi.fastutil.ints.IntArraySet clone() { - it.unimi.dsi.fastutil.ints.IntArraySet c; - try { - c = (it.unimi.dsi.fastutil.ints.IntArraySet) super.clone(); - } catch (CloneNotSupportedException cantHappen) { - throw new InternalError(); - } - c.a = a.clone(); - return c; - } - - private void writeObject(java.io.ObjectOutputStream s) - throws java.io.IOException { - s.defaultWriteObject(); - for (int i = 0; i < size; i++) - s.writeInt(a[i]); - } - - private void readObject(java.io.ObjectInputStream s) - throws java.io.IOException, ClassNotFoundException { - s.defaultReadObject(); - a = new int[size]; - for (int i = 0; i < size; i++) - a[i] = s.readInt(); - } - -} diff --git a/src/main/java/it/unimi/dsi/fastutil/ints/IntArrays.java b/src/main/java/it/unimi/dsi/fastutil/ints/IntArrays.java deleted file mode 100644 index 132e00d..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/ints/IntArrays.java +++ /dev/null @@ -1,3454 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Primitive-type-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * - * - * For the sorting and binary search code: - * - * Copyright (C) 1999 CERN - European Organization for Nuclear Research. - * - * Permission to use, copy, modify, distribute and sell this software and - * its documentation for any purpose is hereby granted without fee, - * provided that the above copyright notice appear in all copies and that - * both that copyright notice and this permission notice appear in - * supporting documentation. CERN makes no representations about the - * suitability of this software for any purpose. It is provided "as is" - * without expressed or implied warranty. - */ - -package it.unimi.dsi.fastutil.ints; - -import it.unimi.dsi.fastutil.Arrays; -import it.unimi.dsi.fastutil.Hash; -import it.unimi.dsi.fastutil.ints.IntComparator; - -import java.util.Random; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutorCompletionService; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.ForkJoinPool; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.RecursiveAction; -import java.util.concurrent.atomic.AtomicInteger; - -/** - * A class providing static methods and objects that do useful things with - * type-specific arrays. - * - *

- * In particular, the ensureCapacity(), grow(), - * trim() and setLength() methods allow to handle - * arrays much like array lists. This can be very useful when efficiency (or - * syntactic simplicity) reasons make array lists unsuitable. - * - *

- - - * possible to load and save arrays of primitive types as sequences of elements - * in {@link java.io.DataInput} format (i.e., not as objects) or as sequences of - * lines of text. - * - *

Sorting

- * - *

- * There are several sorting methods available. The main theme is that of - * letting you choose the sorting algorithm you prefer (i.e., trading stability - * of mergesort for no memory allocation in quicksort). Several algorithms - * provide a parallel version, that will use the - * {@linkplain Runtime#availableProcessors() number of cores available}. Some - * algorithms also provide an explicit indirect sorting facility, which - * makes it possible to sort an array using the values in another array as - * comparator. - * - *

- * All comparison-based algorithm have an implementation based on a - * type-specific comparator. - * - *

- * As a general rule, sequential radix sort is significantly faster than - * quicksort or mergesort, in particular on random-looking data. In the parallel - * case, up to a few cores parallel radix sort is still the fastest, but at some - * point quicksort exploits parallelism better. - * - *

- * If you are fine with not knowing exactly which algorithm will be run (in - * particular, not knowing exactly whether a support array will be allocated), - * the dual-pivot parallel sorts in {@link java.util.Arrays} are about 50% - * faster than the classical single-pivot implementation used here. - * - *

- * In any case, if sorting time is important I suggest that you benchmark your - * sorting load with your data distribution and on your architecture. - * - * @see java.util.Arrays - */ - -public class IntArrays { - private IntArrays() { - } - - /** A static, final, empty array. */ - public final static int[] EMPTY_ARRAY = {}; - /** - * Ensures that an array can contain the given number of entries. - * - *

- * If you cannot foresee whether this array will need again to be enlarged, - * you should probably use grow() instead. - * - * @param array - * an array. - * @param length - * the new minimum length for this array. - * @return array, if it contains length entries or - * more; otherwise, an array with length entries whose - * first array.length entries are the same as those of - * array. - */ - public static int[] ensureCapacity(final int[] array, final int length) { - if (length > array.length) { - final int t[] = - - new int[length]; - - System.arraycopy(array, 0, t, 0, array.length); - return t; - } - return array; - } - - /** - * Ensures that an array can contain the given number of entries, preserving - * just a part of the array. - * - * @param array - * an array. - * @param length - * the new minimum length for this array. - * @param preserve - * the number of elements of the array that must be preserved in - * case a new allocation is necessary. - * @return array, if it can contain length entries - * or more; otherwise, an array with length entries - * whose first preserve entries are the same as those - * of array. - */ - public static int[] ensureCapacity(final int[] array, final int length, - final int preserve) { - if (length > array.length) { - final int t[] = - - new int[length]; - - System.arraycopy(array, 0, t, 0, preserve); - return t; - } - return array; - } - - /** - * Grows the given array to the maximum between the given length and the - * current length multiplied by two, provided that the given length is - * larger than the current length. - * - *

- * If you want complete control on the array growth, you should probably use - * ensureCapacity() instead. - * - * @param array - * an array. - * @param length - * the new minimum length for this array. - * @return array, if it can contain length - * entries; otherwise, an array with max(length, - * array.length/φ) entries whose first - * array.length entries are the same as those of - * array. - * */ - - public static int[] grow(final int[] array, final int length) { - if (length > array.length) { - final int newLength = (int) Math.max( - Math.min(2L * array.length, Arrays.MAX_ARRAY_SIZE), length); - final int t[] = - - new int[newLength]; - - System.arraycopy(array, 0, t, 0, array.length); - return t; - } - return array; - } - - /** - * Grows the given array to the maximum between the given length and the - * current length multiplied by two, provided that the given length is - * larger than the current length, preserving just a part of the array. - * - *

- * If you want complete control on the array growth, you should probably use - * ensureCapacity() instead. - * - * @param array - * an array. - * @param length - * the new minimum length for this array. - * @param preserve - * the number of elements of the array that must be preserved in - * case a new allocation is necessary. - * @return array, if it can contain length - * entries; otherwise, an array with max(length, - * array.length/φ) entries whose first - * preserve entries are the same as those of - * array. - * */ - - public static int[] grow(final int[] array, final int length, - final int preserve) { - - if (length > array.length) { - final int newLength = (int) Math.max( - Math.min(2L * array.length, Arrays.MAX_ARRAY_SIZE), length); - - final int t[] = - - new int[newLength]; - - System.arraycopy(array, 0, t, 0, preserve); - - return t; - } - return array; - - } - - /** - * Trims the given array to the given length. - * - * @param array - * an array. - * @param length - * the new maximum length for the array. - * @return array, if it contains length entries or - * less; otherwise, an array with length entries whose - * entries are the same as the first length entries of - * array. - * - */ - - public static int[] trim(final int[] array, final int length) { - if (length >= array.length) - return array; - final int t[] = - - length == 0 ? EMPTY_ARRAY : new int[length]; - - System.arraycopy(array, 0, t, 0, length); - return t; - } - - /** - * Sets the length of the given array. - * - * @param array - * an array. - * @param length - * the new length for the array. - * @return array, if it contains exactly length - * entries; otherwise, if it contains more than - * length entries, an array with length - * entries whose entries are the same as the first - * length entries of array; otherwise, an - * array with length entries whose first - * array.length entries are the same as those of - * array. - * - */ - - public static int[] setLength(final int[] array, final int length) { - if (length == array.length) - return array; - if (length < array.length) - return trim(array, length); - return ensureCapacity(array, length); - } - - /** - * Returns a copy of a portion of an array. - * - * @param array - * an array. - * @param offset - * the first element to copy. - * @param length - * the number of elements to copy. - * @return a new array containing length elements of - * array starting at offset. - */ - - public static int[] copy(final int[] array, final int offset, - final int length) { - ensureOffsetLength(array, offset, length); - final int[] a = - - length == 0 ? EMPTY_ARRAY : new int[length]; - - System.arraycopy(array, offset, a, 0, length); - return a; - } - - /** - * Returns a copy of an array. - * - * @param array - * an array. - * @return a copy of array. - */ - - public static int[] copy(final int[] array) { - return array.clone(); - } - - /** - * Fills the given array with the given value. - * - * @param array - * an array. - * @param value - * the new value for all elements of the array. - * @deprecated Please use the corresponding {@link java.util.Arrays} method. - */ - - @Deprecated - public static void fill(final int[] array, final int value) { - int i = array.length; - while (i-- != 0) - array[i] = value; - } - - /** - * Fills a portion of the given array with the given value. - * - * @param array - * an array. - * @param from - * the starting index of the portion to fill (inclusive). - * @param to - * the end index of the portion to fill (exclusive). - * @param value - * the new value for all elements of the specified portion of the - * array. - * @deprecated Please use the corresponding {@link java.util.Arrays} method. - */ - - @Deprecated - public static void fill(final int[] array, final int from, int to, - final int value) { - ensureFromTo(array, from, to); - if (from == 0) - while (to-- != 0) - array[to] = value; - else - for (int i = from; i < to; i++) - array[i] = value; - } - - /** - * Returns true if the two arrays are elementwise equal. - * - * @param a1 - * an array. - * @param a2 - * another array. - * @return true if the two arrays are of the same length, and their elements - * are equal. - * @deprecated Please use the corresponding {@link java.util.Arrays} method, - * which is intrinsified in recent JVMs. - */ - - @Deprecated - public static boolean equals(final int[] a1, final int a2[]) { - int i = a1.length; - if (i != a2.length) - return false; - while (i-- != 0) - if (!((a1[i]) == (a2[i]))) - return false; - return true; - } - - /** - * Ensures that a range given by its first (inclusive) and last (exclusive) - * elements fits an array. - * - *

- * This method may be used whenever an array range check is needed. - * - * @param a - * an array. - * @param from - * a start index (inclusive). - * @param to - * an end index (exclusive). - * @throws IllegalArgumentException - * if from is greater than to. - * @throws ArrayIndexOutOfBoundsException - * if from or to are greater than the - * array length or negative. - */ - public static void ensureFromTo(final int[] a, final int from, final int to) { - Arrays.ensureFromTo(a.length, from, to); - } - - /** - * Ensures that a range given by an offset and a length fits an array. - * - *

- * This method may be used whenever an array range check is needed. - * - * @param a - * an array. - * @param offset - * a start index. - * @param length - * a length (the number of elements in the range). - * @throws IllegalArgumentException - * if length is negative. - * @throws ArrayIndexOutOfBoundsException - * if offset is negative or offset+ - * length is greater than the array length. - */ - public static void ensureOffsetLength(final int[] a, final int offset, - final int length) { - Arrays.ensureOffsetLength(a.length, offset, length); - } - - /** - * Ensures that two arrays are of the same length. - * - * @param a - * an array. - * @param b - * another array. - * @throws IllegalArgumentException - * if the two argument arrays are not of the same length. - */ - public static void ensureSameLength(final int[] a, final int[] b) { - if (a.length != b.length) - throw new IllegalArgumentException("Array size mismatch: " - + a.length + " != " + b.length); - } - - private static final int QUICKSORT_NO_REC = 16; - private static final int PARALLEL_QUICKSORT_NO_FORK = 8192; - private static final int QUICKSORT_MEDIAN_OF_9 = 128; - private static final int MERGESORT_NO_REC = 16; - - /** - * Swaps two elements of an anrray. - * - * @param x - * an array. - * @param a - * a position in {@code x}. - * @param b - * another position in {@code x}. - */ - public static void swap(final int x[], final int a, final int b) { - final int t = x[a]; - x[a] = x[b]; - x[b] = t; - } - - /** - * Swaps two sequences of elements of an array. - * - * @param x - * an array. - * @param a - * a position in {@code x}. - * @param b - * another position in {@code x}. - * @param n - * the number of elements to exchange starting at {@code a} and - * {@code b}. - */ - public static void swap(final int[] x, int a, int b, final int n) { - for (int i = 0; i < n; i++, a++, b++) - swap(x, a, b); - } - - private static int med3(final int x[], final int a, final int b, - final int c, IntComparator comp) { - final int ab = comp.compare(x[a], x[b]); - final int ac = comp.compare(x[a], x[c]); - final int bc = comp.compare(x[b], x[c]); - return (ab < 0 ? (bc < 0 ? b : ac < 0 ? c : a) : (bc > 0 ? b : ac > 0 - ? c - : a)); - } - - private static void selectionSort(final int[] a, final int from, - final int to, final IntComparator comp) { - for (int i = from; i < to - 1; i++) { - int m = i; - for (int j = i + 1; j < to; j++) - if (comp.compare(a[j], a[m]) < 0) - m = j; - if (m != i) { - final int u = a[i]; - a[i] = a[m]; - a[m] = u; - } - } - } - - private static void insertionSort(final int[] a, final int from, - final int to, final IntComparator comp) { - for (int i = from; ++i < to;) { - int t = a[i]; - int j = i; - for (int u = a[j - 1]; comp.compare(t, u) < 0; u = a[--j - 1]) { - a[j] = u; - if (from == j - 1) { - --j; - break; - } - } - a[j] = t; - } - } - - /** - * Sorts the specified range of elements according to the order induced by - * the specified comparator using quicksort. - * - *

- * The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley - * and M. Douglas McIlroy, “Engineering a Sort Function”, - * Software: Practice and Experience, 23(11), pages 1249−1265, - * 1993. - * - *

- * Note that this implementation does not allocate any object, contrarily to - * the implementation used to sort primitive types in - * {@link java.util.Arrays}, which switches to mergesort on large inputs. - * - * @param x - * the array to be sorted. - * @param from - * the index of the first element (inclusive) to be sorted. - * @param to - * the index of the last element (exclusive) to be sorted. - * @param comp - * the comparator to determine the sorting order. - * - */ - public static void quickSort(final int[] x, final int from, final int to, - final IntComparator comp) { - final int len = to - from; - // Selection sort on smallest arrays - if (len < QUICKSORT_NO_REC) { - selectionSort(x, from, to, comp); - return; - } - - // Choose a partition element, v - int m = from + len / 2; - int l = from; - int n = to - 1; - if (len > QUICKSORT_MEDIAN_OF_9) { // Big arrays, pseudomedian of 9 - int s = len / 8; - l = med3(x, l, l + s, l + 2 * s, comp); - m = med3(x, m - s, m, m + s, comp); - n = med3(x, n - 2 * s, n - s, n, comp); - } - m = med3(x, l, m, n, comp); // Mid-size, med of 3 - - final int v = x[m]; - - // Establish Invariant: v* (v)* v* - int a = from, b = a, c = to - 1, d = c; - while (true) { - int comparison; - while (b <= c && (comparison = comp.compare(x[b], v)) <= 0) { - if (comparison == 0) - swap(x, a++, b); - b++; - } - while (c >= b && (comparison = comp.compare(x[c], v)) >= 0) { - if (comparison == 0) - swap(x, c, d--); - c--; - } - if (b > c) - break; - swap(x, b++, c--); - } - - // Swap partition elements back to middle - int s; - s = Math.min(a - from, b - a); - swap(x, from, b - s, s); - s = Math.min(d - c, to - d - 1); - swap(x, b, to - s, s); - - // Recursively sort non-partition-elements - if ((s = b - a) > 1) - quickSort(x, from, from + s, comp); - if ((s = d - c) > 1) - quickSort(x, to - s, to, comp); - } - - /** - * Sorts an array according to the order induced by the specified comparator - * using quicksort. - * - *

- * The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley - * and M. Douglas McIlroy, “Engineering a Sort Function”, - * Software: Practice and Experience, 23(11), pages 1249−1265, - * 1993. - * - *

- * Note that this implementation does not allocate any object, contrarily to - * the implementation used to sort primitive types in - * {@link java.util.Arrays}, which switches to mergesort on large inputs. - * - * @param x - * the array to be sorted. - * @param comp - * the comparator to determine the sorting order. - * - */ - public static void quickSort(final int[] x, final IntComparator comp) { - quickSort(x, 0, x.length, comp); - } - - protected static class ForkJoinQuickSortComp extends RecursiveAction { - private static final long serialVersionUID = 1L; - private final int from; - private final int to; - private final int[] x; - private final IntComparator comp; - - public ForkJoinQuickSortComp(final int[] x, final int from, - final int to, final IntComparator comp) { - this.from = from; - this.to = to; - this.x = x; - this.comp = comp; - } - - @Override - protected void compute() { - final int[] x = this.x; - final int len = to - from; - if (len < PARALLEL_QUICKSORT_NO_FORK) { - quickSort(x, from, to, comp); - return; - } - // Choose a partition element, v - int m = from + len / 2; - int l = from; - int n = to - 1; - int s = len / 8; - l = med3(x, l, l + s, l + 2 * s, comp); - m = med3(x, m - s, m, m + s, comp); - n = med3(x, n - 2 * s, n - s, n, comp); - m = med3(x, l, m, n, comp); - final int v = x[m]; - // Establish Invariant: v* (v)* v* - int a = from, b = a, c = to - 1, d = c; - while (true) { - int comparison; - while (b <= c && (comparison = comp.compare(x[b], v)) <= 0) { - if (comparison == 0) - swap(x, a++, b); - b++; - } - while (c >= b && (comparison = comp.compare(x[c], v)) >= 0) { - if (comparison == 0) - swap(x, c, d--); - c--; - } - if (b > c) - break; - swap(x, b++, c--); - } - // Swap partition elements back to middle - int t; - s = Math.min(a - from, b - a); - swap(x, from, b - s, s); - s = Math.min(d - c, to - d - 1); - swap(x, b, to - s, s); - // Recursively sort non-partition-elements - s = b - a; - t = d - c; - if (s > 1 && t > 1) - invokeAll(new ForkJoinQuickSortComp(x, from, from + s, comp), - new ForkJoinQuickSortComp(x, to - t, to, comp)); - else if (s > 1) - invokeAll(new ForkJoinQuickSortComp(x, from, from + s, comp)); - else - invokeAll(new ForkJoinQuickSortComp(x, to - t, to, comp)); - } - } - - /** - * Sorts the specified range of elements according to the order induced by - * the specified comparator using a parallel quicksort. - * - *

- * The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley - * and M. Douglas McIlroy, “Engineering a Sort Function”, - * Software: Practice and Experience, 23(11), pages 1249−1265, - * 1993. - * - *

- * This implementation uses a {@link ForkJoinPool} executor service with - * {@link Runtime#availableProcessors()} parallel threads. - * - * @param x - * the array to be sorted. - * @param from - * the index of the first element (inclusive) to be sorted. - * @param to - * the index of the last element (exclusive) to be sorted. - * @param comp - * the comparator to determine the sorting order. - */ - public static void parallelQuickSort(final int[] x, final int from, - final int to, final IntComparator comp) { - if (to - from < PARALLEL_QUICKSORT_NO_FORK) - quickSort(x, from, to, comp); - else { - final ForkJoinPool pool = new ForkJoinPool(Runtime.getRuntime() - .availableProcessors()); - pool.invoke(new ForkJoinQuickSortComp(x, from, to, comp)); - pool.shutdown(); - } - } - - /** - * Sorts an array according to the order induced by the specified comparator - * using a parallel quicksort. - * - *

- * The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley - * and M. Douglas McIlroy, “Engineering a Sort Function”, - * Software: Practice and Experience, 23(11), pages 1249−1265, - * 1993. - * - *

- * This implementation uses a {@link ForkJoinPool} executor service with - * {@link Runtime#availableProcessors()} parallel threads. - * - * @param x - * the array to be sorted. - * @param comp - * the comparator to determine the sorting order. - */ - public static void parallelQuickSort(final int[] x, final IntComparator comp) { - parallelQuickSort(x, 0, x.length, comp); - } - - private static int med3(final int x[], final int a, final int b, final int c) { - final int ab = (Integer.compare((x[a]), (x[b]))); - final int ac = (Integer.compare((x[a]), (x[c]))); - final int bc = (Integer.compare((x[b]), (x[c]))); - return (ab < 0 ? (bc < 0 ? b : ac < 0 ? c : a) : (bc > 0 ? b : ac > 0 - ? c - : a)); - } - - private static void selectionSort(final int[] a, final int from, - final int to) { - for (int i = from; i < to - 1; i++) { - int m = i; - for (int j = i + 1; j < to; j++) - if (((a[j]) < (a[m]))) - m = j; - if (m != i) { - final int u = a[i]; - a[i] = a[m]; - a[m] = u; - } - } - } - - private static void insertionSort(final int[] a, final int from, - final int to) { - for (int i = from; ++i < to;) { - int t = a[i]; - int j = i; - for (int u = a[j - 1]; ((t) < (u)); u = a[--j - 1]) { - a[j] = u; - if (from == j - 1) { - --j; - break; - } - } - a[j] = t; - } - } - - /** - * Sorts the specified range of elements according to the natural ascending - * order using quicksort. - * - *

- * The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley - * and M. Douglas McIlroy, “Engineering a Sort Function”, - * Software: Practice and Experience, 23(11), pages 1249−1265, - * 1993. - * - *

- * Note that this implementation does not allocate any object, contrarily to - * the implementation used to sort primitive types in - * {@link java.util.Arrays}, which switches to mergesort on large inputs. - * - * @param x - * the array to be sorted. - * @param from - * the index of the first element (inclusive) to be sorted. - * @param to - * the index of the last element (exclusive) to be sorted. - */ - - public static void quickSort(final int[] x, final int from, final int to) { - final int len = to - from; - // Selection sort on smallest arrays - if (len < QUICKSORT_NO_REC) { - selectionSort(x, from, to); - return; - } - - // Choose a partition element, v - int m = from + len / 2; - int l = from; - int n = to - 1; - if (len > QUICKSORT_MEDIAN_OF_9) { // Big arrays, pseudomedian of 9 - int s = len / 8; - l = med3(x, l, l + s, l + 2 * s); - m = med3(x, m - s, m, m + s); - n = med3(x, n - 2 * s, n - s, n); - } - m = med3(x, l, m, n); // Mid-size, med of 3 - - final int v = x[m]; - - // Establish Invariant: v* (v)* v* - int a = from, b = a, c = to - 1, d = c; - while (true) { - int comparison; - while (b <= c && (comparison = (Integer.compare((x[b]), (v)))) <= 0) { - if (comparison == 0) - swap(x, a++, b); - b++; - } - while (c >= b && (comparison = (Integer.compare((x[c]), (v)))) >= 0) { - if (comparison == 0) - swap(x, c, d--); - c--; - } - if (b > c) - break; - swap(x, b++, c--); - } - - // Swap partition elements back to middle - int s; - s = Math.min(a - from, b - a); - swap(x, from, b - s, s); - s = Math.min(d - c, to - d - 1); - swap(x, b, to - s, s); - - // Recursively sort non-partition-elements - if ((s = b - a) > 1) - quickSort(x, from, from + s); - if ((s = d - c) > 1) - quickSort(x, to - s, to); - } - - /** - * Sorts an array according to the natural ascending order using quicksort. - * - *

- * The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley - * and M. Douglas McIlroy, “Engineering a Sort Function”, - * Software: Practice and Experience, 23(11), pages 1249−1265, - * 1993. - * - *

- * Note that this implementation does not allocate any object, contrarily to - * the implementation used to sort primitive types in - * {@link java.util.Arrays}, which switches to mergesort on large inputs. - * - * @param x - * the array to be sorted. - * - */ - public static void quickSort(final int[] x) { - quickSort(x, 0, x.length); - } - - protected static class ForkJoinQuickSort extends RecursiveAction { - private static final long serialVersionUID = 1L; - private final int from; - private final int to; - private final int[] x; - - public ForkJoinQuickSort(final int[] x, final int from, final int to) { - this.from = from; - this.to = to; - this.x = x; - } - - @Override - protected void compute() { - final int[] x = this.x; - final int len = to - from; - if (len < PARALLEL_QUICKSORT_NO_FORK) { - quickSort(x, from, to); - return; - } - // Choose a partition element, v - int m = from + len / 2; - int l = from; - int n = to - 1; - int s = len / 8; - l = med3(x, l, l + s, l + 2 * s); - m = med3(x, m - s, m, m + s); - n = med3(x, n - 2 * s, n - s, n); - m = med3(x, l, m, n); - final int v = x[m]; - // Establish Invariant: v* (v)* v* - int a = from, b = a, c = to - 1, d = c; - while (true) { - int comparison; - while (b <= c - && (comparison = (Integer.compare((x[b]), (v)))) <= 0) { - if (comparison == 0) - swap(x, a++, b); - b++; - } - while (c >= b - && (comparison = (Integer.compare((x[c]), (v)))) >= 0) { - if (comparison == 0) - swap(x, c, d--); - c--; - } - if (b > c) - break; - swap(x, b++, c--); - } - // Swap partition elements back to middle - int t; - s = Math.min(a - from, b - a); - swap(x, from, b - s, s); - s = Math.min(d - c, to - d - 1); - swap(x, b, to - s, s); - // Recursively sort non-partition-elements - s = b - a; - t = d - c; - if (s > 1 && t > 1) - invokeAll(new ForkJoinQuickSort(x, from, from + s), - new ForkJoinQuickSort(x, to - t, to)); - else if (s > 1) - invokeAll(new ForkJoinQuickSort(x, from, from + s)); - else - invokeAll(new ForkJoinQuickSort(x, to - t, to)); - } - } - - /** - * Sorts the specified range of elements according to the natural ascending - * order using a parallel quicksort. - * - *

- * The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley - * and M. Douglas McIlroy, “Engineering a Sort Function”, - * Software: Practice and Experience, 23(11), pages 1249−1265, - * 1993. - * - *

- * This implementation uses a {@link ForkJoinPool} executor service with - * {@link Runtime#availableProcessors()} parallel threads. - * - * @param x - * the array to be sorted. - * @param from - * the index of the first element (inclusive) to be sorted. - * @param to - * the index of the last element (exclusive) to be sorted. - */ - public static void parallelQuickSort(final int[] x, final int from, - final int to) { - if (to - from < PARALLEL_QUICKSORT_NO_FORK) - quickSort(x, from, to); - else { - final ForkJoinPool pool = new ForkJoinPool(Runtime.getRuntime() - .availableProcessors()); - pool.invoke(new ForkJoinQuickSort(x, from, to)); - pool.shutdown(); - } - } - - /** - * Sorts an array according to the natural ascending order using a parallel - * quicksort. - * - *

- * The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley - * and M. Douglas McIlroy, “Engineering a Sort Function”, - * Software: Practice and Experience, 23(11), pages 1249−1265, - * 1993. - * - *

- * This implementation uses a {@link ForkJoinPool} executor service with - * {@link Runtime#availableProcessors()} parallel threads. - * - * @param x - * the array to be sorted. - * - */ - public static void parallelQuickSort(final int[] x) { - parallelQuickSort(x, 0, x.length); - } - - private static int med3Indirect(final int perm[], final int x[], - final int a, final int b, final int c) { - final int aa = x[perm[a]]; - final int bb = x[perm[b]]; - final int cc = x[perm[c]]; - final int ab = (Integer.compare((aa), (bb))); - final int ac = (Integer.compare((aa), (cc))); - final int bc = (Integer.compare((bb), (cc))); - return (ab < 0 ? (bc < 0 ? b : ac < 0 ? c : a) : (bc > 0 ? b : ac > 0 - ? c - : a)); - } - - private static void insertionSortIndirect(final int[] perm, final int[] a, - final int from, final int to) { - for (int i = from; ++i < to;) { - int t = perm[i]; - int j = i; - for (int u = perm[j - 1]; ((a[t]) < (a[u])); u = perm[--j - 1]) { - perm[j] = u; - if (from == j - 1) { - --j; - break; - } - } - perm[j] = t; - } - } - - /** - * Sorts the specified range of elements according to the natural ascending - * order using indirect quicksort. - * - *

- * The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley - * and M. Douglas McIlroy, “Engineering a Sort Function”, - * Software: Practice and Experience, 23(11), pages 1249−1265, - * 1993. - * - *

- * This method implement an indirect sort. The elements of - * perm (which must be exactly the numbers in the interval - * [0..perm.length)) will be permuted so that - * x[ perm[ i ] ] ≤ x[ perm[ i + 1 ] ]. - * - *

- * Note that this implementation does not allocate any object, contrarily to - * the implementation used to sort primitive types in - * {@link java.util.Arrays}, which switches to mergesort on large inputs. - * - * @param perm - * a permutation array indexing {@code x}. - * @param x - * the array to be sorted. - * @param from - * the index of the first element (inclusive) to be sorted. - * @param to - * the index of the last element (exclusive) to be sorted. - */ - - public static void quickSortIndirect(final int[] perm, final int[] x, - final int from, final int to) { - final int len = to - from; - // Selection sort on smallest arrays - if (len < QUICKSORT_NO_REC) { - insertionSortIndirect(perm, x, from, to); - return; - } - - // Choose a partition element, v - int m = from + len / 2; - int l = from; - int n = to - 1; - if (len > QUICKSORT_MEDIAN_OF_9) { // Big arrays, pseudomedian of 9 - int s = len / 8; - l = med3Indirect(perm, x, l, l + s, l + 2 * s); - m = med3Indirect(perm, x, m - s, m, m + s); - n = med3Indirect(perm, x, n - 2 * s, n - s, n); - } - m = med3Indirect(perm, x, l, m, n); // Mid-size, med of 3 - - final int v = x[perm[m]]; - - // Establish Invariant: v* (v)* v* - int a = from, b = a, c = to - 1, d = c; - while (true) { - int comparison; - while (b <= c - && (comparison = (Integer.compare((x[perm[b]]), (v)))) <= 0) { - if (comparison == 0) - swap(perm, a++, b); - b++; - } - while (c >= b - && (comparison = (Integer.compare((x[perm[c]]), (v)))) >= 0) { - if (comparison == 0) - swap(perm, c, d--); - c--; - } - if (b > c) - break; - swap(perm, b++, c--); - } - - // Swap partition elements back to middle - int s; - s = Math.min(a - from, b - a); - swap(perm, from, b - s, s); - s = Math.min(d - c, to - d - 1); - swap(perm, b, to - s, s); - - // Recursively sort non-partition-elements - if ((s = b - a) > 1) - quickSortIndirect(perm, x, from, from + s); - if ((s = d - c) > 1) - quickSortIndirect(perm, x, to - s, to); - } - - /** - * Sorts an array according to the natural ascending order using indirect - * quicksort. - * - *

- * The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley - * and M. Douglas McIlroy, “Engineering a Sort Function”, - * Software: Practice and Experience, 23(11), pages 1249−1265, - * 1993. - * - *

- * This method implement an indirect sort. The elements of - * perm (which must be exactly the numbers in the interval - * [0..perm.length)) will be permuted so that - * x[ perm[ i ] ] ≤ x[ perm[ i + 1 ] ]. - * - *

- * Note that this implementation does not allocate any object, contrarily to - * the implementation used to sort primitive types in - * {@link java.util.Arrays}, which switches to mergesort on large inputs. - * - * @param perm - * a permutation array indexing {@code x}. - * @param x - * the array to be sorted. - */ - public static void quickSortIndirect(final int perm[], final int[] x) { - quickSortIndirect(perm, x, 0, x.length); - } - - protected static class ForkJoinQuickSortIndirect extends RecursiveAction { - private static final long serialVersionUID = 1L; - private final int from; - private final int to; - private final int[] perm; - private final int[] x; - - public ForkJoinQuickSortIndirect(final int perm[], final int[] x, - final int from, final int to) { - this.from = from; - this.to = to; - this.x = x; - this.perm = perm; - } - - @Override - protected void compute() { - final int[] x = this.x; - final int len = to - from; - if (len < PARALLEL_QUICKSORT_NO_FORK) { - quickSortIndirect(perm, x, from, to); - return; - } - // Choose a partition element, v - int m = from + len / 2; - int l = from; - int n = to - 1; - int s = len / 8; - l = med3Indirect(perm, x, l, l + s, l + 2 * s); - m = med3Indirect(perm, x, m - s, m, m + s); - n = med3Indirect(perm, x, n - 2 * s, n - s, n); - m = med3Indirect(perm, x, l, m, n); - final int v = x[perm[m]]; - // Establish Invariant: v* (v)* v* - int a = from, b = a, c = to - 1, d = c; - while (true) { - int comparison; - while (b <= c - && (comparison = (Integer.compare((x[perm[b]]), (v)))) <= 0) { - if (comparison == 0) - swap(perm, a++, b); - b++; - } - while (c >= b - && (comparison = (Integer.compare((x[perm[c]]), (v)))) >= 0) { - if (comparison == 0) - swap(perm, c, d--); - c--; - } - if (b > c) - break; - swap(perm, b++, c--); - } - // Swap partition elements back to middle - int t; - s = Math.min(a - from, b - a); - swap(perm, from, b - s, s); - s = Math.min(d - c, to - d - 1); - swap(perm, b, to - s, s); - // Recursively sort non-partition-elements - s = b - a; - t = d - c; - if (s > 1 && t > 1) - invokeAll( - new ForkJoinQuickSortIndirect(perm, x, from, from + s), - new ForkJoinQuickSortIndirect(perm, x, to - t, to)); - else if (s > 1) - invokeAll(new ForkJoinQuickSortIndirect(perm, x, from, from + s)); - else - invokeAll(new ForkJoinQuickSortIndirect(perm, x, to - t, to)); - } - } - - /** - * Sorts the specified range of elements according to the natural ascending - * order using a parallel indirect quicksort. - * - *

- * The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley - * and M. Douglas McIlroy, “Engineering a Sort Function”, - * Software: Practice and Experience, 23(11), pages 1249−1265, - * 1993. - * - *

- * This method implement an indirect sort. The elements of - * perm (which must be exactly the numbers in the interval - * [0..perm.length)) will be permuted so that - * x[ perm[ i ] ] ≤ x[ perm[ i + 1 ] ]. - * - *

- * This implementation uses a {@link ForkJoinPool} executor service with - * {@link Runtime#availableProcessors()} parallel threads. - * - * @param perm - * a permutation array indexing {@code x}. - * @param x - * the array to be sorted. - * @param from - * the index of the first element (inclusive) to be sorted. - * @param to - * the index of the last element (exclusive) to be sorted. - */ - public static void parallelQuickSortIndirect(final int[] perm, - final int[] x, final int from, final int to) { - if (to - from < PARALLEL_QUICKSORT_NO_FORK) - quickSortIndirect(perm, x, from, to); - else { - final ForkJoinPool pool = new ForkJoinPool(Runtime.getRuntime() - .availableProcessors()); - pool.invoke(new ForkJoinQuickSortIndirect(perm, x, from, to)); - pool.shutdown(); - } - } - - /** - * Sorts an array according to the natural ascending order using a parallel - * indirect quicksort. - * - *

- * The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley - * and M. Douglas McIlroy, “Engineering a Sort Function”, - * Software: Practice and Experience, 23(11), pages 1249−1265, - * 1993. - * - *

- * This method implement an indirect sort. The elements of - * perm (which must be exactly the numbers in the interval - * [0..perm.length)) will be permuted so that - * x[ perm[ i ] ] ≤ x[ perm[ i + 1 ] ]. - * - *

- * This implementation uses a {@link ForkJoinPool} executor service with - * {@link Runtime#availableProcessors()} parallel threads. - * - * @param perm - * a permutation array indexing {@code x}. - * @param x - * the array to be sorted. - * - */ - public static void parallelQuickSortIndirect(final int perm[], final int[] x) { - parallelQuickSortIndirect(perm, x, 0, x.length); - } - - /** - * Stabilizes a permutation. - * - *

- * This method can be used to stabilize the permutation generated by an - * indirect sorting, assuming that initially the permutation array was in - * ascending order (e.g., the identity, as usually happens). This method - * scans the permutation, and for each non-singleton block of elements with - * the same associated values in {@code x}, permutes them in ascending order. - * The resulting permutation corresponds to a stable sort. - * - *

- * Usually combining an unstable indirect sort and this method is more - * efficient than using a stable sort, as most stable sort algorithms - * require a support array. - * - *

- * More precisely, assuming that - * x[ perm[ i ] ] ≤ x[ perm[ i + 1 ] ], after stabilization - * we will also have that x[ perm[ i ] ] = x[ perm[ i + 1 ] ] - * implies perm[ i ] ≤ perm[ i + 1 ]. - * - * @param perm - * a permutation array indexing {@code x} so that it is sorted. - * @param x - * the sorted array to be stabilized. - * @param from - * the index of the first element (inclusive) to be stabilized. - * @param to - * the index of the last element (exclusive) to be stabilized. - */ - public static void stabilize(final int perm[], final int[] x, - final int from, final int to) { - int curr = from; - for (int i = from + 1; i < to; i++) { - if (x[perm[i]] != x[perm[curr]]) { - if (i - curr > 1) - parallelQuickSort(perm, curr, i); - curr = i; - } - } - if (to - curr > 1) - parallelQuickSort(perm, curr, to); - } - - /** - * Stabilizes a permutation. - * - *

- * This method can be used to stabilize the permutation generated by an - * indirect sorting, assuming that initially the permutation array was in - * ascending order (e.g., the identity, as usually happens). This method - * scans the permutation, and for each non-singleton block of elements with - * the same associated values in {@code x}, permutes them in ascending order. - * The resulting permutation corresponds to a stable sort. - * - *

- * Usually combining an unstable indirect sort and this method is more - * efficient than using a stable sort, as most stable sort algorithms - * require a support array. - * - *

- * More precisely, assuming that - * x[ perm[ i ] ] ≤ x[ perm[ i + 1 ] ], after stabilization - * we will also have that x[ perm[ i ] ] = x[ perm[ i + 1 ] ] - * implies perm[ i ] ≤ perm[ i + 1 ]. - * - * @param perm - * a permutation array indexing {@code x} so that it is sorted. - * @param x - * the sorted array to be stabilized. - */ - public static void stabilize(final int perm[], final int[] x) { - stabilize(perm, x, 0, perm.length); - } - - private static int med3(final int x[], final int[] y, final int a, - final int b, final int c) { - int t; - final int ab = (t = (Integer.compare((x[a]), (x[b])))) == 0 ? (Integer - .compare((y[a]), (y[b]))) : t; - final int ac = (t = (Integer.compare((x[a]), (x[c])))) == 0 ? (Integer - .compare((y[a]), (y[c]))) : t; - final int bc = (t = (Integer.compare((x[b]), (x[c])))) == 0 ? (Integer - .compare((y[b]), (y[c]))) : t; - return (ab < 0 ? (bc < 0 ? b : ac < 0 ? c : a) : (bc > 0 ? b : ac > 0 - ? c - : a)); - } - - private static void swap(final int x[], final int[] y, final int a, - final int b) { - final int t = x[a]; - final int u = y[a]; - x[a] = x[b]; - y[a] = y[b]; - x[b] = t; - y[b] = u; - } - - private static void swap(final int[] x, final int[] y, int a, int b, - final int n) { - for (int i = 0; i < n; i++, a++, b++) - swap(x, y, a, b); - } - - private static void selectionSort(final int[] a, final int[] b, - final int from, final int to) { - for (int i = from; i < to - 1; i++) { - int m = i, u; - for (int j = i + 1; j < to; j++) - if ((u = (Integer.compare((a[j]), (a[m])))) < 0 || u == 0 - && ((b[j]) < (b[m]))) - m = j; - - if (m != i) { - int t = a[i]; - a[i] = a[m]; - a[m] = t; - t = b[i]; - b[i] = b[m]; - b[m] = t; - } - } - } - - /** - * Sorts the specified range of elements of two arrays according to the - * natural lexicographical ascending order using quicksort. - * - *

- * The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley - * and M. Douglas McIlroy, “Engineering a Sort Function”, - * Software: Practice and Experience, 23(11), pages 1249−1265, - * 1993. - * - *

- * This method implements a lexicographical sorting of the - * arguments. Pairs of elements in the same position in the two provided - * arrays will be considered a single key, and permuted accordingly. In the - * end, either x[ i ] < x[ i + 1 ] or x[ i ] - * == x[ i + 1 ] and y[ i ] ≤ y[ i + 1 ]. - * - * @param x - * the first array to be sorted. - * @param y - * the second array to be sorted. - * @param from - * the index of the first element (inclusive) to be sorted. - * @param to - * the index of the last element (exclusive) to be sorted. - */ - - public static void quickSort(final int[] x, final int[] y, final int from, - final int to) { - final int len = to - from; - if (len < QUICKSORT_NO_REC) { - selectionSort(x, y, from, to); - return; - } - // Choose a partition element, v - int m = from + len / 2; - int l = from; - int n = to - 1; - if (len > QUICKSORT_MEDIAN_OF_9) { // Big arrays, pseudomedian of 9 - int s = len / 8; - l = med3(x, y, l, l + s, l + 2 * s); - m = med3(x, y, m - s, m, m + s); - n = med3(x, y, n - 2 * s, n - s, n); - } - m = med3(x, y, l, m, n); // Mid-size, med of 3 - final int v = x[m], w = y[m]; - // Establish Invariant: v* (v)* v* - int a = from, b = a, c = to - 1, d = c; - while (true) { - int comparison, t; - while (b <= c - && (comparison = (t = (Integer.compare((x[b]), (v)))) == 0 - ? (Integer.compare((y[b]), (w))) - : t) <= 0) { - if (comparison == 0) - swap(x, y, a++, b); - b++; - } - while (c >= b - && (comparison = (t = (Integer.compare((x[c]), (v)))) == 0 - ? (Integer.compare((y[c]), (w))) - : t) >= 0) { - if (comparison == 0) - swap(x, y, c, d--); - c--; - } - if (b > c) - break; - swap(x, y, b++, c--); - } - // Swap partition elements back to middle - int s; - s = Math.min(a - from, b - a); - swap(x, y, from, b - s, s); - s = Math.min(d - c, to - d - 1); - swap(x, y, b, to - s, s); - // Recursively sort non-partition-elements - if ((s = b - a) > 1) - quickSort(x, y, from, from + s); - if ((s = d - c) > 1) - quickSort(x, y, to - s, to); - } - - /** - * Sorts two arrays according to the natural lexicographical ascending order - * using quicksort. - * - *

- * The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley - * and M. Douglas McIlroy, “Engineering a Sort Function”, - * Software: Practice and Experience, 23(11), pages 1249−1265, - * 1993. - * - *

- * This method implements a lexicographical sorting of the - * arguments. Pairs of elements in the same position in the two provided - * arrays will be considered a single key, and permuted accordingly. In the - * end, either x[ i ] < x[ i + 1 ] or x[ i ] - * == x[ i + 1 ] and y[ i ] ≤ y[ i + 1 ]. - * - * @param x - * the first array to be sorted. - * @param y - * the second array to be sorted. - */ - public static void quickSort(final int[] x, final int[] y) { - ensureSameLength(x, y); - quickSort(x, y, 0, x.length); - } - - protected static class ForkJoinQuickSort2 extends RecursiveAction { - private static final long serialVersionUID = 1L; - private final int from; - private final int to; - private final int[] x, y; - - public ForkJoinQuickSort2(final int[] x, final int[] y, final int from, - final int to) { - this.from = from; - this.to = to; - this.x = x; - this.y = y; - } - - @Override - protected void compute() { - final int[] x = this.x; - final int[] y = this.y; - final int len = to - from; - if (len < PARALLEL_QUICKSORT_NO_FORK) { - quickSort(x, y, from, to); - return; - } - // Choose a partition element, v - int m = from + len / 2; - int l = from; - int n = to - 1; - int s = len / 8; - l = med3(x, y, l, l + s, l + 2 * s); - m = med3(x, y, m - s, m, m + s); - n = med3(x, y, n - 2 * s, n - s, n); - m = med3(x, y, l, m, n); - final int v = x[m], w = y[m]; - // Establish Invariant: v* (v)* v* - int a = from, b = a, c = to - 1, d = c; - while (true) { - int comparison, t; - while (b <= c - && (comparison = (t = (Integer.compare((x[b]), (v)))) == 0 - ? (Integer.compare((y[b]), (w))) - : t) <= 0) { - if (comparison == 0) - swap(x, y, a++, b); - b++; - } - while (c >= b - && (comparison = (t = (Integer.compare((x[c]), (v)))) == 0 - ? (Integer.compare((y[c]), (w))) - : t) >= 0) { - if (comparison == 0) - swap(x, y, c, d--); - c--; - } - if (b > c) - break; - swap(x, y, b++, c--); - } - // Swap partition elements back to middle - int t; - s = Math.min(a - from, b - a); - swap(x, y, from, b - s, s); - s = Math.min(d - c, to - d - 1); - swap(x, y, b, to - s, s); - s = b - a; - t = d - c; - // Recursively sort non-partition-elements - if (s > 1 && t > 1) - invokeAll(new ForkJoinQuickSort2(x, y, from, from + s), - new ForkJoinQuickSort2(x, y, to - t, to)); - else if (s > 1) - invokeAll(new ForkJoinQuickSort2(x, y, from, from + s)); - else - invokeAll(new ForkJoinQuickSort2(x, y, to - t, to)); - } - } - - /** - * Sorts the specified range of elements of two arrays according to the - * natural lexicographical ascending order using a parallel quicksort. - * - *

- * The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley - * and M. Douglas McIlroy, “Engineering a Sort Function”, - * Software: Practice and Experience, 23(11), pages 1249−1265, - * 1993. - * - *

- * This method implements a lexicographical sorting of the - * arguments. Pairs of elements in the same position in the two provided - * arrays will be considered a single key, and permuted accordingly. In the - * end, either x[ i ] < x[ i + 1 ] or x[ i ] - * == x[ i + 1 ] and y[ i ] ≤ y[ i + 1 ]. - * - *

- * This implementation uses a {@link ForkJoinPool} executor service with - * {@link Runtime#availableProcessors()} parallel threads. - * - * @param x - * the first array to be sorted. - * @param y - * the second array to be sorted. - * @param from - * the index of the first element (inclusive) to be sorted. - * @param to - * the index of the last element (exclusive) to be sorted. - */ - public static void parallelQuickSort(final int[] x, final int[] y, - final int from, final int to) { - if (to - from < PARALLEL_QUICKSORT_NO_FORK) - quickSort(x, y, from, to); - final ForkJoinPool pool = new ForkJoinPool(Runtime.getRuntime() - .availableProcessors()); - pool.invoke(new ForkJoinQuickSort2(x, y, from, to)); - pool.shutdown(); - } - - /** - * Sorts two arrays according to the natural lexicographical ascending order - * using a parallel quicksort. - * - *

- * The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley - * and M. Douglas McIlroy, “Engineering a Sort Function”, - * Software: Practice and Experience, 23(11), pages 1249−1265, - * 1993. - * - *

- * This method implements a lexicographical sorting of the - * arguments. Pairs of elements in the same position in the two provided - * arrays will be considered a single key, and permuted accordingly. In the - * end, either x[ i ] < x[ i + 1 ] or x[ i ] - * == x[ i + 1 ] and y[ i ] ≤ y[ i + 1 ]. - * - *

- * This implementation uses a {@link ForkJoinPool} executor service with - * {@link Runtime#availableProcessors()} parallel threads. - * - * @param x - * the first array to be sorted. - * @param y - * the second array to be sorted. - */ - public static void parallelQuickSort(final int[] x, final int[] y) { - ensureSameLength(x, y); - parallelQuickSort(x, y, 0, x.length); - } - - /** - * Sorts the specified range of elements according to the natural ascending - * order using mergesort, using a given pre-filled support array. - * - *

- * This sort is guaranteed to be stable: equal elements will not be - * reordered as a result of the sort. Moreover, no support arrays will be - * allocated. - * - * @param a - * the array to be sorted. - * @param from - * the index of the first element (inclusive) to be sorted. - * @param to - * the index of the last element (exclusive) to be sorted. - * @param supp - * a support array containing at least to elements, - * and whose entries are identical to those of {@code a} in the - * specified range. - */ - - public static void mergeSort(final int a[], final int from, final int to, - final int supp[]) { - int len = to - from; - - // Insertion sort on smallest arrays - if (len < MERGESORT_NO_REC) { - insertionSort(a, from, to); - return; - } - - // Recursively sort halves of a into supp - final int mid = (from + to) >>> 1; - mergeSort(supp, from, mid, a); - mergeSort(supp, mid, to, a); - - // If list is already sorted, just copy from supp to a. This is an - // optimization that results in faster sorts for nearly ordered lists. - if (((supp[mid - 1]) <= (supp[mid]))) { - System.arraycopy(supp, from, a, from, len); - return; - } - - // Merge sorted halves (now in supp) into a - for (int i = from, p = from, q = mid; i < to; i++) { - if (q >= to || p < mid && ((supp[p]) <= (supp[q]))) - a[i] = supp[p++]; - else - a[i] = supp[q++]; - } - } - - /** - * Sorts the specified range of elements according to the natural ascending - * order using mergesort. - * - *

- * This sort is guaranteed to be stable: equal elements will not be - * reordered as a result of the sort. An array as large as a - * will be allocated by this method. - * - * @param a - * the array to be sorted. - * @param from - * the index of the first element (inclusive) to be sorted. - * @param to - * the index of the last element (exclusive) to be sorted. - */ - public static void mergeSort(final int a[], final int from, final int to) { - mergeSort(a, from, to, a.clone()); - } - - /** - * Sorts an array according to the natural ascending order using mergesort. - * - *

- * This sort is guaranteed to be stable: equal elements will not be - * reordered as a result of the sort. An array as large as a - * will be allocated by this method. - * - * @param a - * the array to be sorted. - */ - public static void mergeSort(final int a[]) { - mergeSort(a, 0, a.length); - } - - /** - * Sorts the specified range of elements according to the order induced by - * the specified comparator using mergesort, using a given pre-filled - * support array. - * - *

- * This sort is guaranteed to be stable: equal elements will not be - * reordered as a result of the sort. Moreover, no support arrays will be - * allocated. - * - * @param a - * the array to be sorted. - * @param from - * the index of the first element (inclusive) to be sorted. - * @param to - * the index of the last element (exclusive) to be sorted. - * @param comp - * the comparator to determine the sorting order. - * @param supp - * a support array containing at least to elements, - * and whose entries are identical to those of {@code a} in the - * specified range. - */ - public static void mergeSort(final int a[], final int from, final int to, - IntComparator comp, final int supp[]) { - int len = to - from; - - // Insertion sort on smallest arrays - if (len < MERGESORT_NO_REC) { - insertionSort(a, from, to, comp); - return; - } - - // Recursively sort halves of a into supp - final int mid = (from + to) >>> 1; - mergeSort(supp, from, mid, comp, a); - mergeSort(supp, mid, to, comp, a); - - // If list is already sorted, just copy from supp to a. This is an - // optimization that results in faster sorts for nearly ordered lists. - if (comp.compare(supp[mid - 1], supp[mid]) <= 0) { - System.arraycopy(supp, from, a, from, len); - return; - } - - // Merge sorted halves (now in supp) into a - for (int i = from, p = from, q = mid; i < to; i++) { - if (q >= to || p < mid && comp.compare(supp[p], supp[q]) <= 0) - a[i] = supp[p++]; - else - a[i] = supp[q++]; - } - } - - /** - * Sorts the specified range of elements according to the order induced by - * the specified comparator using mergesort. - * - *

- * This sort is guaranteed to be stable: equal elements will not be - * reordered as a result of the sort. An array as large as a - * will be allocated by this method. - * - * @param a - * the array to be sorted. - * @param from - * the index of the first element (inclusive) to be sorted. - * @param to - * the index of the last element (exclusive) to be sorted. - * @param comp - * the comparator to determine the sorting order. - */ - public static void mergeSort(final int a[], final int from, final int to, - IntComparator comp) { - mergeSort(a, from, to, comp, a.clone()); - } - - /** - * Sorts an array according to the order induced by the specified comparator - * using mergesort. - * - *

- * This sort is guaranteed to be stable: equal elements will not be - * reordered as a result of the sort. An array as large as a - * will be allocated by this method. - * - * @param a - * the array to be sorted. - * @param comp - * the comparator to determine the sorting order. - */ - public static void mergeSort(final int a[], IntComparator comp) { - mergeSort(a, 0, a.length, comp); - } - - /** - * Searches a range of the specified array for the specified value using the - * binary search algorithm. The range must be sorted prior to making this - * call. If it is not sorted, the results are undefined. If the range - * contains multiple elements with the specified value, there is no - * guarantee which one will be found. - * - * @param a - * the array to be searched. - * @param from - * the index of the first element (inclusive) to be searched. - * @param to - * the index of the last element (exclusive) to be searched. - * @param key - * the value to be searched for. - * @return index of the search key, if it is contained in the array; - * otherwise, (-(insertion point) - 1). The - * insertion point is defined as the the point at which the - * value would be inserted into the array: the index of the first - * element greater than the key, or the length of the array, if all - * elements in the array are less than the specified key. Note that - * this guarantees that the return value will be ≥ 0 if and only - * if the key is found. - * @see java.util.Arrays - */ - - public static int binarySearch(final int[] a, int from, int to, - final int key) { - int midVal; - to--; - while (from <= to) { - final int mid = (from + to) >>> 1; - midVal = a[mid]; - - if (midVal < key) - from = mid + 1; - else if (midVal > key) - to = mid - 1; - else - return mid; - - } - return -(from + 1); - } - - /** - * Searches an array for the specified value using the binary search - * algorithm. The range must be sorted prior to making this call. If it is - * not sorted, the results are undefined. If the range contains multiple - * elements with the specified value, there is no guarantee which one will - * be found. - * - * @param a - * the array to be searched. - * @param key - * the value to be searched for. - * @return index of the search key, if it is contained in the array; - * otherwise, (-(insertion point) - 1). The - * insertion point is defined as the the point at which the - * value would be inserted into the array: the index of the first - * element greater than the key, or the length of the array, if all - * elements in the array are less than the specified key. Note that - * this guarantees that the return value will be ≥ 0 if and only - * if the key is found. - * @see java.util.Arrays - */ - public static int binarySearch(final int[] a, final int key) { - return binarySearch(a, 0, a.length, key); - } - - /** - * Searches a range of the specified array for the specified value using the - * binary search algorithm and a specified comparator. The range must be - * sorted following the comparator prior to making this call. If it is not - * sorted, the results are undefined. If the range contains multiple - * elements with the specified value, there is no guarantee which one will - * be found. - * - * @param a - * the array to be searched. - * @param from - * the index of the first element (inclusive) to be searched. - * @param to - * the index of the last element (exclusive) to be searched. - * @param key - * the value to be searched for. - * @param c - * a comparator. - * @return index of the search key, if it is contained in the array; - * otherwise, (-(insertion point) - 1). The - * insertion point is defined as the the point at which the - * value would be inserted into the array: the index of the first - * element greater than the key, or the length of the array, if all - * elements in the array are less than the specified key. Note that - * this guarantees that the return value will be ≥ 0 if and only - * if the key is found. - * @see java.util.Arrays - */ - public static int binarySearch(final int[] a, int from, int to, - final int key, final IntComparator c) { - int midVal; - to--; - while (from <= to) { - final int mid = (from + to) >>> 1; - midVal = a[mid]; - final int cmp = c.compare(midVal, key); - if (cmp < 0) - from = mid + 1; - else if (cmp > 0) - to = mid - 1; - else - return mid; // key found - } - return -(from + 1); - } - - /** - * Searches an array for the specified value using the binary search - * algorithm and a specified comparator. The range must be sorted following - * the comparator prior to making this call. If it is not sorted, the - * results are undefined. If the range contains multiple elements with the - * specified value, there is no guarantee which one will be found. - * - * @param a - * the array to be searched. - * @param key - * the value to be searched for. - * @param c - * a comparator. - * @return index of the search key, if it is contained in the array; - * otherwise, (-(insertion point) - 1). The - * insertion point is defined as the the point at which the - * value would be inserted into the array: the index of the first - * element greater than the key, or the length of the array, if all - * elements in the array are less than the specified key. Note that - * this guarantees that the return value will be ≥ 0 if and only - * if the key is found. - * @see java.util.Arrays - */ - public static int binarySearch(final int[] a, final int key, - final IntComparator c) { - return binarySearch(a, 0, a.length, key, c); - } - - /** The size of a digit used during radix sort (must be a power of 2). */ - private static final int DIGIT_BITS = 8; - /** The mask to extract a digit of {@link #DIGIT_BITS} bits. */ - private static final int DIGIT_MASK = (1 << DIGIT_BITS) - 1; - /** The number of digits per element. */ - private static final int DIGITS_PER_ELEMENT = Integer.SIZE / DIGIT_BITS; - private static final int RADIXSORT_NO_REC = 1024; - private static final int PARALLEL_RADIXSORT_NO_FORK = 1024; - - /** - * This method fixes negative numbers so that the combination - * exponent/significand is lexicographically sorted. - */ - /** - * Sorts the specified array using radix sort. - * - *

- * The sorting algorithm is a tuned radix sort adapted from Peter M. - * McIlroy, Keith Bostic and M. Douglas McIlroy, “Engineering radix - * sort”, Computing Systems, 6(1), pages 5−27 (1993). - * - *

- * This implementation is significantly faster than quicksort already at - * small sizes (say, more than 10000 elements), but it can only sort in - * ascending order. - * - * @param a - * the array to be sorted. - */ - public static void radixSort(final int[] a) { - radixSort(a, 0, a.length); - } - - /** - * Sorts the specified range of an array using radix sort. - * - *

- * The sorting algorithm is a tuned radix sort adapted from Peter M. - * McIlroy, Keith Bostic and M. Douglas McIlroy, “Engineering radix - * sort”, Computing Systems, 6(1), pages 5−27 (1993). - * - *

- * This implementation is significantly faster than quicksort already at - * small sizes (say, more than 10000 elements), but it can only sort in - * ascending order. - * - * @param a - * the array to be sorted. - * @param from - * the index of the first element (inclusive) to be sorted. - * @param to - * the index of the last element (exclusive) to be sorted. - */ - public static void radixSort(final int[] a, final int from, final int to) { - if (to - from < RADIXSORT_NO_REC) { - quickSort(a, from, to); - return; - } - - final int maxLevel = DIGITS_PER_ELEMENT - 1; - - final int stackSize = ((1 << DIGIT_BITS) - 1) - * (DIGITS_PER_ELEMENT - 1) + 1; - int stackPos = 0; - final int[] offsetStack = new int[stackSize]; - final int[] lengthStack = new int[stackSize]; - final int[] levelStack = new int[stackSize]; - - offsetStack[stackPos] = from; - lengthStack[stackPos] = to - from; - levelStack[stackPos++] = 0; - - final int[] count = new int[1 << DIGIT_BITS]; - final int[] pos = new int[1 << DIGIT_BITS]; - - while (stackPos > 0) { - final int first = offsetStack[--stackPos]; - final int length = lengthStack[stackPos]; - final int level = levelStack[stackPos]; - - final int signMask = level % DIGITS_PER_ELEMENT == 0 - ? 1 << DIGIT_BITS - 1 - : 0; - - final int shift = (DIGITS_PER_ELEMENT - 1 - level - % DIGITS_PER_ELEMENT) - * DIGIT_BITS; // This is the shift that extract the right - // byte from a key - - // Count keys. - for (int i = first + length; i-- != first;) - count[((a[i]) >>> shift & DIGIT_MASK ^ signMask)]++; - // Compute cumulative distribution - int lastUsed = -1; - for (int i = 0, p = first; i < 1 << DIGIT_BITS; i++) { - if (count[i] != 0) - lastUsed = i; - pos[i] = (p += count[i]); - } - - final int end = first + length - count[lastUsed]; - // i moves through the start of each block - for (int i = first, c = -1, d; i <= end; i += count[c], count[c] = 0) { - int t = a[i]; - c = ((t) >>> shift & DIGIT_MASK ^ signMask); - - if (i < end) { // When all slots are OK, the last slot is - // necessarily OK. - while ((d = --pos[c]) > i) { - final int z = t; - t = a[d]; - a[d] = z; - c = ((t) >>> shift & DIGIT_MASK ^ signMask); - } - a[i] = t; - } - - if (level < maxLevel && count[c] > 1) { - if (count[c] < RADIXSORT_NO_REC) - quickSort(a, i, i + count[c]); - else { - offsetStack[stackPos] = i; - lengthStack[stackPos] = count[c]; - levelStack[stackPos++] = level + 1; - } - } - } - } - } - - protected final static class Segment { - protected final int offset, length, level; - protected Segment(final int offset, final int length, final int level) { - this.offset = offset; - this.length = length; - this.level = level; - } - - @Override - public String toString() { - return "Segment [offset=" + offset + ", length=" + length - + ", level=" + level + "]"; - } - } - - protected final static Segment POISON_PILL = new Segment(-1, -1, -1); - - /** - * Sorts the specified range of an array using parallel radix sort. - * - *

- * The sorting algorithm is a tuned radix sort adapted from Peter M. - * McIlroy, Keith Bostic and M. Douglas McIlroy, “Engineering radix - * sort”, Computing Systems, 6(1), pages 5−27 (1993). - * - *

- * This implementation uses a pool of {@link Runtime#availableProcessors()} - * threads. - * - * @param a - * the array to be sorted. - * @param from - * the index of the first element (inclusive) to be sorted. - * @param to - * the index of the last element (exclusive) to be sorted. - */ - public static void parallelRadixSort(final int[] a, final int from, - final int to) { - if (to - from < PARALLEL_RADIXSORT_NO_FORK) { - quickSort(a, from, to); - return; - } - final int maxLevel = DIGITS_PER_ELEMENT - 1; - final LinkedBlockingQueue queue = new LinkedBlockingQueue(); - queue.add(new Segment(from, to - from, 0)); - final AtomicInteger queueSize = new AtomicInteger(1); - final int numberOfThreads = Runtime.getRuntime().availableProcessors(); - final ExecutorService executorService = Executors.newFixedThreadPool( - numberOfThreads, Executors.defaultThreadFactory()); - final ExecutorCompletionService executorCompletionService = new ExecutorCompletionService( - executorService); - - for (int i = numberOfThreads; i-- != 0;) - executorCompletionService.submit(new Callable() { - public Void call() throws Exception { - final int[] count = new int[1 << DIGIT_BITS]; - final int[] pos = new int[1 << DIGIT_BITS]; - - for (;;) { - if (queueSize.get() == 0) - for (int i = numberOfThreads; i-- != 0;) - queue.add(POISON_PILL); - final Segment segment = queue.take(); - if (segment == POISON_PILL) - return null; - - final int first = segment.offset; - final int length = segment.length; - final int level = segment.level; - - final int signMask = level % DIGITS_PER_ELEMENT == 0 - ? 1 << DIGIT_BITS - 1 - : 0; - - final int shift = (DIGITS_PER_ELEMENT - 1 - level - % DIGITS_PER_ELEMENT) - * DIGIT_BITS; // This is the shift that extract - // the right byte from a key - - // Count keys. - for (int i = first + length; i-- != first;) - count[((a[i]) >>> shift & DIGIT_MASK ^ signMask)]++; - // Compute cumulative distribution - int lastUsed = -1; - for (int i = 0, p = first; i < 1 << DIGIT_BITS; i++) { - if (count[i] != 0) - lastUsed = i; - pos[i] = (p += count[i]); - } - - final int end = first + length - count[lastUsed]; - // i moves through the start of each block - for (int i = first, c = -1, d; i <= end; i += count[c], count[c] = 0) { - int t = a[i]; - c = ((t) >>> shift & DIGIT_MASK ^ signMask); - if (i < end) { - while ((d = --pos[c]) > i) { - final int z = t; - t = a[d]; - a[d] = z; - c = ((t) >>> shift & DIGIT_MASK ^ signMask); - } - a[i] = t; - } - - if (level < maxLevel && count[c] > 1) { - if (count[c] < PARALLEL_RADIXSORT_NO_FORK) - quickSort(a, i, i + count[c]); - else { - queueSize.incrementAndGet(); - queue.add(new Segment(i, count[c], - level + 1)); - } - } - } - queueSize.decrementAndGet(); - } - } - }); - - Throwable problem = null; - for (int i = numberOfThreads; i-- != 0;) - try { - executorCompletionService.take().get(); - } catch (Exception e) { - problem = e.getCause(); // We keep only the last one. They will - // be logged anyway. - } - - executorService.shutdown(); - if (problem != null) - throw (problem instanceof RuntimeException) - ? (RuntimeException) problem - : new RuntimeException(problem); - } - - /** - * Sorts the specified array using parallel radix sort. - * - *

- * The sorting algorithm is a tuned radix sort adapted from Peter M. - * McIlroy, Keith Bostic and M. Douglas McIlroy, “Engineering radix - * sort”, Computing Systems, 6(1), pages 5−27 (1993). - * - *

- * This implementation uses a pool of {@link Runtime#availableProcessors()} - * threads. - * - * @param a - * the array to be sorted. - */ - public static void parallelRadixSort(final int[] a) { - parallelRadixSort(a, 0, a.length); - } - - /** - * Sorts the specified array using indirect radix sort. - * - *

- * The sorting algorithm is a tuned radix sort adapted from Peter M. - * McIlroy, Keith Bostic and M. Douglas McIlroy, “Engineering radix - * sort”, Computing Systems, 6(1), pages 5−27 (1993). - * - *

- * This method implement an indirect sort. The elements of - * perm (which must be exactly the numbers in the interval - * [0..perm.length)) will be permuted so that - * a[ perm[ i ] ] ≤ a[ perm[ i + 1 ] ]. - * - *

- * This implementation will allocate, in the stable case, a support array as - * large as perm (note that the stable version is slightly - * faster). - * - * @param perm - * a permutation array indexing a. - * @param a - * the array to be sorted. - * @param stable - * whether the sorting algorithm should be stable. - */ - public static void radixSortIndirect(final int[] perm, final int[] a, - final boolean stable) { - radixSortIndirect(perm, a, 0, perm.length, stable); - } - - /** - * Sorts the specified array using indirect radix sort. - * - *

- * The sorting algorithm is a tuned radix sort adapted from Peter M. - * McIlroy, Keith Bostic and M. Douglas McIlroy, “Engineering radix - * sort”, Computing Systems, 6(1), pages 5−27 (1993). - * - *

- * This method implement an indirect sort. The elements of - * perm (which must be exactly the numbers in the interval - * [0..perm.length)) will be permuted so that - * a[ perm[ i ] ] ≤ a[ perm[ i + 1 ] ]. - * - *

- * This implementation will allocate, in the stable case, a support array as - * large as perm (note that the stable version is slightly - * faster). - * - * @param perm - * a permutation array indexing a. - * @param a - * the array to be sorted. - * @param from - * the index of the first element of perm - * (inclusive) to be permuted. - * @param to - * the index of the last element of perm (exclusive) - * to be permuted. - * @param stable - * whether the sorting algorithm should be stable. - */ - public static void radixSortIndirect(final int[] perm, final int[] a, - final int from, final int to, final boolean stable) { - if (to - from < RADIXSORT_NO_REC) { - insertionSortIndirect(perm, a, from, to); - return; - } - - final int maxLevel = DIGITS_PER_ELEMENT - 1; - - final int stackSize = ((1 << DIGIT_BITS) - 1) - * (DIGITS_PER_ELEMENT - 1) + 1; - int stackPos = 0; - final int[] offsetStack = new int[stackSize]; - final int[] lengthStack = new int[stackSize]; - final int[] levelStack = new int[stackSize]; - - offsetStack[stackPos] = from; - lengthStack[stackPos] = to - from; - levelStack[stackPos++] = 0; - - final int[] count = new int[1 << DIGIT_BITS]; - final int[] pos = new int[1 << DIGIT_BITS]; - final int[] support = stable ? new int[perm.length] : null; - - while (stackPos > 0) { - final int first = offsetStack[--stackPos]; - final int length = lengthStack[stackPos]; - final int level = levelStack[stackPos]; - - final int signMask = level % DIGITS_PER_ELEMENT == 0 - ? 1 << DIGIT_BITS - 1 - : 0; - - final int shift = (DIGITS_PER_ELEMENT - 1 - level - % DIGITS_PER_ELEMENT) - * DIGIT_BITS; // This is the shift that extract the right - // byte from a key - - // Count keys. - for (int i = first + length; i-- != first;) - count[((a[perm[i]]) >>> shift & DIGIT_MASK ^ signMask)]++; - // Compute cumulative distribution - int lastUsed = -1; - for (int i = 0, p = stable ? 0 : first; i < 1 << DIGIT_BITS; i++) { - if (count[i] != 0) - lastUsed = i; - pos[i] = (p += count[i]); - } - - if (stable) { - for (int i = first + length; i-- != first;) - support[--pos[((a[perm[i]]) >>> shift & DIGIT_MASK ^ signMask)]] = perm[i]; - System.arraycopy(support, 0, perm, first, length); - for (int i = 0, p = first; i <= lastUsed; i++) { - if (level < maxLevel && count[i] > 1) { - if (count[i] < RADIXSORT_NO_REC) - insertionSortIndirect(perm, a, p, p + count[i]); - else { - offsetStack[stackPos] = p; - lengthStack[stackPos] = count[i]; - levelStack[stackPos++] = level + 1; - } - } - p += count[i]; - } - java.util.Arrays.fill(count, 0); - } else { - final int end = first + length - count[lastUsed]; - // i moves through the start of each block - for (int i = first, c = -1, d; i <= end; i += count[c], count[c] = 0) { - int t = perm[i]; - c = ((a[t]) >>> shift & DIGIT_MASK ^ signMask); - - if (i < end) { // When all slots are OK, the last slot is - // necessarily OK. - while ((d = --pos[c]) > i) { - final int z = t; - t = perm[d]; - perm[d] = z; - c = ((a[t]) >>> shift & DIGIT_MASK ^ signMask); - } - perm[i] = t; - } - - if (level < maxLevel && count[c] > 1) { - if (count[c] < RADIXSORT_NO_REC) - insertionSortIndirect(perm, a, i, i + count[c]); - else { - offsetStack[stackPos] = i; - lengthStack[stackPos] = count[c]; - levelStack[stackPos++] = level + 1; - } - } - } - } - } - } - - /** - * Sorts the specified range of an array using parallel indirect radix sort. - * - *

- * The sorting algorithm is a tuned radix sort adapted from Peter M. - * McIlroy, Keith Bostic and M. Douglas McIlroy, “Engineering radix - * sort”, Computing Systems, 6(1), pages 5−27 (1993). - * - *

- * This method implement an indirect sort. The elements of - * perm (which must be exactly the numbers in the interval - * [0..perm.length)) will be permuted so that - * a[ perm[ i ] ] ≤ a[ perm[ i + 1 ] ]. - * - *

- * This implementation uses a pool of {@link Runtime#availableProcessors()} - * threads. - * - * @param perm - * a permutation array indexing a. - * @param a - * the array to be sorted. - * @param from - * the index of the first element (inclusive) to be sorted. - * @param to - * the index of the last element (exclusive) to be sorted. - * @param stable - * whether the sorting algorithm should be stable. - */ - public static void parallelRadixSortIndirect(final int perm[], - final int[] a, final int from, final int to, final boolean stable) { - if (to - from < PARALLEL_RADIXSORT_NO_FORK) { - radixSortIndirect(perm, a, from, to, stable); - return; - } - final int maxLevel = DIGITS_PER_ELEMENT - 1; - final LinkedBlockingQueue queue = new LinkedBlockingQueue(); - queue.add(new Segment(from, to - from, 0)); - final AtomicInteger queueSize = new AtomicInteger(1); - final int numberOfThreads = Runtime.getRuntime().availableProcessors(); - final ExecutorService executorService = Executors.newFixedThreadPool( - numberOfThreads, Executors.defaultThreadFactory()); - final ExecutorCompletionService executorCompletionService = new ExecutorCompletionService( - executorService); - final int[] support = stable ? new int[perm.length] : null; - - for (int i = numberOfThreads; i-- != 0;) - executorCompletionService.submit(new Callable() { - public Void call() throws Exception { - final int[] count = new int[1 << DIGIT_BITS]; - final int[] pos = new int[1 << DIGIT_BITS]; - - for (;;) { - if (queueSize.get() == 0) - for (int i = numberOfThreads; i-- != 0;) - queue.add(POISON_PILL); - final Segment segment = queue.take(); - if (segment == POISON_PILL) - return null; - - final int first = segment.offset; - final int length = segment.length; - final int level = segment.level; - - final int signMask = level % DIGITS_PER_ELEMENT == 0 - ? 1 << DIGIT_BITS - 1 - : 0; - - final int shift = (DIGITS_PER_ELEMENT - 1 - level - % DIGITS_PER_ELEMENT) - * DIGIT_BITS; // This is the shift that extract - // the right byte from a key - - // Count keys. - for (int i = first + length; i-- != first;) - count[((a[perm[i]]) >>> shift & DIGIT_MASK ^ signMask)]++; - // Compute cumulative distribution - int lastUsed = -1; - for (int i = 0, p = first; i < 1 << DIGIT_BITS; i++) { - if (count[i] != 0) - lastUsed = i; - pos[i] = (p += count[i]); - } - - if (stable) { - for (int i = first + length; i-- != first;) - support[--pos[((a[perm[i]]) >>> shift - & DIGIT_MASK ^ signMask)]] = perm[i]; - System.arraycopy(support, first, perm, first, - length); - for (int i = 0, p = first; i <= lastUsed; i++) { - if (level < maxLevel && count[i] > 1) { - if (count[i] < PARALLEL_RADIXSORT_NO_FORK) - radixSortIndirect(perm, a, p, p - + count[i], stable); - else { - queueSize.incrementAndGet(); - queue.add(new Segment(p, count[i], - level + 1)); - } - } - p += count[i]; - } - java.util.Arrays.fill(count, 0); - } else { - final int end = first + length - count[lastUsed]; - // i moves through the start of each block - for (int i = first, c = -1, d; i <= end; i += count[c], count[c] = 0) { - int t = perm[i]; - c = ((a[t]) >>> shift & DIGIT_MASK ^ signMask); - - if (i < end) { // When all slots are OK, the - // last slot is necessarily OK. - while ((d = --pos[c]) > i) { - final int z = t; - t = perm[d]; - perm[d] = z; - c = ((a[t]) >>> shift & DIGIT_MASK ^ signMask); - } - perm[i] = t; - } - - if (level < maxLevel && count[c] > 1) { - if (count[c] < PARALLEL_RADIXSORT_NO_FORK) - radixSortIndirect(perm, a, i, i - + count[c], stable); - else { - queueSize.incrementAndGet(); - queue.add(new Segment(i, count[c], - level + 1)); - } - } - } - } - queueSize.decrementAndGet(); - } - } - }); - - Throwable problem = null; - for (int i = numberOfThreads; i-- != 0;) - try { - executorCompletionService.take().get(); - } catch (Exception e) { - problem = e.getCause(); // We keep only the last one. They will - // be logged anyway. - } - - executorService.shutdown(); - if (problem != null) - throw (problem instanceof RuntimeException) - ? (RuntimeException) problem - : new RuntimeException(problem); - } - - /** - * Sorts the specified array using parallel indirect radix sort. - * - *

- * The sorting algorithm is a tuned radix sort adapted from Peter M. - * McIlroy, Keith Bostic and M. Douglas McIlroy, “Engineering radix - * sort”, Computing Systems, 6(1), pages 5−27 (1993). - * - *

- * This method implement an indirect sort. The elements of - * perm (which must be exactly the numbers in the interval - * [0..perm.length)) will be permuted so that - * a[ perm[ i ] ] ≤ a[ perm[ i + 1 ] ]. - * - *

- * This implementation uses a pool of {@link Runtime#availableProcessors()} - * threads. - * - * @param perm - * a permutation array indexing a. - * @param a - * the array to be sorted. - * @param stable - * whether the sorting algorithm should be stable. - */ - public static void parallelRadixSortIndirect(final int perm[], - final int[] a, final boolean stable) { - parallelRadixSortIndirect(perm, a, 0, a.length, stable); - } - - /** - * Sorts the specified pair of arrays lexicographically using radix sort. - *

- * The sorting algorithm is a tuned radix sort adapted from Peter M. - * McIlroy, Keith Bostic and M. Douglas McIlroy, “Engineering radix - * sort”, Computing Systems, 6(1), pages 5−27 (1993). - * - *

- * This method implements a lexicographical sorting of the - * arguments. Pairs of elements in the same position in the two provided - * arrays will be considered a single key, and permuted accordingly. In the - * end, either a[ i ] < a[ i + 1 ] or - * a[ i ] == a[ i + 1 ] and b[ i ] ≤ b[ i + 1 ]. - * - * @param a - * the first array to be sorted. - * @param b - * the second array to be sorted. - */ - - public static void radixSort(final int[] a, final int[] b) { - ensureSameLength(a, b); - radixSort(a, b, 0, a.length); - } - - /** - * Sorts the specified range of elements of two arrays using radix sort. - * - *

- * The sorting algorithm is a tuned radix sort adapted from Peter M. - * McIlroy, Keith Bostic and M. Douglas McIlroy, “Engineering radix - * sort”, Computing Systems, 6(1), pages 5−27 (1993). - * - *

- * This method implements a lexicographical sorting of the - * arguments. Pairs of elements in the same position in the two provided - * arrays will be considered a single key, and permuted accordingly. In the - * end, either a[ i ] < a[ i + 1 ] or - * a[ i ] == a[ i + 1 ] and b[ i ] ≤ b[ i + 1 ]. - * - * @param a - * the first array to be sorted. - * @param b - * the second array to be sorted. - * @param from - * the index of the first element (inclusive) to be sorted. - * @param to - * the index of the last element (exclusive) to be sorted. - */ - public static void radixSort(final int[] a, final int[] b, final int from, - final int to) { - if (to - from < RADIXSORT_NO_REC) { - selectionSort(a, b, from, to); - return; - } - - final int layers = 2; - final int maxLevel = DIGITS_PER_ELEMENT * layers - 1; - - final int stackSize = ((1 << DIGIT_BITS) - 1) - * (layers * DIGITS_PER_ELEMENT - 1) + 1; - int stackPos = 0; - final int[] offsetStack = new int[stackSize]; - final int[] lengthStack = new int[stackSize]; - final int[] levelStack = new int[stackSize]; - - offsetStack[stackPos] = from; - lengthStack[stackPos] = to - from; - levelStack[stackPos++] = 0; - - final int[] count = new int[1 << DIGIT_BITS]; - final int[] pos = new int[1 << DIGIT_BITS]; - - while (stackPos > 0) { - final int first = offsetStack[--stackPos]; - final int length = lengthStack[stackPos]; - final int level = levelStack[stackPos]; - - final int signMask = level % DIGITS_PER_ELEMENT == 0 - ? 1 << DIGIT_BITS - 1 - : 0; - - final int[] k = level < DIGITS_PER_ELEMENT ? a : b; // This is the - // key array - final int shift = (DIGITS_PER_ELEMENT - 1 - level - % DIGITS_PER_ELEMENT) - * DIGIT_BITS; // This is the shift that extract the right - // byte from a key - - // Count keys. - for (int i = first + length; i-- != first;) - count[((k[i]) >>> shift & DIGIT_MASK ^ signMask)]++; - - // Compute cumulative distribution - int lastUsed = -1; - for (int i = 0, p = first; i < 1 << DIGIT_BITS; i++) { - if (count[i] != 0) - lastUsed = i; - pos[i] = (p += count[i]); - } - - final int end = first + length - count[lastUsed]; - // i moves through the start of each block - for (int i = first, c = -1, d; i <= end; i += count[c], count[c] = 0) { - int t = a[i]; - int u = b[i]; - c = ((k[i]) >>> shift & DIGIT_MASK ^ signMask); - - if (i < end) { // When all slots are OK, the last slot is - // necessarily OK. - while ((d = --pos[c]) > i) { - c = ((k[d]) >>> shift & DIGIT_MASK ^ signMask); - int z = t; - t = a[d]; - a[d] = z; - z = u; - u = b[d]; - b[d] = z; - } - a[i] = t; - b[i] = u; - - } - - if (level < maxLevel && count[c] > 1) { - if (count[c] < RADIXSORT_NO_REC) - selectionSort(a, b, i, i + count[c]); - else { - offsetStack[stackPos] = i; - lengthStack[stackPos] = count[c]; - levelStack[stackPos++] = level + 1; - } - } - } - } - } - - /** - * Sorts the specified range of elements of two arrays using a parallel - * radix sort. - * - *

- * The sorting algorithm is a tuned radix sort adapted from Peter M. - * McIlroy, Keith Bostic and M. Douglas McIlroy, “Engineering radix - * sort”, Computing Systems, 6(1), pages 5−27 (1993). - * - *

- * This method implements a lexicographical sorting of the - * arguments. Pairs of elements in the same position in the two provided - * arrays will be considered a single key, and permuted accordingly. In the - * end, either a[ i ] < a[ i + 1 ] or - * a[ i ] == a[ i + 1 ] and b[ i ] ≤ b[ i + 1 ]. - * - *

- * This implementation uses a pool of {@link Runtime#availableProcessors()} - * threads. - * - * @param a - * the first array to be sorted. - * @param b - * the second array to be sorted. - * @param from - * the index of the first element (inclusive) to be sorted. - * @param to - * the index of the last element (exclusive) to be sorted. - */ - public static void parallelRadixSort(final int[] a, final int[] b, - final int from, final int to) { - if (to - from < PARALLEL_RADIXSORT_NO_FORK) { - quickSort(a, b, from, to); - return; - } - final int layers = 2; - if (a.length != b.length) - throw new IllegalArgumentException("Array size mismatch."); - final int maxLevel = DIGITS_PER_ELEMENT * layers - 1; - final LinkedBlockingQueue queue = new LinkedBlockingQueue(); - queue.add(new Segment(from, to - from, 0)); - final AtomicInteger queueSize = new AtomicInteger(1); - final int numberOfThreads = Runtime.getRuntime().availableProcessors(); - final ExecutorService executorService = Executors.newFixedThreadPool( - numberOfThreads, Executors.defaultThreadFactory()); - final ExecutorCompletionService executorCompletionService = new ExecutorCompletionService( - executorService); - for (int i = numberOfThreads; i-- != 0;) - executorCompletionService.submit(new Callable() { - public Void call() throws Exception { - final int[] count = new int[1 << DIGIT_BITS]; - final int[] pos = new int[1 << DIGIT_BITS]; - for (;;) { - if (queueSize.get() == 0) - for (int i = numberOfThreads; i-- != 0;) - queue.add(POISON_PILL); - final Segment segment = queue.take(); - if (segment == POISON_PILL) - return null; - final int first = segment.offset; - final int length = segment.length; - final int level = segment.level; - final int signMask = level % DIGITS_PER_ELEMENT == 0 - ? 1 << DIGIT_BITS - 1 - : 0; - final int[] k = level < DIGITS_PER_ELEMENT ? a : b; // This - // is - // the - // key - // array - final int shift = (DIGITS_PER_ELEMENT - 1 - level - % DIGITS_PER_ELEMENT) - * DIGIT_BITS; - // Count keys. - for (int i = first + length; i-- != first;) - count[((k[i]) >>> shift & DIGIT_MASK ^ signMask)]++; - // Compute cumulative distribution - int lastUsed = -1; - for (int i = 0, p = first; i < 1 << DIGIT_BITS; i++) { - if (count[i] != 0) - lastUsed = i; - pos[i] = (p += count[i]); - } - final int end = first + length - count[lastUsed]; - for (int i = first, c = -1, d; i <= end; i += count[c], count[c] = 0) { - int t = a[i]; - int u = b[i]; - c = ((k[i]) >>> shift & DIGIT_MASK ^ signMask); - if (i < end) { // When all slots are OK, the last - // slot is necessarily OK. - while ((d = --pos[c]) > i) { - c = ((k[d]) >>> shift & DIGIT_MASK ^ signMask); - final int z = t; - final int w = u; - t = a[d]; - u = b[d]; - a[d] = z; - b[d] = w; - } - a[i] = t; - b[i] = u; - } - if (level < maxLevel && count[c] > 1) { - if (count[c] < PARALLEL_RADIXSORT_NO_FORK) - quickSort(a, b, i, i + count[c]); - else { - queueSize.incrementAndGet(); - queue.add(new Segment(i, count[c], - level + 1)); - } - } - } - queueSize.decrementAndGet(); - } - } - }); - Throwable problem = null; - for (int i = numberOfThreads; i-- != 0;) - try { - executorCompletionService.take().get(); - } catch (Exception e) { - problem = e.getCause(); // We keep only the last one. They will - // be logged anyway. - } - executorService.shutdown(); - if (problem != null) - throw (problem instanceof RuntimeException) - ? (RuntimeException) problem - : new RuntimeException(problem); - } - - /** - * Sorts two arrays using a parallel radix sort. - * - *

- * The sorting algorithm is a tuned radix sort adapted from Peter M. - * McIlroy, Keith Bostic and M. Douglas McIlroy, “Engineering radix - * sort”, Computing Systems, 6(1), pages 5−27 (1993). - * - *

- * This method implements a lexicographical sorting of the - * arguments. Pairs of elements in the same position in the two provided - * arrays will be considered a single key, and permuted accordingly. In the - * end, either a[ i ] < a[ i + 1 ] or - * a[ i ] == a[ i + 1 ] and b[ i ] ≤ b[ i + 1 ]. - * - *

- * This implementation uses a pool of {@link Runtime#availableProcessors()} - * threads. - * - * @param a - * the first array to be sorted. - * @param b - * the second array to be sorted. - */ - public static void parallelRadixSort(final int[] a, final int[] b) { - ensureSameLength(a, b); - parallelRadixSort(a, b, 0, a.length); - } - - private static void insertionSortIndirect(final int[] perm, final int[] a, - final int[] b, final int from, final int to) { - for (int i = from; ++i < to;) { - int t = perm[i]; - int j = i; - for (int u = perm[j - 1]; ((a[t]) < (a[u])) || ((a[t]) == (a[u])) - && ((b[t]) < (b[u])); u = perm[--j - 1]) { - perm[j] = u; - if (from == j - 1) { - --j; - break; - } - } - perm[j] = t; - } - } - - /** - * Sorts the specified pair of arrays lexicographically using indirect radix - * sort. - * - *

- * The sorting algorithm is a tuned radix sort adapted from Peter M. - * McIlroy, Keith Bostic and M. Douglas McIlroy, “Engineering radix - * sort”, Computing Systems, 6(1), pages 5−27 (1993). - * - *

- * This method implement an indirect sort. The elements of - * perm (which must be exactly the numbers in the interval - * [0..perm.length)) will be permuted so that - * a[ perm[ i ] ] ≤ a[ perm[ i + 1 ] ]. - * - *

- * This implementation will allocate, in the stable case, a further support - * array as large as perm (note that the stable version is - * slightly faster). - * - * @param perm - * a permutation array indexing a. - * @param a - * the array to be sorted. - * @param b - * the second array to be sorted. - * @param stable - * whether the sorting algorithm should be stable. - */ - public static void radixSortIndirect(final int[] perm, final int[] a, - final int[] b, final boolean stable) { - ensureSameLength(a, b); - radixSortIndirect(perm, a, b, 0, a.length, stable); - } - - /** - * Sorts the specified pair of arrays lexicographically using indirect radix - * sort. - * - *

- * The sorting algorithm is a tuned radix sort adapted from Peter M. - * McIlroy, Keith Bostic and M. Douglas McIlroy, “Engineering radix - * sort”, Computing Systems, 6(1), pages 5−27 (1993). - * - *

- * This method implement an indirect sort. The elements of - * perm (which must be exactly the numbers in the interval - * [0..perm.length)) will be permuted so that - * a[ perm[ i ] ] ≤ a[ perm[ i + 1 ] ]. - * - *

- * This implementation will allocate, in the stable case, a further support - * array as large as perm (note that the stable version is - * slightly faster). - * - * @param perm - * a permutation array indexing a. - * @param a - * the array to be sorted. - * @param b - * the second array to be sorted. - * @param from - * the index of the first element of perm - * (inclusive) to be permuted. - * @param to - * the index of the last element of perm (exclusive) - * to be permuted. - * @param stable - * whether the sorting algorithm should be stable. - */ - public static void radixSortIndirect(final int[] perm, final int[] a, - final int[] b, final int from, final int to, final boolean stable) { - if (to - from < RADIXSORT_NO_REC) { - insertionSortIndirect(perm, a, b, from, to); - return; - } - - final int layers = 2; - final int maxLevel = DIGITS_PER_ELEMENT * layers - 1; - - final int stackSize = ((1 << DIGIT_BITS) - 1) - * (layers * DIGITS_PER_ELEMENT - 1) + 1; - int stackPos = 0; - final int[] offsetStack = new int[stackSize]; - final int[] lengthStack = new int[stackSize]; - final int[] levelStack = new int[stackSize]; - - offsetStack[stackPos] = from; - lengthStack[stackPos] = to - from; - levelStack[stackPos++] = 0; - - final int[] count = new int[1 << DIGIT_BITS]; - final int[] pos = new int[1 << DIGIT_BITS]; - final int[] support = stable ? new int[perm.length] : null; - - while (stackPos > 0) { - final int first = offsetStack[--stackPos]; - final int length = lengthStack[stackPos]; - final int level = levelStack[stackPos]; - - final int signMask = level % DIGITS_PER_ELEMENT == 0 - ? 1 << DIGIT_BITS - 1 - : 0; - - final int[] k = level < DIGITS_PER_ELEMENT ? a : b; // This is the - // key array - final int shift = (DIGITS_PER_ELEMENT - 1 - level - % DIGITS_PER_ELEMENT) - * DIGIT_BITS; // This is the shift that extract the right - // byte from a key - - // Count keys. - for (int i = first + length; i-- != first;) - count[((k[perm[i]]) >>> shift & DIGIT_MASK ^ signMask)]++; - - // Compute cumulative distribution - int lastUsed = -1; - for (int i = 0, p = stable ? 0 : first; i < 1 << DIGIT_BITS; i++) { - if (count[i] != 0) - lastUsed = i; - pos[i] = (p += count[i]); - } - - if (stable) { - for (int i = first + length; i-- != first;) - support[--pos[((k[perm[i]]) >>> shift & DIGIT_MASK ^ signMask)]] = perm[i]; - System.arraycopy(support, 0, perm, first, length); - for (int i = 0, p = first; i < 1 << DIGIT_BITS; i++) { - if (level < maxLevel && count[i] > 1) { - if (count[i] < RADIXSORT_NO_REC) - insertionSortIndirect(perm, a, b, p, p + count[i]); - else { - offsetStack[stackPos] = p; - lengthStack[stackPos] = count[i]; - levelStack[stackPos++] = level + 1; - } - } - p += count[i]; - } - java.util.Arrays.fill(count, 0); - } else { - final int end = first + length - count[lastUsed]; - // i moves through the start of each block - for (int i = first, c = -1, d; i <= end; i += count[c], count[c] = 0) { - int t = perm[i]; - c = ((k[t]) >>> shift & DIGIT_MASK ^ signMask); - - if (i < end) { // When all slots are OK, the last slot is - // necessarily OK. - while ((d = --pos[c]) > i) { - final int z = t; - t = perm[d]; - perm[d] = z; - c = ((k[t]) >>> shift & DIGIT_MASK ^ signMask); - } - perm[i] = t; - } - - if (level < maxLevel && count[c] > 1) { - if (count[c] < RADIXSORT_NO_REC) - insertionSortIndirect(perm, a, b, i, i + count[c]); - else { - offsetStack[stackPos] = i; - lengthStack[stackPos] = count[c]; - levelStack[stackPos++] = level + 1; - } - } - } - } - } - } - - private static void selectionSort(final int[][] a, final int from, - final int to, final int level) { - final int layers = a.length; - final int firstLayer = level / DIGITS_PER_ELEMENT; - - for (int i = from; i < to - 1; i++) { - int m = i; - for (int j = i + 1; j < to; j++) { - for (int p = firstLayer; p < layers; p++) { - if (a[p][j] < a[p][m]) { - m = j; - break; - } else if (a[p][j] > a[p][m]) - break; - } - } - if (m != i) { - for (int p = layers; p-- != 0;) { - final int u = a[p][i]; - a[p][i] = a[p][m]; - a[p][m] = u; - } - } - } - } - - /** - * Sorts the specified array of arrays lexicographically using radix sort. - * - *

- * The sorting algorithm is a tuned radix sort adapted from Peter M. - * McIlroy, Keith Bostic and M. Douglas McIlroy, “Engineering radix - * sort”, Computing Systems, 6(1), pages 5−27 (1993). - * - *

- * This method implements a lexicographical sorting of the provided - * arrays. Tuples of elements in the same position will be considered a - * single key, and permuted accordingly. - * - * @param a - * an array containing arrays of equal length to be sorted - * lexicographically in parallel. - */ - public static void radixSort(final int[][] a) { - radixSort(a, 0, a[0].length); - } - - /** - * Sorts the specified array of arrays lexicographically using radix sort. - * - *

- * The sorting algorithm is a tuned radix sort adapted from Peter M. - * McIlroy, Keith Bostic and M. Douglas McIlroy, “Engineering radix - * sort”, Computing Systems, 6(1), pages 5−27 (1993). - * - *

- * This method implements a lexicographical sorting of the provided - * arrays. Tuples of elements in the same position will be considered a - * single key, and permuted accordingly. - * - * @param a - * an array containing arrays of equal length to be sorted - * lexicographically in parallel. - * @param from - * the index of the first element (inclusive) to be sorted. - * @param to - * the index of the last element (exclusive) to be sorted. - */ - public static void radixSort(final int[][] a, final int from, final int to) { - if (to - from < RADIXSORT_NO_REC) { - selectionSort(a, from, to, 0); - return; - } - - final int layers = a.length; - final int maxLevel = DIGITS_PER_ELEMENT * layers - 1; - for (int p = layers, l = a[0].length; p-- != 0;) - if (a[p].length != l) - throw new IllegalArgumentException("The array of index " + p - + " has not the same length of the array of index 0."); - - final int stackSize = ((1 << DIGIT_BITS) - 1) - * (layers * DIGITS_PER_ELEMENT - 1) + 1; - int stackPos = 0; - final int[] offsetStack = new int[stackSize]; - final int[] lengthStack = new int[stackSize]; - final int[] levelStack = new int[stackSize]; - - offsetStack[stackPos] = from; - lengthStack[stackPos] = to - from; - levelStack[stackPos++] = 0; - - final int[] count = new int[1 << DIGIT_BITS]; - final int[] pos = new int[1 << DIGIT_BITS]; - final int[] t = new int[layers]; - - while (stackPos > 0) { - final int first = offsetStack[--stackPos]; - final int length = lengthStack[stackPos]; - final int level = levelStack[stackPos]; - - final int signMask = level % DIGITS_PER_ELEMENT == 0 - ? 1 << DIGIT_BITS - 1 - : 0; - - final int[] k = a[level / DIGITS_PER_ELEMENT]; // This is the key - // array - final int shift = (DIGITS_PER_ELEMENT - 1 - level - % DIGITS_PER_ELEMENT) - * DIGIT_BITS; // This is the shift that extract the right - // byte from a key - - // Count keys. - for (int i = first + length; i-- != first;) - count[((k[i]) >>> shift & DIGIT_MASK ^ signMask)]++; - - // Compute cumulative distribution - int lastUsed = -1; - for (int i = 0, p = first; i < 1 << DIGIT_BITS; i++) { - if (count[i] != 0) - lastUsed = i; - pos[i] = (p += count[i]); - } - - final int end = first + length - count[lastUsed]; - // i moves through the start of each block - for (int i = first, c = -1, d; i <= end; i += count[c], count[c] = 0) { - for (int p = layers; p-- != 0;) - t[p] = a[p][i]; - c = ((k[i]) >>> shift & DIGIT_MASK ^ signMask); - - if (i < end) { // When all slots are OK, the last slot is - // necessarily OK. - while ((d = --pos[c]) > i) { - c = ((k[d]) >>> shift & DIGIT_MASK ^ signMask); - for (int p = layers; p-- != 0;) { - final int u = t[p]; - t[p] = a[p][d]; - a[p][d] = u; - } - } - for (int p = layers; p-- != 0;) - a[p][i] = t[p]; - } - - if (level < maxLevel && count[c] > 1) { - if (count[c] < RADIXSORT_NO_REC) - selectionSort(a, i, i + count[c], level + 1); - else { - offsetStack[stackPos] = i; - lengthStack[stackPos] = count[c]; - levelStack[stackPos++] = level + 1; - } - } - } - } - } - - /** - * Shuffles the specified array fragment using the specified pseudorandom - * number generator. - * - * @param a - * the array to be shuffled. - * @param from - * the index of the first element (inclusive) to be shuffled. - * @param to - * the index of the last element (exclusive) to be shuffled. - * @param random - * a pseudorandom number generator (please use a XorShift* generator). - * @return a. - */ - public static int[] shuffle(final int[] a, final int from, final int to, - final Random random) { - for (int i = to - from; i-- != 0;) { - final int p = random.nextInt(i + 1); - final int t = a[from + i]; - a[from + i] = a[from + p]; - a[from + p] = t; - } - return a; - } - - /** - * Shuffles the specified array using the specified pseudorandom number - * generator. - * - * @param a - * the array to be shuffled. - * @param random - * a pseudorandom number generator (please use a XorShift* generator). - * @return a. - */ - public static int[] shuffle(final int[] a, final Random random) { - for (int i = a.length; i-- != 0;) { - final int p = random.nextInt(i + 1); - final int t = a[i]; - a[i] = a[p]; - a[p] = t; - } - return a; - } - - /** - * Reverses the order of the elements in the specified array. - * - * @param a - * the array to be reversed. - * @return a. - */ - public static int[] reverse(final int[] a) { - final int length = a.length; - for (int i = length / 2; i-- != 0;) { - final int t = a[length - i - 1]; - a[length - i - 1] = a[i]; - a[i] = t; - } - return a; - } - - /** - * Reverses the order of the elements in the specified array fragment. - * - * @param a - * the array to be reversed. - * @param from - * the index of the first element (inclusive) to be reversed. - * @param to - * the index of the last element (exclusive) to be reversed. - * @return a. - */ - public static int[] reverse(final int[] a, final int from, final int to) { - final int length = to - from; - for (int i = length / 2; i-- != 0;) { - final int t = a[from + length - i - 1]; - a[from + length - i - 1] = a[from + i]; - a[from + i] = t; - } - return a; - } - - /** A type-specific content-based hash strategy for arrays. */ - - private static final class ArrayHashStrategy - implements - Hash.Strategy, - java.io.Serializable { - private static final long serialVersionUID = -7046029254386353129L; - - public int hashCode(final int[] o) { - return java.util.Arrays.hashCode(o); - } - - public boolean equals(final int[] a, final int[] b) { - return java.util.Arrays.equals(a, b); - } - } - - /** - * A type-specific content-based hash strategy for arrays. - * - *

- * This hash strategy may be used in custom hash collections whenever keys - * are arrays, and they must be considered equal by content. This strategy - * will handle null correctly, and it is serializable. - */ - - public final static Hash.Strategy HASH_STRATEGY = new ArrayHashStrategy(); - -} diff --git a/src/main/java/it/unimi/dsi/fastutil/ints/IntBidirectionalIterator.java b/src/main/java/it/unimi/dsi/fastutil/ints/IntBidirectionalIterator.java deleted file mode 100644 index cac670c..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/ints/IntBidirectionalIterator.java +++ /dev/null @@ -1,89 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Primitive-type-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.ints; - -import it.unimi.dsi.fastutil.BidirectionalIterator; -import it.unimi.dsi.fastutil.ints.IntIterator; -import it.unimi.dsi.fastutil.objects.ObjectBidirectionalIterator; - -/** - * A type-specific bidirectional iterator; provides an additional method to - * avoid (un)boxing, and the possibility to skip elements backwards. - * - * @see BidirectionalIterator - */ - -public interface IntBidirectionalIterator - extends - IntIterator, - ObjectBidirectionalIterator { - - /** - * Returns the previous element as a primitive type. - * - * @return the previous element in the iteration. - * @see java.util.ListIterator#previous() - */ - - int previousInt(); - - /** - * Moves back for the given number of elements. - * - *

- * The effect of this call is exactly the same as that of calling - * {@link #previous()} for n times (possibly stopping if - * {@link #hasPrevious()} becomes false). - * - * @param n - * the number of elements to skip back. - * @return the number of elements actually skipped. - * @see java.util.Iterator#next() - */ - - int back(int n); -} diff --git a/src/main/java/it/unimi/dsi/fastutil/ints/IntCollection.java b/src/main/java/it/unimi/dsi/fastutil/ints/IntCollection.java deleted file mode 100644 index 04d032a..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/ints/IntCollection.java +++ /dev/null @@ -1,189 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Primitive-type-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.ints; - -import it.unimi.dsi.fastutil.ints.IntIterable; -import it.unimi.dsi.fastutil.ints.IntIterator; - -import java.util.Collection; - -/** - * A type-specific {@link Collection}; provides some additional methods that use - * polymorphism to avoid (un)boxing. - * - *

- * Additionally, this class defines strengthens (again) {@link #iterator()} and - * defines a slightly different semantics for {@link #toArray(Object[])}. - * - * @see Collection - */ - -public interface IntCollection extends Collection, IntIterable { - - /** - * Returns a type-specific iterator on the elements of this collection. - * - *

- * Note that this specification strengthens the one given in - * {@link Iterable#iterator()}, which was already strengthened in - * the corresponding type-specific class, but was weakened by the fact that - * this interface extends {@link Collection}. - * - * @return a type-specific iterator on the elements of this collection. - */ - IntIterator iterator(); - - /** - * Returns a type-specific iterator on this elements of this collection. - * - * @see #iterator() - * @deprecated As of fastutil 5, replaced by - * {@link #iterator()}. - */ - @Deprecated - IntIterator intIterator(); - - /** - * Returns an containing the items of this collection; the runtime type of - * the returned array is that of the specified array. - * - *

- * Warning: Note that, contrarily to - * {@link Collection#toArray(Object[])}, this methods just writes all - * elements of this collection: no special value will be added after the - * last one. - * - * @param a - * if this array is big enough, it will be used to store this - * collection. - * @return a primitive type array containing the items of this collection. - * @see Collection#toArray(Object[]) - */ - T[] toArray(T[] a); - - /** - * @see Collection#contains(Object) - */ - boolean contains(int key); - - /** - * Returns a primitive type array containing the items of this collection. - * - * @return a primitive type array containing the items of this collection. - * @see Collection#toArray() - */ - int[] toIntArray(); - - /** - * Returns a primitive type array containing the items of this collection. - * - *

- * Note that, contrarily to {@link Collection#toArray(Object[])}, this - * methods just writes all elements of this collection: no special value - * will be added after the last one. - * - * @param a - * if this array is big enough, it will be used to store this - * collection. - * @return a primitive type array containing the items of this collection. - * @see Collection#toArray(Object[]) - */ - int[] toIntArray(int a[]); - - /** - * Returns a primitive type array containing the items of this collection. - * - *

- * Note that, contrarily to {@link Collection#toArray(Object[])}, this - * methods just writes all elements of this collection: no special value - * will be added after the last one. - * - * @param a - * if this array is big enough, it will be used to store this - * collection. - * @return a primitive type array containing the items of this collection. - * @see Collection#toArray(Object[]) - */ - int[] toArray(int a[]); - - /** - * @see Collection#add(Object) - */ - boolean add(int key); - - /** - * Note that this method should be called - * {@link Collection#remove(Object) remove()}, but the clash with - * the similarly named index-based method in the {@link java.util.List} - * interface forces us to use a distinguished name. For simplicity, the set - * interfaces reinstates remove(). - * - * @see Collection#remove(Object) - */ - boolean rem(int key); - - /** - * @see Collection#addAll(Collection) - */ - boolean addAll(it.unimi.dsi.fastutil.ints.IntCollection c); - - /** - * @see Collection#containsAll(Collection) - */ - boolean containsAll(it.unimi.dsi.fastutil.ints.IntCollection c); - - /** - * @see Collection#removeAll(Collection) - */ - boolean removeAll(it.unimi.dsi.fastutil.ints.IntCollection c); - - /** - * @see Collection#retainAll(Collection) - */ - boolean retainAll(it.unimi.dsi.fastutil.ints.IntCollection c); - -} diff --git a/src/main/java/it/unimi/dsi/fastutil/ints/IntComparator.java b/src/main/java/it/unimi/dsi/fastutil/ints/IntComparator.java deleted file mode 100644 index 16ce7ea..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/ints/IntComparator.java +++ /dev/null @@ -1,75 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Primitive-type-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.ints; - -import java.util.Comparator; - -/** - * A type-specific {@link Comparator}; provides methods to compare two primitive - * types both as objects and as primitive types. - * - *

- * Note that fastutil provides a corresponding abstract class that - * can be used to implement this interface just by specifying the type-specific - * comparator. - * - * @see Comparator - */ - -public interface IntComparator extends Comparator { - - /** - * Compares the given primitive types. - * - * @see Comparator - * @return A positive integer, zero, or a negative integer if the first - * argument is greater than, equal to, or smaller than, - * respectively, the second one. - */ - - public int compare(int k1, int k2); -} diff --git a/src/main/java/it/unimi/dsi/fastutil/ints/IntIterable.java b/src/main/java/it/unimi/dsi/fastutil/ints/IntIterable.java deleted file mode 100644 index 9a822e0..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/ints/IntIterable.java +++ /dev/null @@ -1,76 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Primitive-type-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.ints; - -import it.unimi.dsi.fastutil.ints.IntIterator; - -/** - * A type-specific {@link Iterable} that strengthens that specification of - * {@link Iterable#iterator()}. - * - *

- * Warning: Java will let you write “colon” - * for statements with primitive-type loop variables; however, what - * is (unfortunately) really happening is that at each iteration an unboxing - * (and, in the case of fastutil type-specific data structures, a - * boxing) will be performed. Watch out. - * - * @see Iterable - */ - -public interface IntIterable extends Iterable { - - /** - * Returns a type-specific iterator. - * - * Note that this specification strengthens the one given in - * {@link Iterable#iterator()}. - * - * @return a type-specific iterator. - */ - IntIterator iterator(); -} diff --git a/src/main/java/it/unimi/dsi/fastutil/ints/IntIterator.java b/src/main/java/it/unimi/dsi/fastutil/ints/IntIterator.java deleted file mode 100644 index ec5c1b8..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/ints/IntIterator.java +++ /dev/null @@ -1,84 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Primitive-type-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.ints; - -import java.util.Iterator; - -/** - * A type-specific {@link Iterator}; provides an additional method to avoid - * (un)boxing, and the possibility to skip elements. - * - * @see Iterator - */ - -public interface IntIterator extends Iterator { - - /** - * Returns the next element as a primitive type. - * - * @return the next element in the iteration. - * @see Iterator#next() - */ - - int nextInt(); - - /** - * Skips the given number of elements. - * - *

- * The effect of this call is exactly the same as that of calling - * {@link #next()} for n times (possibly stopping if - * {@link #hasNext()} becomes false). - * - * @param n - * the number of elements to skip. - * @return the number of elements actually skipped. - * @see Iterator#next() - */ - - int skip(int n); -} diff --git a/src/main/java/it/unimi/dsi/fastutil/ints/IntIterators.java b/src/main/java/it/unimi/dsi/fastutil/ints/IntIterators.java deleted file mode 100644 index 0dd0f24..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/ints/IntIterators.java +++ /dev/null @@ -1,1083 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Primitive-type-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.ints; - -import it.unimi.dsi.fastutil.ints.AbstractIntBidirectionalIterator; -import it.unimi.dsi.fastutil.ints.AbstractIntIterator; -import it.unimi.dsi.fastutil.ints.AbstractIntListIterator; -import it.unimi.dsi.fastutil.ints.IntArrayList; -import it.unimi.dsi.fastutil.ints.IntArrays; -import it.unimi.dsi.fastutil.ints.IntBidirectionalIterator; -import it.unimi.dsi.fastutil.ints.IntCollection; -import it.unimi.dsi.fastutil.ints.IntIterator; -import it.unimi.dsi.fastutil.ints.IntList; -import it.unimi.dsi.fastutil.ints.IntListIterator; - -import java.util.Iterator; -import java.util.ListIterator; -import java.util.NoSuchElementException; - -/** - * A class providing static methods and objects that do useful things with - * type-specific iterators. - * - * @see Iterator - */ - -public class IntIterators { - - private IntIterators() { - } - - /** - * A class returning no elements and a type-specific iterator interface. - * - *

- * This class may be useful to implement your own in case you subclass a - * type-specific iterator. - */ - - public static class EmptyIterator extends AbstractIntListIterator - implements - java.io.Serializable, - Cloneable { - - private static final long serialVersionUID = -7046029254386353129L; - - protected EmptyIterator() { - } - - public boolean hasNext() { - return false; - } - public boolean hasPrevious() { - return false; - } - public int nextInt() { - throw new NoSuchElementException(); - } - public int previousInt() { - throw new NoSuchElementException(); - } - public int nextIndex() { - return 0; - } - public int previousIndex() { - return -1; - } - public int skip(int n) { - return 0; - }; - public int back(int n) { - return 0; - }; - public Object clone() { - return EMPTY_ITERATOR; - } - private Object readResolve() { - return EMPTY_ITERATOR; - } - } - - /** - * An empty iterator (immutable). It is serializable and cloneable. - * - *

- * The class of this objects represent an abstract empty iterator that can - * iterate as a type-specific (list) iterator. - */ - - public final static EmptyIterator EMPTY_ITERATOR = new EmptyIterator(); - - /** An iterator returning a single element. */ - - private static class SingletonIterator extends AbstractIntListIterator { - private final int element; - private int curr; - - public SingletonIterator(final int element) { - this.element = element; - } - - public boolean hasNext() { - return curr == 0; - } - public boolean hasPrevious() { - return curr == 1; - } - - public int nextInt() { - if (!hasNext()) - throw new NoSuchElementException(); - curr = 1; - return element; - } - - public int previousInt() { - if (!hasPrevious()) - throw new NoSuchElementException(); - curr = 0; - return element; - } - - public int nextIndex() { - return curr; - } - - public int previousIndex() { - return curr - 1; - } - } - - /** - * Returns an iterator that iterates just over the given element. - * - * @param element - * the only element to be returned by a type-specific list - * iterator. - * @return an iterator that iterates just over element. - */ - public static IntListIterator singleton(final int element) { - return new SingletonIterator(element); - } - - /** A class to wrap arrays in iterators. */ - - private static class ArrayIterator extends AbstractIntListIterator { - private final int[] array; - private final int offset, length; - private int curr; - - public ArrayIterator(final int[] array, final int offset, - final int length) { - this.array = array; - this.offset = offset; - this.length = length; - } - - public boolean hasNext() { - return curr < length; - } - public boolean hasPrevious() { - return curr > 0; - } - - public int nextInt() { - if (!hasNext()) - throw new NoSuchElementException(); - return array[offset + curr++]; - } - - public int previousInt() { - if (!hasPrevious()) - throw new NoSuchElementException(); - return array[offset + --curr]; - } - - public int skip(int n) { - if (n <= length - curr) { - curr += n; - return n; - } - n = length - curr; - curr = length; - return n; - } - - public int back(int n) { - if (n <= curr) { - curr -= n; - return n; - } - n = curr; - curr = 0; - return n; - } - - public int nextIndex() { - return curr; - } - - public int previousIndex() { - return curr - 1; - } - } - - /** - * Wraps the given part of an array into a type-specific list iterator. - * - *

- * The type-specific list iterator returned by this method will iterate - * length times, returning consecutive elements of the given - * array starting from the one with index offset. - * - * @param array - * an array to wrap into a type-specific list iterator. - * @param offset - * the first element of the array to be returned. - * @param length - * the number of elements to return. - * @return an iterator that will return length elements of - * array starting at position offset. - */ - public static IntListIterator wrap(final int[] array, final int offset, - final int length) { - IntArrays.ensureOffsetLength(array, offset, length); - return new ArrayIterator(array, offset, length); - } - - /** - * Wraps the given array into a type-specific list iterator. - * - *

- * The type-specific list iterator returned by this method will return all - * elements of the given array. - * - * @param array - * an array to wrap into a type-specific list iterator. - * @return an iterator that will the elements of array. - */ - public static IntListIterator wrap(final int[] array) { - return new ArrayIterator(array, 0, array.length); - } - - /** - * Unwraps an iterator into an array starting at a given offset for a given - * number of elements. - * - *

- * This method iterates over the given type-specific iterator and stores the - * elements returned, up to a maximum of length, in the given - * array starting at offset. The number of actually unwrapped - * elements is returned (it may be less than max if the - * iterator emits less than max elements). - * - * @param i - * a type-specific iterator. - * @param array - * an array to contain the output of the iterator. - * @param offset - * the first element of the array to be returned. - * @param max - * the maximum number of elements to unwrap. - * @return the number of elements unwrapped. - */ - public static int unwrap(final IntIterator i, final int array[], - int offset, final int max) { - if (max < 0) - throw new IllegalArgumentException( - "The maximum number of elements (" + max + ") is negative"); - if (offset < 0 || offset + max > array.length) - throw new IllegalArgumentException(); - int j = max; - while (j-- != 0 && i.hasNext()) - array[offset++] = i.nextInt(); - return max - j - 1; - } - - /** - * Unwraps an iterator into an array. - * - *

- * This method iterates over the given type-specific iterator and stores the - * elements returned in the given array. The iteration will stop when the - * iterator has no more elements or when the end of the array has been - * reached. - * - * @param i - * a type-specific iterator. - * @param array - * an array to contain the output of the iterator. - * @return the number of elements unwrapped. - */ - public static int unwrap(final IntIterator i, final int array[]) { - return unwrap(i, array, 0, array.length); - } - - /** - * Unwraps an iterator, returning an array, with a limit on the number of - * elements. - * - *

- * This method iterates over the given type-specific iterator and returns an - * array containing the elements returned by the iterator. At most - * max elements will be returned. - * - * @param i - * a type-specific iterator. - * @param max - * the maximum number of elements to be unwrapped. - * @return an array containing the elements returned by the iterator (at - * most max). - */ - - public static int[] unwrap(final IntIterator i, int max) { - if (max < 0) - throw new IllegalArgumentException( - "The maximum number of elements (" + max + ") is negative"); - int array[] = new int[16]; - int j = 0; - - while (max-- != 0 && i.hasNext()) { - if (j == array.length) - array = IntArrays.grow(array, j + 1); - array[j++] = i.nextInt(); - } - - return IntArrays.trim(array, j); - } - - /** - * Unwraps an iterator, returning an array. - * - *

- * This method iterates over the given type-specific iterator and returns an - * array containing the elements returned by the iterator. - * - * @param i - * a type-specific iterator. - * @return an array containing the elements returned by the iterator. - */ - - public static int[] unwrap(final IntIterator i) { - return unwrap(i, Integer.MAX_VALUE); - } - - /** - * Unwraps an iterator into a type-specific collection, with a limit on the - * number of elements. - * - *

- * This method iterates over the given type-specific iterator and stores the - * elements returned, up to a maximum of max, in the given - * type-specific collection. The number of actually unwrapped elements is - * returned (it may be less than max if the iterator emits less - * than max elements). - * - * @param i - * a type-specific iterator. - * @param c - * a type-specific collection array to contain the output of the - * iterator. - * @param max - * the maximum number of elements to unwrap. - * @return the number of elements unwrapped. Note that this is the number of - * elements returned by the iterator, which is not necessarily the - * number of elements that have been added to the collection - * (because of duplicates). - */ - public static int unwrap(final IntIterator i, final IntCollection c, - final int max) { - if (max < 0) - throw new IllegalArgumentException( - "The maximum number of elements (" + max + ") is negative"); - int j = max; - while (j-- != 0 && i.hasNext()) - c.add(i.nextInt()); - return max - j - 1; - } - - /** - * Unwraps an iterator into a type-specific collection. - * - *

- * This method iterates over the given type-specific iterator and stores the - * elements returned in the given type-specific collection. The returned - * count on the number unwrapped elements is a long, so that it will work - * also with very large collections. - * - * @param i - * a type-specific iterator. - * @param c - * a type-specific collection to contain the output of the - * iterator. - * @return the number of elements unwrapped. Note that this is the number of - * elements returned by the iterator, which is not necessarily the - * number of elements that have been added to the collection - * (because of duplicates). - */ - public static long unwrap(final IntIterator i, final IntCollection c) { - long n = 0; - while (i.hasNext()) { - c.add(i.nextInt()); - n++; - } - return n; - } - - /** - * Pours an iterator into a type-specific collection, with a limit on the - * number of elements. - * - *

- * This method iterates over the given type-specific iterator and adds the - * returned elements to the given collection (up to max). - * - * @param i - * a type-specific iterator. - * @param s - * a type-specific collection. - * @param max - * the maximum number of elements to be poured. - * @return the number of elements poured. Note that this is the number of - * elements returned by the iterator, which is not necessarily the - * number of elements that have been added to the collection - * (because of duplicates). - */ - - public static int pour(final IntIterator i, final IntCollection s, - final int max) { - if (max < 0) - throw new IllegalArgumentException( - "The maximum number of elements (" + max + ") is negative"); - int j = max; - while (j-- != 0 && i.hasNext()) - s.add(i.nextInt()); - return max - j - 1; - } - - /** - * Pours an iterator into a type-specific collection. - * - *

- * This method iterates over the given type-specific iterator and adds the - * returned elements to the given collection. - * - * @param i - * a type-specific iterator. - * @param s - * a type-specific collection. - * @return the number of elements poured. Note that this is the number of - * elements returned by the iterator, which is not necessarily the - * number of elements that have been added to the collection - * (because of duplicates). - */ - - public static int pour(final IntIterator i, final IntCollection s) { - return pour(i, s, Integer.MAX_VALUE); - } - - /** - * Pours an iterator, returning a type-specific list, with a limit on the - * number of elements. - * - *

- * This method iterates over the given type-specific iterator and returns a - * type-specific list containing the returned elements (up to - * max). Iteration on the returned list is guaranteed to - * produce the elements in the same order in which they appeared in the - * iterator. - * - * - * @param i - * a type-specific iterator. - * @param max - * the maximum number of elements to be poured. - * @return a type-specific list containing the returned elements, up to - * max. - */ - - public static IntList pour(final IntIterator i, int max) { - final IntArrayList l = new IntArrayList(); - pour(i, l, max); - l.trim(); - return l; - } - - /** - * Pours an iterator, returning a type-specific list. - * - *

- * This method iterates over the given type-specific iterator and returns a - * list containing the returned elements. Iteration on the returned list is - * guaranteed to produce the elements in the same order in which they - * appeared in the iterator. - * - * @param i - * a type-specific iterator. - * @return a type-specific list containing the returned elements. - */ - - public static IntList pour(final IntIterator i) { - return pour(i, Integer.MAX_VALUE); - } - - private static class IteratorWrapper extends AbstractIntIterator { - final Iterator i; - - public IteratorWrapper(final Iterator i) { - this.i = i; - } - - public boolean hasNext() { - return i.hasNext(); - } - public void remove() { - i.remove(); - } - - public int nextInt() { - return ((i.next()).intValue()); - } - } - - /** - * Wraps a standard iterator into a type-specific iterator. - * - *

- * This method wraps a standard iterator into a type-specific one which will - * handle the type conversions for you. Of course, any attempt to wrap an - * iterator returning the instances of the wrong class will generate a - * {@link ClassCastException}. The returned iterator is backed by - * i: changes to one of the iterators will affect the other, - * too. - * - *

- * If i is already type-specific, it will returned and no new - * object will be generated. - * - * @param i - * an iterator. - * @return a type-specific iterator backed by i. - */ - - @SuppressWarnings({"unchecked", "rawtypes"}) - public static IntIterator asIntIterator(final Iterator i) { - if (i instanceof IntIterator) - return (IntIterator) i; - return new IteratorWrapper(i); - } - - private static class ListIteratorWrapper extends AbstractIntListIterator { - final ListIterator i; - - public ListIteratorWrapper(final ListIterator i) { - this.i = i; - } - - public boolean hasNext() { - return i.hasNext(); - } - public boolean hasPrevious() { - return i.hasPrevious(); - } - public int nextIndex() { - return i.nextIndex(); - } - public int previousIndex() { - return i.previousIndex(); - } - public void set(int k) { - i.set((Integer.valueOf(k))); - } - public void add(int k) { - i.add((Integer.valueOf(k))); - } - public void remove() { - i.remove(); - } - - public int nextInt() { - return ((i.next()).intValue()); - } - public int previousInt() { - return ((i.previous()).intValue()); - } - } - - /** - * Wraps a standard list iterator into a type-specific list iterator. - * - *

- * This method wraps a standard list iterator into a type-specific one which - * will handle the type conversions for you. Of course, any attempt to wrap - * an iterator returning the instances of the wrong class will generate a - * {@link ClassCastException}. The returned iterator is backed by - * i: changes to one of the iterators will affect the other, - * too. - * - *

- * If i is already type-specific, it will returned and no new - * object will be generated. - * - * @param i - * a list iterator. - * @return a type-specific list iterator backed by i. - */ - - @SuppressWarnings({"unchecked", "rawtypes"}) - public static IntListIterator asIntIterator(final ListIterator i) { - if (i instanceof IntListIterator) - return (IntListIterator) i; - return new ListIteratorWrapper(i); - } - - private static class IntervalIterator extends AbstractIntListIterator { - - private final int from, to; - int curr; - - public IntervalIterator(final int from, final int to) { - this.from = this.curr = from; - this.to = to; - } - - public boolean hasNext() { - return curr < to; - } - public boolean hasPrevious() { - return curr > from; - } - - public int nextInt() { - if (!hasNext()) - throw new NoSuchElementException(); - return curr++; - } - public int previousInt() { - if (!hasPrevious()) - throw new NoSuchElementException(); - return --curr; - } - - public int nextIndex() { - return curr - from; - } - public int previousIndex() { - return curr - from - 1; - } - - public int skip(int n) { - if (curr + n <= to) { - curr += n; - return n; - } - - n = to - curr; - - curr = to; - return n; - } - - public int back(int n) { - if (curr - n >= from) { - curr -= n; - return n; - } - - n = curr - from; - - curr = from; - return n; - } - } - /** - * Creates a type-specific list iterator over an interval. - * - *

- * The type-specific list iterator returned by this method will return the - * elements from, from+1,…, - * to-1. - * - * @param from - * the starting element (inclusive). - * @param to - * the ending element (exclusive). - * @return a type-specific list iterator enumerating the elements from - * from to to. - */ - public static IntListIterator fromTo(final int from, final int to) { - return new IntervalIterator(from, to); - } - - private static class IteratorConcatenator extends AbstractIntIterator { - final IntIterator a[]; - int offset, length, lastOffset = -1; - - public IteratorConcatenator(final IntIterator a[], int offset, - int length) { - this.a = a; - this.offset = offset; - this.length = length; - advance(); - } - - private void advance() { - while (length != 0) { - if (a[offset].hasNext()) - break; - length--; - offset++; - } - - return; - } - - public boolean hasNext() { - return length > 0; - } - - public int nextInt() { - if (!hasNext()) - throw new NoSuchElementException(); - int next = a[lastOffset = offset].nextInt(); - advance(); - return next; - } - - public void remove() { - if (lastOffset == -1) - throw new IllegalStateException(); - a[lastOffset].remove(); - } - - public int skip(int n) { - lastOffset = -1; - - int skipped = 0; - - while (skipped < n && length != 0) { - skipped += a[offset].skip(n - skipped); - if (a[offset].hasNext()) - break; - length--; - offset++; - } - - return skipped; - } - - } - - /** - * Concatenates all iterators contained in an array. - * - *

- * This method returns an iterator that will enumerate in order the elements - * returned by all iterators contained in the given array. - * - * @param a - * an array of iterators. - * @return an iterator obtained by concatenation. - */ - - public static IntIterator concat(final IntIterator a[]) { - return concat(a, 0, a.length); - } - - /** - * Concatenates a sequence of iterators contained in an array. - * - *

- * This method returns an iterator that will enumerate in order the elements - * returned by a[ offset ], then those returned by - * a[ offset + 1 ], and so on up to - * a[ offset + length - 1 ]. - * - * @param a - * an array of iterators. - * @param offset - * the index of the first iterator to concatenate. - * @param length - * the number of iterators to concatenate. - * @return an iterator obtained by concatenation of length - * elements of a starting at offset. - */ - - public static IntIterator concat(final IntIterator a[], final int offset, - final int length) { - return new IteratorConcatenator(a, offset, length); - } - - /** An unmodifiable wrapper class for iterators. */ - - public static class UnmodifiableIterator extends AbstractIntIterator { - final protected IntIterator i; - - public UnmodifiableIterator(final IntIterator i) { - this.i = i; - } - - public boolean hasNext() { - return i.hasNext(); - } - - public int nextInt() { - return i.nextInt(); - } - - /** - * {@inheritDoc} - * - * @deprecated Please use the corresponding type-specific method - * instead. - */ - @Deprecated - @Override - public Integer next() { - return i.next(); - } - - } - - /** - * Returns an unmodifiable iterator backed by the specified iterator. - * - * @param i - * the iterator to be wrapped in an unmodifiable iterator. - * @return an unmodifiable view of the specified iterator. - */ - public static IntIterator unmodifiable(final IntIterator i) { - return new UnmodifiableIterator(i); - } - - /** An unmodifiable wrapper class for bidirectional iterators. */ - - public static class UnmodifiableBidirectionalIterator - extends - AbstractIntBidirectionalIterator { - final protected IntBidirectionalIterator i; - - public UnmodifiableBidirectionalIterator( - final IntBidirectionalIterator i) { - this.i = i; - } - - public boolean hasNext() { - return i.hasNext(); - } - public boolean hasPrevious() { - return i.hasPrevious(); - } - public int nextInt() { - return i.nextInt(); - } - public int previousInt() { - return i.previousInt(); - } - - /** - * {@inheritDoc} - * - * @deprecated Please use the corresponding type-specific method - * instead. - */ - @Deprecated - @Override - public Integer next() { - return i.next(); - } - /** - * {@inheritDoc} - * - * @deprecated Please use the corresponding type-specific method - * instead. - */ - @Deprecated - @Override - public Integer previous() { - return i.previous(); - } - - } - - /** - * Returns an unmodifiable bidirectional iterator backed by the specified - * bidirectional iterator. - * - * @param i - * the bidirectional iterator to be wrapped in an unmodifiable - * bidirectional iterator. - * @return an unmodifiable view of the specified bidirectional iterator. - */ - public static IntBidirectionalIterator unmodifiable( - final IntBidirectionalIterator i) { - return new UnmodifiableBidirectionalIterator(i); - } - - /** An unmodifiable wrapper class for list iterators. */ - - public static class UnmodifiableListIterator - extends - AbstractIntListIterator { - final protected IntListIterator i; - - public UnmodifiableListIterator(final IntListIterator i) { - this.i = i; - } - - public boolean hasNext() { - return i.hasNext(); - } - public boolean hasPrevious() { - return i.hasPrevious(); - } - public int nextInt() { - return i.nextInt(); - } - public int previousInt() { - return i.previousInt(); - } - public int nextIndex() { - return i.nextIndex(); - } - public int previousIndex() { - return i.previousIndex(); - } - - /** - * {@inheritDoc} - * - * @deprecated Please use the corresponding type-specific method - * instead. - */ - @Deprecated - @Override - public Integer next() { - return i.next(); - } - /** - * {@inheritDoc} - * - * @deprecated Please use the corresponding type-specific method - * instead. - */ - @Deprecated - @Override - public Integer previous() { - return i.previous(); - } - - } - - /** - * Returns an unmodifiable list iterator backed by the specified list - * iterator. - * - * @param i - * the list iterator to be wrapped in an unmodifiable list - * iterator. - * @return an unmodifiable view of the specified list iterator. - */ - public static IntListIterator unmodifiable(final IntListIterator i) { - return new UnmodifiableListIterator(i); - } - - /** A wrapper promoting the results of a ByteIterator. */ - - protected static class ByteIteratorWrapper implements IntIterator { - final it.unimi.dsi.fastutil.bytes.ByteIterator iterator; - - public ByteIteratorWrapper( - final it.unimi.dsi.fastutil.bytes.ByteIterator iterator) { - this.iterator = iterator; - } - - public boolean hasNext() { - return iterator.hasNext(); - } - public Integer next() { - return Integer.valueOf(iterator.nextByte()); - } - public int nextInt() { - return iterator.nextByte(); - } - public void remove() { - iterator.remove(); - } - public int skip(final int n) { - return iterator.skip(n); - } - } - - /** - * Returns an iterator backed by the specified byte iterator. - * - * @return an iterator backed by the specified byte iterator. - */ - public static IntIterator wrap( - final it.unimi.dsi.fastutil.bytes.ByteIterator iterator) { - return new ByteIteratorWrapper(iterator); - } - - /** A wrapper promoting the results of a ShortIterator. */ - - protected static class ShortIteratorWrapper implements IntIterator { - final it.unimi.dsi.fastutil.shorts.ShortIterator iterator; - - public ShortIteratorWrapper( - final it.unimi.dsi.fastutil.shorts.ShortIterator iterator) { - this.iterator = iterator; - } - - public boolean hasNext() { - return iterator.hasNext(); - } - public Integer next() { - return Integer.valueOf(iterator.nextShort()); - } - public int nextInt() { - return iterator.nextShort(); - } - public void remove() { - iterator.remove(); - } - public int skip(final int n) { - return iterator.skip(n); - } - } - - /** - * Returns an iterator backed by the specified short iterator. - * - * @return an iterator backed by the specified short iterator. - */ - public static IntIterator wrap( - final it.unimi.dsi.fastutil.shorts.ShortIterator iterator) { - return new ShortIteratorWrapper(iterator); - } -} diff --git a/src/main/java/it/unimi/dsi/fastutil/ints/IntList.java b/src/main/java/it/unimi/dsi/fastutil/ints/IntList.java deleted file mode 100644 index a937104..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/ints/IntList.java +++ /dev/null @@ -1,269 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Primitive-type-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.ints; - -import it.unimi.dsi.fastutil.ints.IntCollection; -import it.unimi.dsi.fastutil.ints.IntListIterator; - -import java.util.List; - -/** - * A type-specific {@link List}; provides some additional methods that use - * polymorphism to avoid (un)boxing. - * - *

- * Note that this type-specific interface extends {@link Comparable}: it is - * expected that implementing classes perform a lexicographical comparison using - * the standard operator "less then" for primitive types, and the usual - * {@link Comparable#compareTo(Object) compareTo()} method for objects. - * - *

- * Additionally, this interface strengthens {@link #listIterator()}, - * {@link #listIterator(int)} and {@link #subList(int,int)}. - * - *

- * Besides polymorphic methods, this interfaces specifies methods to copy into - * an array or remove contiguous sublists. Although the abstract implementation - * of this interface provides simple, one-by-one implementations of these - * methods, it is expected that concrete implementation override them with - * optimized versions. - * - * @see List - */ - -public interface IntList - extends - List, - Comparable>, - IntCollection { - /** - * Returns a type-specific iterator on the elements of this list (in proper - * sequence). - * - * Note that this specification strengthens the one given in - * {@link List#iterator()}. It would not be normally necessary, but - * {@link Iterable#iterator()} is bizarrily re-specified in - * {@link List}. - * - * @return an iterator on the elements of this list (in proper sequence). - */ - IntListIterator iterator(); - - /** - * Returns a type-specific list iterator on the list. - * - * @see #listIterator() - * @deprecated As of fastutil 5, replaced by - * {@link #listIterator()}. - */ - @Deprecated - IntListIterator intListIterator(); - - /** - * Returns a type-specific list iterator on the list starting at a given - * index. - * - * @see #listIterator(int) - * @deprecated As of fastutil 5, replaced by - * {@link #listIterator(int)}. - */ - @Deprecated - IntListIterator intListIterator(int index); - - /** - * Returns a type-specific list iterator on the list. - * - * @see List#listIterator() - */ - IntListIterator listIterator(); - - /** - * Returns a type-specific list iterator on the list starting at a given - * index. - * - * @see List#listIterator(int) - */ - IntListIterator listIterator(int index); - - /** - * Returns a type-specific view of the portion of this list from the index - * from, inclusive, to the index to, exclusive. - * - * @see List#subList(int,int) - * @deprecated As of fastutil 5, replaced by - * {@link #subList(int,int)}. - */ - @Deprecated - it.unimi.dsi.fastutil.ints.IntList intSubList(int from, int to); - - /** - * Returns a type-specific view of the portion of this list from the index - * from, inclusive, to the index to, exclusive. - * - *

- * Note that this specification strengthens the one given in - * {@link List#subList(int,int)}. - * - * @see List#subList(int,int) - */ - it.unimi.dsi.fastutil.ints.IntList subList(int from, int to); - - /** - * Sets the size of this list. - * - *

- * If the specified size is smaller than the current size, the last elements - * are discarded. Otherwise, they are filled with 0/null/ - * false. - * - * @param size - * the new size. - */ - - void size(int size); - - /** - * Copies (hopefully quickly) elements of this type-specific list into the - * given array. - * - * @param from - * the start index (inclusive). - * @param a - * the destination array. - * @param offset - * the offset into the destination array where to store the first - * element copied. - * @param length - * the number of elements to be copied. - */ - void getElements(int from, int a[], int offset, int length); - - /** - * Removes (hopefully quickly) elements of this type-specific list. - * - * @param from - * the start index (inclusive). - * @param to - * the end index (exclusive). - */ - void removeElements(int from, int to); - - /** - * Add (hopefully quickly) elements to this type-specific list. - * - * @param index - * the index at which to add elements. - * @param a - * the array containing the elements. - */ - void addElements(int index, int a[]); - - /** - * Add (hopefully quickly) elements to this type-specific list. - * - * @param index - * the index at which to add elements. - * @param a - * the array containing the elements. - * @param offset - * the offset of the first element to add. - * @param length - * the number of elements to add. - */ - void addElements(int index, int a[], int offset, int length); - - /** - * @see List#add(Object) - */ - boolean add(int key); - - /** - * @see List#add(int,Object) - */ - void add(int index, int key); - - /** - * @see List#add(int,Object) - */ - boolean addAll(int index, IntCollection c); - - /** - * @see List#add(int,Object) - */ - boolean addAll(int index, it.unimi.dsi.fastutil.ints.IntList c); - - /** - * @see List#add(int,Object) - */ - boolean addAll(it.unimi.dsi.fastutil.ints.IntList c); - - /** - * @see List#get(int) - */ - int getInt(int index); - - /** - * @see List#indexOf(Object) - */ - int indexOf(int k); - - /** - * @see List#lastIndexOf(Object) - */ - int lastIndexOf(int k); - - /** - * @see List#remove(int) - */ - int removeInt(int index); - - /** - * @see List#set(int,Object) - */ - int set(int index, int k); - -} diff --git a/src/main/java/it/unimi/dsi/fastutil/ints/IntListIterator.java b/src/main/java/it/unimi/dsi/fastutil/ints/IntListIterator.java deleted file mode 100644 index f000968..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/ints/IntListIterator.java +++ /dev/null @@ -1,75 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Primitive-type-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.ints; - -import it.unimi.dsi.fastutil.ints.IntBidirectionalIterator; - -import java.util.ListIterator; - -/** - * A type-specific bidirectional iterator that is also a {@link ListIterator}. - * - *

- * This interface merges the methods provided by a {@link ListIterator} and a - * type-specific {@link it.unimi.dsi.fastutil.BidirectionalIterator}. Moreover, - * it provides type-specific versions of - * {@link ListIterator#add(Object) add()} and - * {@link ListIterator#set(Object) set()}. - * - * @see ListIterator - * @see it.unimi.dsi.fastutil.BidirectionalIterator - */ - -public interface IntListIterator - extends - ListIterator, - IntBidirectionalIterator { - - void set(int k); - void add(int k); - -} diff --git a/src/main/java/it/unimi/dsi/fastutil/ints/IntSet.java b/src/main/java/it/unimi/dsi/fastutil/ints/IntSet.java deleted file mode 100644 index dbb8447..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/ints/IntSet.java +++ /dev/null @@ -1,92 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Primitive-type-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.ints; - -import it.unimi.dsi.fastutil.ints.IntCollection; -import it.unimi.dsi.fastutil.ints.IntIterator; - -import java.util.Set; - -/** - * A type-specific {@link Set}; provides some additional methods that use - * polymorphism to avoid (un)boxing. - * - *

- * Additionally, this interface strengthens (again) {@link #iterator()}. - * - * @see Set - */ - -public interface IntSet - extends IntCollection, Set { - - /** - * Returns a type-specific iterator on the elements of this set. - * - *

- * Note that this specification strengthens the one given in - * {@link Iterable#iterator()}, which was already strengthened in - * the corresponding type-specific class, but was weakened by the fact that - * this interface extends {@link Set}. - * - * @return a type-specific iterator on the elements of this set. - */ - IntIterator iterator(); - - /** - * Removes an element from this set. - * - *

- * Note that the corresponding method of the type-specific collection is - * rem(). This unfortunate situation is caused by the clash - * with the similarly named index-based method in the {@link java.util.List} - * interface. - * - * @see java.util.Collection#remove(Object) - */ - public boolean remove(int k); -} diff --git a/src/main/java/it/unimi/dsi/fastutil/ints/IntStack.java b/src/main/java/it/unimi/dsi/fastutil/ints/IntStack.java deleted file mode 100644 index 3e7f681..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/ints/IntStack.java +++ /dev/null @@ -1,81 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Primitive-type-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.ints; - -import it.unimi.dsi.fastutil.Stack; - -/** - * A type-specific {@link Stack}; provides some additional methods that use - * polymorphism to avoid (un)boxing. - */ - -public interface IntStack extends Stack { - - /** - * @see Stack#push(Object) - */ - - void push(int k); - - /** - * @see Stack#pop() - */ - int popInt(); - - /** - * @see Stack#top() - */ - - int topInt(); - - /** - * @see Stack#peek(int) - */ - - int peekInt(int i); - -} diff --git a/src/main/java/it/unimi/dsi/fastutil/objects/AbstractObject2IntFunction.java b/src/main/java/it/unimi/dsi/fastutil/objects/AbstractObject2IntFunction.java deleted file mode 100644 index 45ee9d6..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/objects/AbstractObject2IntFunction.java +++ /dev/null @@ -1,169 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* Primitive-type-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.objects; - -import it.unimi.dsi.fastutil.objects.Object2IntFunction; - -/** - * An abstract class providing basic methods for functions implementing a - * type-specific interface. - * - *

- * Optional operations just throw an {@link UnsupportedOperationException}. - * Generic versions of accessors delegate to the corresponding type-specific - * counterparts following the interface rules (they take care of returning - * null on a missing key). - * - *

- * This class handles directly a default return value (including - * {@linkplain #defaultReturnValue() methods to access it}). Instances of classes - * inheriting from this class have just to return defRetValue to - * denote lack of a key in type-specific methods. The value is serialized. - * - *

- * Implementing subclasses have just to provide type-specific get() - * , type-specific containsKey(), and size() methods. - * - */ - -public abstract class AbstractObject2IntFunction - implements - Object2IntFunction, - java.io.Serializable { - - private static final long serialVersionUID = -4940583368468432370L; - - protected AbstractObject2IntFunction() { - } - - /** - * The default return value for get(), put() and - * remove(). - */ - - protected int defRetValue; - - public void defaultReturnValue(final int rv) { - defRetValue = rv; - } - - public int defaultReturnValue() { - return defRetValue; - } - - public int put(K key, int value) { - throw new UnsupportedOperationException(); - } - - public int removeInt(Object key) { - throw new UnsupportedOperationException(); - } - - public void clear() { - throw new UnsupportedOperationException(); - } - /** - * Delegates to the corresponding type-specific method, taking care of - * returning null on a missing key. - * - *

- * This method must check whether the provided key is in the map using - * containsKey(). Thus, it probes the map twice. - * Implementors of subclasses should override it with a more efficient - * method. - * - * @deprecated Please use the corresponding type-specific method instead. - */ - @Deprecated - public Integer get(final Object ok) { - - final Object k = (ok); - return containsKey(k) ? (Integer.valueOf(getInt(k))) : null; - } - - /** - * Delegates to the corresponding type-specific method, taking care of - * returning null on a missing key. - * - *

- * This method must check whether the provided key is in the map using - * containsKey(). Thus, it probes the map twice. - * Implementors of subclasses should override it with a more efficient - * method. - * - * @deprecated Please use the corresponding type-specific method instead. - */ - @Deprecated - public Integer put(final K ok, final Integer ov) { - final K k = (ok); - final boolean containsKey = containsKey(k); - final int v = put(k, ((ov).intValue())); - return containsKey ? (Integer.valueOf(v)) : null; - } - - /** - * Delegates to the corresponding type-specific method, taking care of - * returning null on a missing key. - * - *

- * This method must check whether the provided key is in the map using - * containsKey(). Thus, it probes the map twice. - * Implementors of subclasses should override it with a more efficient - * method. - * - * @deprecated Please use the corresponding type-specific method instead. - */ - @Deprecated - public Integer remove(final Object ok) { - - final Object k = (ok); - final boolean containsKey = containsKey(k); - final int v = removeInt(k); - return containsKey ? (Integer.valueOf(v)) : null; - } - -} diff --git a/src/main/java/it/unimi/dsi/fastutil/objects/AbstractObject2IntMap.java b/src/main/java/it/unimi/dsi/fastutil/objects/AbstractObject2IntMap.java deleted file mode 100644 index fcfa665..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/objects/AbstractObject2IntMap.java +++ /dev/null @@ -1,392 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* Primitive-type-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.objects; - -import it.unimi.dsi.fastutil.ints.AbstractIntCollection; -import it.unimi.dsi.fastutil.ints.AbstractIntIterator; -import it.unimi.dsi.fastutil.ints.IntCollection; -import it.unimi.dsi.fastutil.ints.IntIterator; -import it.unimi.dsi.fastutil.objects.AbstractObject2IntFunction; -import it.unimi.dsi.fastutil.objects.AbstractObjectIterator; -import it.unimi.dsi.fastutil.objects.AbstractObjectSet; -import it.unimi.dsi.fastutil.objects.Object2IntMap; -import it.unimi.dsi.fastutil.objects.ObjectIterator; -import it.unimi.dsi.fastutil.objects.ObjectSet; - -import java.util.Iterator; -import java.util.Map; - -/** - * An abstract class providing basic methods for maps implementing a - * type-specific interface. - * - *

- * Optional operations just throw an {@link UnsupportedOperationException}. - * Generic versions of accessors delegate to the corresponding type-specific - * counterparts following the interface rules (they take care of returning - * null on a missing key). - * - *

- * As a further help, this class provides a {@link BasicEntry BasicEntry} inner - * class that implements a type-specific version of {@link Map.Entry}; - * it is particularly useful for those classes that do not implement their own - * entries (e.g., most immutable maps). - */ - -public abstract class AbstractObject2IntMap - extends - AbstractObject2IntFunction - implements - Object2IntMap, - java.io.Serializable { - - private static final long serialVersionUID = -4940583368468432370L; - - protected AbstractObject2IntMap() { - } - - public boolean containsValue(Object ov) { - if (ov == null) - return false; - return containsValue(((((Integer) (ov)).intValue()))); - } - - /** Checks whether the given value is contained in {@link #values()}. */ - public boolean containsValue(int v) { - return values().contains(v); - } - - /** Checks whether the given value is contained in {@link #keySet()}. */ - public boolean containsKey(Object k) { - return keySet().contains(k); - } - - /** - * Puts all pairs in the given map. If the map implements the interface of - * this map, it uses the faster iterators. - * - * @param m - * a map. - */ - - @SuppressWarnings({"unchecked", "deprecation"}) - public void putAll(Map m) { - int n = m.size(); - final Iterator> i = m - .entrySet().iterator(); - - if (m instanceof Object2IntMap) { - Entry e; - while (n-- != 0) { - e = (Entry) i.next(); - put(e.getKey(), e.getIntValue()); - } - } else { - Map.Entry e; - while (n-- != 0) { - e = i.next(); - put(e.getKey(), e.getValue()); - } - } - } - - public boolean isEmpty() { - return size() == 0; - } - - /** - * This class provides a basic but complete type-specific entry class for - * all those maps implementations that do not have entries on their own - * (e.g., most immutable maps). - * - *

- * This class does not implement - * {@link Map.Entry#setValue(Object) setValue()}, as the - * modification would not be reflected in the base map. - */ - - public static class BasicEntry implements Entry { - protected K key; - protected int value; - - public BasicEntry(final K key, final Integer value) { - this.key = (key); - this.value = ((value).intValue()); - } - - public BasicEntry(final K key, final int value) { - this.key = key; - this.value = value; - } - public K getKey() { - return (key); - } - /** - * {@inheritDoc} - * - * @deprecated Please use the corresponding type-specific method - * instead. - */ - @Deprecated - public Integer getValue() { - return (Integer.valueOf(value)); - } - - public int getIntValue() { - return value; - } - - public int setValue(final int value) { - throw new UnsupportedOperationException(); - } - - /** - * {@inheritDoc} - * - * @deprecated Please use the corresponding type-specific method - * instead. - */ - @Deprecated - public Integer setValue(final Integer value) { - return Integer.valueOf(setValue(value.intValue())); - } - - public boolean equals(final Object o) { - if (!(o instanceof Map.Entry)) - return false; - final Map.Entry e = (Map.Entry) o; - - if (e.getValue() == null || !(e.getValue() instanceof Integer)) - return false; - - return ((key) == null ? ((e.getKey())) == null : (key).equals((e - .getKey()))) - && ((value) == (((((Integer) (e.getValue())).intValue())))); - } - - public int hashCode() { - return ((key) == null ? 0 : (key).hashCode()) ^ (value); - } - - public String toString() { - return key + "->" + value; - } - } - - /** - * Returns a type-specific-set view of the keys of this map. - * - *

- * The view is backed by the set returned by {@link #entrySet()}. Note that - * no attempt is made at caching the result of this method, as this - * would require adding some attributes that lightweight implementations - * would not need. Subclasses may easily override this policy by calling - * this method and caching the result, but implementors are encouraged to - * write more efficient ad-hoc implementations. - * - * @return a set view of the keys of this map; it may be safely cast to a - * type-specific interface. - */ - - public ObjectSet keySet() { - return new AbstractObjectSet() { - - public boolean contains(final Object k) { - return containsKey(k); - } - - public int size() { - return it.unimi.dsi.fastutil.objects.AbstractObject2IntMap.this.size(); - } - public void clear() { - it.unimi.dsi.fastutil.objects.AbstractObject2IntMap.this.clear(); - } - - public ObjectIterator iterator() { - return new AbstractObjectIterator() { - final ObjectIterator> i = entrySet() - .iterator(); - @Override - public K next() { - return ((Entry) i.next()).getKey(); - }; - @Override - public boolean hasNext() { - return i.hasNext(); - } - @Override - public void remove() { - i.remove(); - } - }; - } - }; - } - - /** - * Returns a type-specific-set view of the values of this map. - * - *

- * The view is backed by the set returned by {@link #entrySet()}. Note that - * no attempt is made at caching the result of this method, as this - * would require adding some attributes that lightweight implementations - * would not need. Subclasses may easily override this policy by calling - * this method and caching the result, but implementors are encouraged to - * write more efficient ad-hoc implementations. - * - * @return a set view of the values of this map; it may be safely cast to a - * type-specific interface. - */ - - public IntCollection values() { - return new AbstractIntCollection() { - - public boolean contains(final int k) { - return containsValue(k); - } - - public int size() { - return it.unimi.dsi.fastutil.objects.AbstractObject2IntMap.this.size(); - } - public void clear() { - it.unimi.dsi.fastutil.objects.AbstractObject2IntMap.this.clear(); - } - - public IntIterator iterator() { - return new AbstractIntIterator() { - final ObjectIterator> i = entrySet() - .iterator(); - - /** - * {@inheritDoc} - * - * @deprecated Please use the corresponding type-specific - * method instead. - */ - @Deprecated - public int nextInt() { - return ((Entry) i.next()) - .getIntValue(); - }; - - public boolean hasNext() { - return i.hasNext(); - } - }; - } - }; - } - - @SuppressWarnings({"unchecked", "rawtypes"}) - public ObjectSet> entrySet() { - return (ObjectSet) object2IntEntrySet(); - } - - /** - * Returns a hash code for this map. - * - * The hash code of a map is computed by summing the hash codes of its - * entries. - * - * @return a hash code for this map. - */ - - public int hashCode() { - int h = 0, n = size(); - final ObjectIterator> i = entrySet() - .iterator(); - - while (n-- != 0) - h += i.next().hashCode(); - return h; - } - - public boolean equals(Object o) { - if (o == this) - return true; - if (!(o instanceof Map)) - return false; - - Map m = (Map) o; - if (m.size() != size()) - return false; - return entrySet().containsAll(m.entrySet()); - } - - public String toString() { - final StringBuilder s = new StringBuilder(); - final ObjectIterator> i = entrySet() - .iterator(); - int n = size(); - Entry e; - boolean first = true; - - s.append("{"); - - while (n-- != 0) { - if (first) - first = false; - else - s.append(", "); - - e = (Entry) i.next(); - - if (this == e.getKey()) - s.append("(this map)"); - else - - s.append(String.valueOf(e.getKey())); - s.append("=>"); - - s.append(String.valueOf(e.getIntValue())); - } - - s.append("}"); - return s.toString(); - } - -} diff --git a/src/main/java/it/unimi/dsi/fastutil/objects/AbstractObjectBidirectionalIterator.java b/src/main/java/it/unimi/dsi/fastutil/objects/AbstractObjectBidirectionalIterator.java deleted file mode 100644 index 03ab1e8..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/objects/AbstractObjectBidirectionalIterator.java +++ /dev/null @@ -1,86 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.objects; - -import it.unimi.dsi.fastutil.objects.AbstractObjectIterator; -import it.unimi.dsi.fastutil.objects.ObjectBidirectionalIterator; - -/** - * An abstract class facilitating the creation of type-specific - * {@linkplain it.unimi.dsi.fastutil.BidirectionalIterator bidirectional - * iterators}. - * - *

- * To create a type-specific bidirectional iterator, besides what is needed for - * an iterator you need both a method returning the previous element as - * primitive type and a method returning the previous element as an object. - * However, if you inherit from this class you need just one (anyone). - * - *

- * This class implements also a trivial version of {@link #back(int)} that uses - * type-specific methods. - */ - -public abstract class AbstractObjectBidirectionalIterator - extends - AbstractObjectIterator - implements ObjectBidirectionalIterator { - - protected AbstractObjectBidirectionalIterator() { - } - /** - * This method just iterates the type-specific version of - * {@link #previous()} for at most n times, stopping if - * {@link #hasPrevious()} becomes false. - */ - public int back(final int n) { - int i = n; - while (i-- != 0 && hasPrevious()) - previous(); - return n - i - 1; - } - -} diff --git a/src/main/java/it/unimi/dsi/fastutil/objects/AbstractObjectCollection.java b/src/main/java/it/unimi/dsi/fastutil/objects/AbstractObjectCollection.java deleted file mode 100644 index 2e616d7..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/objects/AbstractObjectCollection.java +++ /dev/null @@ -1,218 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.objects; - -import it.unimi.dsi.fastutil.objects.ObjectCollection; -import it.unimi.dsi.fastutil.objects.ObjectIterator; - -import java.util.AbstractCollection; -import java.util.Collection; -import java.util.Iterator; - -/** - * An abstract class providing basic methods for collections implementing a - * type-specific interface. - * - *

- * In particular, this class provide {@link #iterator()}, add(), - * {@link #remove(Object)} and {@link #contains(Object)} methods that just call - * the type-specific counterpart. - */ - -public abstract class AbstractObjectCollection extends AbstractCollection - implements - ObjectCollection { - - protected AbstractObjectCollection() { - } - public Object[] toArray() { - final Object[] a = new Object[size()]; - it.unimi.dsi.fastutil.objects.ObjectIterators.unwrap(iterator(), a); - return a; - } - - @SuppressWarnings("unchecked") - public T[] toArray(T[] a) { - final int size = size(); - if (a.length < size) - a = (T[]) java.lang.reflect.Array.newInstance(a.getClass() - .getComponentType(), size); - it.unimi.dsi.fastutil.objects.ObjectIterators.unwrap(iterator(), a); - if (size < a.length) - a[size] = null; - return a; - } - - /** - * Adds all elements of the given collection to this collection. - * - * @param c - * a collection. - * @return true if this collection changed as a result of the - * call. - */ - - public boolean addAll(Collection c) { - boolean retVal = false; - final Iterator i = c.iterator(); - int n = c.size(); - - while (n-- != 0) - if (add(i.next())) - retVal = true; - return retVal; - } - - public boolean add(K k) { - throw new UnsupportedOperationException(); - } - - /** Delegates to the new covariantly stronger generic method. */ - - @Deprecated - public ObjectIterator objectIterator() { - return iterator(); - } - - public abstract ObjectIterator iterator(); - /** - * Checks whether this collection contains all elements from the given - * collection. - * - * @param c - * a collection. - * @return true if this collection contains all elements of the - * argument. - */ - - public boolean containsAll(Collection c) { - int n = c.size(); - - final Iterator i = c.iterator(); - while (n-- != 0) - if (!contains(i.next())) - return false; - - return true; - } - - /** - * Retains in this collection only elements from the given collection. - * - * @param c - * a collection. - * @return true if this collection changed as a result of the - * call. - */ - - public boolean retainAll(Collection c) { - boolean retVal = false; - int n = size(); - - final Iterator i = iterator(); - while (n-- != 0) { - if (!c.contains(i.next())) { - i.remove(); - retVal = true; - } - } - - return retVal; - } - - /** - * Remove from this collection all elements in the given collection. If the - * collection is an instance of this class, it uses faster iterators. - * - * @param c - * a collection. - * @return true if this collection changed as a result of the - * call. - */ - - public boolean removeAll(Collection c) { - boolean retVal = false; - int n = c.size(); - - final Iterator i = c.iterator(); - while (n-- != 0) - if (remove(i.next())) - retVal = true; - - return retVal; - } - - public boolean isEmpty() { - return size() == 0; - } - - public String toString() { - final StringBuilder s = new StringBuilder(); - final ObjectIterator i = iterator(); - int n = size(); - Object k; - boolean first = true; - - s.append("{"); - - while (n-- != 0) { - if (first) - first = false; - else - s.append(", "); - k = i.next(); - - if (this == k) - s.append("(this collection)"); - else - - s.append(String.valueOf(k)); - } - - s.append("}"); - return s.toString(); - } -} diff --git a/src/main/java/it/unimi/dsi/fastutil/objects/AbstractObjectIterator.java b/src/main/java/it/unimi/dsi/fastutil/objects/AbstractObjectIterator.java deleted file mode 100644 index 5011764..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/objects/AbstractObjectIterator.java +++ /dev/null @@ -1,87 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.objects; - -import it.unimi.dsi.fastutil.objects.ObjectIterator; - -/** - * An abstract class facilitating the creation of type-specific iterators. - * - *

- * To create a type-specific iterator you need both a method returning the next - * element as primitive type and a method returning the next element as an - * object. However, if you inherit from this class you need just one (anyone). - * - *

- * This class implements also a trivial version of {@link #skip(int)} that uses - * type-specific methods; moreover, {@link #remove()} will throw an - * {@link UnsupportedOperationException}. - * - * @see java.util.Iterator - */ - -public abstract class AbstractObjectIterator implements ObjectIterator { - - protected AbstractObjectIterator() { - } - /** This method just throws an {@link UnsupportedOperationException}. */ - public void remove() { - throw new UnsupportedOperationException(); - } - - /** - * This method just iterates the type-specific version of {@link #next()} - * for at most n times, stopping if {@link #hasNext()} becomes - * false. - */ - - public int skip(final int n) { - int i = n; - while (i-- != 0 && hasNext()) - next(); - return n - i - 1; - } -} diff --git a/src/main/java/it/unimi/dsi/fastutil/objects/AbstractObjectList.java b/src/main/java/it/unimi/dsi/fastutil/objects/AbstractObjectList.java deleted file mode 100644 index f826515..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/objects/AbstractObjectList.java +++ /dev/null @@ -1,689 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.objects; - -import it.unimi.dsi.fastutil.Stack; -import it.unimi.dsi.fastutil.objects.AbstractObjectCollection; -import it.unimi.dsi.fastutil.objects.AbstractObjectListIterator; -import it.unimi.dsi.fastutil.objects.ObjectIterator; -import it.unimi.dsi.fastutil.objects.ObjectList; -import it.unimi.dsi.fastutil.objects.ObjectListIterator; - -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; -import java.util.NoSuchElementException; - -/** - * An abstract class providing basic methods for lists implementing a - * type-specific list interface. - * - *

- * As an additional bonus, this class implements on top of the list operations a - * type-specific stack. - */ - -public abstract class AbstractObjectList extends AbstractObjectCollection - implements - ObjectList, - Stack { - - protected AbstractObjectList() { - } - - /** - * Ensures that the given index is nonnegative and not greater than the list - * size. - * - * @param index - * an index. - * @throws IndexOutOfBoundsException - * if the given index is negative or greater than the list size. - */ - protected void ensureIndex(final int index) { - if (index < 0) - throw new IndexOutOfBoundsException("Index (" + index - + ") is negative"); - if (index > size()) - throw new IndexOutOfBoundsException("Index (" + index - + ") is greater than list size (" + (size()) + ")"); - } - - /** - * Ensures that the given index is nonnegative and smaller than the list - * size. - * - * @param index - * an index. - * @throws IndexOutOfBoundsException - * if the given index is negative or not smaller than the list - * size. - */ - protected void ensureRestrictedIndex(final int index) { - if (index < 0) - throw new IndexOutOfBoundsException("Index (" + index - + ") is negative"); - if (index >= size()) - throw new IndexOutOfBoundsException("Index (" + index - + ") is greater than or equal to list size (" + (size()) - + ")"); - } - - public void add(final int index, final K k) { - throw new UnsupportedOperationException(); - } - - public boolean add(final K k) { - add(size(), k); - return true; - } - - public K remove(int i) { - throw new UnsupportedOperationException(); - } - - public K set(final int index, final K k) { - throw new UnsupportedOperationException(); - } - - public boolean addAll(int index, final Collection c) { - ensureIndex(index); - int n = c.size(); - if (n == 0) - return false; - Iterator i = c.iterator(); - while (n-- != 0) - add(index++, i.next()); - return true; - } - - /** Delegates to a more generic method. */ - public boolean addAll(final Collection c) { - return addAll(size(), c); - } - - /** Delegates to the new covariantly stronger generic method. */ - - @Deprecated - public ObjectListIterator objectListIterator() { - return listIterator(); - } - - /** Delegates to the new covariantly stronger generic method. */ - - @Deprecated - public ObjectListIterator objectListIterator(final int index) { - return listIterator(index); - } - - public ObjectListIterator iterator() { - return listIterator(); - } - - public ObjectListIterator listIterator() { - return listIterator(0); - } - - public ObjectListIterator listIterator(final int index) { - ensureIndex(index); - - return new AbstractObjectListIterator() { - int pos = index, last = -1; - - public boolean hasNext() { - return pos < it.unimi.dsi.fastutil.objects.AbstractObjectList.this.size(); - } - public boolean hasPrevious() { - return pos > 0; - } - public K next() { - if (!hasNext()) - throw new NoSuchElementException(); - return it.unimi.dsi.fastutil.objects.AbstractObjectList.this.get(last = pos++); - } - public K previous() { - if (!hasPrevious()) - throw new NoSuchElementException(); - return it.unimi.dsi.fastutil.objects.AbstractObjectList.this.get(last = --pos); - } - public int nextIndex() { - return pos; - } - public int previousIndex() { - return pos - 1; - } - public void add(K k) { - it.unimi.dsi.fastutil.objects.AbstractObjectList.this.add(pos++, k); - last = -1; - } - public void set(K k) { - if (last == -1) - throw new IllegalStateException(); - it.unimi.dsi.fastutil.objects.AbstractObjectList.this.set(last, k); - } - public void remove() { - if (last == -1) - throw new IllegalStateException(); - it.unimi.dsi.fastutil.objects.AbstractObjectList.this.remove(last); - /* - * If the last operation was a next(), we are removing an - * element *before* us, and we must decrease pos - * correspondingly. - */ - if (last < pos) - pos--; - last = -1; - } - }; - } - - public boolean contains(final Object k) { - return indexOf(k) >= 0; - } - - public int indexOf(final Object k) { - final ObjectListIterator i = listIterator(); - K e; - while (i.hasNext()) { - e = i.next(); - if (((k) == null ? (e) == null : (k).equals(e))) - return i.previousIndex(); - } - return -1; - } - - public int lastIndexOf(final Object k) { - ObjectListIterator i = listIterator(size()); - K e; - while (i.hasPrevious()) { - e = i.previous(); - if (((k) == null ? (e) == null : (k).equals(e))) - return i.nextIndex(); - } - return -1; - } - - public void size(final int size) { - int i = size(); - if (size > i) - while (i++ < size) - add((null)); - else - while (i-- != size) - remove(i); - } - - public ObjectList subList(final int from, final int to) { - ensureIndex(from); - ensureIndex(to); - if (from > to) - throw new IndexOutOfBoundsException("Start index (" + from - + ") is greater than end index (" + to + ")"); - - return new ObjectSubList(this, from, to); - } - - /** Delegates to the new covariantly stronger generic method. */ - - @Deprecated - public ObjectList objectSubList(final int from, final int to) { - return subList(from, to); - } - - /** - * Removes elements of this type-specific list one-by-one. - * - *

- * This is a trivial iterator-based implementation. It is expected that - * implementations will override this method with a more optimized version. - * - * - * @param from - * the start index (inclusive). - * @param to - * the end index (exclusive). - */ - - public void removeElements(final int from, final int to) { - ensureIndex(to); - ObjectListIterator i = listIterator(from); - int n = to - from; - if (n < 0) - throw new IllegalArgumentException("Start index (" + from - + ") is greater than end index (" + to + ")"); - while (n-- != 0) { - i.next(); - i.remove(); - } - } - - /** - * Adds elements to this type-specific list one-by-one. - * - *

- * This is a trivial iterator-based implementation. It is expected that - * implementations will override this method with a more optimized version. - * - * @param index - * the index at which to add elements. - * @param a - * the array containing the elements. - * @param offset - * the offset of the first element to add. - * @param length - * the number of elements to add. - */ - - public void addElements(int index, final K a[], int offset, int length) { - ensureIndex(index); - if (offset < 0) - throw new ArrayIndexOutOfBoundsException("Offset (" + offset - + ") is negative"); - if (offset + length > a.length) - throw new ArrayIndexOutOfBoundsException("End index (" - + (offset + length) + ") is greater than array length (" - + a.length + ")"); - while (length-- != 0) - add(index++, a[offset++]); - } - - public void addElements(final int index, final K a[]) { - addElements(index, a, 0, a.length); - } - - /** - * Copies element of this type-specific list into the given array - * one-by-one. - * - *

- * This is a trivial iterator-based implementation. It is expected that - * implementations will override this method with a more optimized version. - * - * @param from - * the start index (inclusive). - * @param a - * the destination array. - * @param offset - * the offset into the destination array where to store the first - * element copied. - * @param length - * the number of elements to be copied. - */ - - public void getElements(final int from, final Object a[], int offset, - int length) { - ObjectListIterator i = listIterator(from); - if (offset < 0) - throw new ArrayIndexOutOfBoundsException("Offset (" + offset - + ") is negative"); - if (offset + length > a.length) - throw new ArrayIndexOutOfBoundsException("End index (" - + (offset + length) + ") is greater than array length (" - + a.length + ")"); - if (from + length > size()) - throw new IndexOutOfBoundsException("End index (" + (from + length) - + ") is greater than list size (" + size() + ")"); - while (length-- != 0) - a[offset++] = i.next(); - } - - private boolean valEquals(final Object a, final Object b) { - return a == null ? b == null : a.equals(b); - } - - public boolean equals(final Object o) { - if (o == this) - return true; - if (!(o instanceof List)) - return false; - - final List l = (List) o; - int s = size(); - if (s != l.size()) - return false; - final ListIterator i1 = listIterator(), i2 = l.listIterator(); - - while (s-- != 0) - if (!valEquals(i1.next(), i2.next())) - return false; - - return true; - } - - /** - * Compares this list to another object. If the argument is a - * {@link List}, this method performs a lexicographical - * comparison; otherwise, it throws a ClassCastException. - * - * @param l - * a list. - * @return if the argument is a {@link List}, a negative integer, - * zero, or a positive integer as this list is lexicographically - * less than, equal to, or greater than the argument. - * @throws ClassCastException - * if the argument is not a list. - */ - - @SuppressWarnings("unchecked") - public int compareTo(final List l) { - if (l == this) - return 0; - - if (l instanceof ObjectList) { - - final ObjectListIterator i1 = listIterator(), i2 = ((ObjectList) l) - .listIterator(); - int r; - K e1, e2; - - while (i1.hasNext() && i2.hasNext()) { - e1 = i1.next(); - e2 = i2.next(); - if ((r = (((Comparable) (e1)).compareTo(e2))) != 0) - return r; - } - return i2.hasNext() ? -1 : (i1.hasNext() ? 1 : 0); - } - - ListIterator i1 = listIterator(), i2 = l.listIterator(); - int r; - - while (i1.hasNext() && i2.hasNext()) { - if ((r = ((Comparable) i1.next()).compareTo(i2.next())) != 0) - return r; - } - return i2.hasNext() ? -1 : (i1.hasNext() ? 1 : 0); - } - - /** - * Returns the hash code for this list, which is identical to - * {@link List#hashCode()}. - * - * @return the hash code for this list. - */ - public int hashCode() { - ObjectIterator i = iterator(); - int h = 1, s = size(); - while (s-- != 0) { - K k = i.next(); - h = 31 * h + ((k) == null ? 0 : (k).hashCode()); - } - return h; - } - - public void push(K o) { - add(o); - } - - public K pop() { - if (isEmpty()) - throw new NoSuchElementException(); - return remove(size() - 1); - } - - public K top() { - if (isEmpty()) - throw new NoSuchElementException(); - return get(size() - 1); - } - - public K peek(int i) { - return get(size() - 1 - i); - } - public String toString() { - final StringBuilder s = new StringBuilder(); - final ObjectIterator i = iterator(); - int n = size(); - K k; - boolean first = true; - - s.append("["); - - while (n-- != 0) { - if (first) - first = false; - else - s.append(", "); - k = i.next(); - - if (this == k) - s.append("(this list)"); - else - - s.append(String.valueOf(k)); - } - - s.append("]"); - return s.toString(); - } - - public static class ObjectSubList extends it.unimi.dsi.fastutil.objects.AbstractObjectList - implements - java.io.Serializable { - private static final long serialVersionUID = -7046029254386353129L; - /** The list this sublist restricts. */ - protected final ObjectList l; - /** Initial (inclusive) index of this sublist. */ - protected final int from; - /** Final (exclusive) index of this sublist. */ - protected int to; - - private static final boolean ASSERTS = false; - - public ObjectSubList(final ObjectList l, final int from, final int to) { - this.l = l; - this.from = from; - this.to = to; - } - - private void assertRange() { - if (ASSERTS) { - assert from <= l.size(); - assert to <= l.size(); - assert to >= from; - } - } - - public boolean add(final K k) { - l.add(to, k); - to++; - if (ASSERTS) - assertRange(); - return true; - } - - public void add(final int index, final K k) { - ensureIndex(index); - l.add(from + index, k); - to++; - if (ASSERTS) - assertRange(); - } - - public boolean addAll(final int index, final Collection c) { - ensureIndex(index); - to += c.size(); - if (ASSERTS) { - boolean retVal = l.addAll(from + index, c); - assertRange(); - return retVal; - } - return l.addAll(from + index, c); - } - - public K get(int index) { - ensureRestrictedIndex(index); - return l.get(from + index); - } - - public K remove(int index) { - ensureRestrictedIndex(index); - to--; - return l.remove(from + index); - } - - public K set(int index, K k) { - ensureRestrictedIndex(index); - return l.set(from + index, k); - } - - public void clear() { - removeElements(0, size()); - if (ASSERTS) - assertRange(); - } - - public int size() { - return to - from; - } - - public void getElements(final int from, final Object[] a, - final int offset, final int length) { - ensureIndex(from); - if (from + length > size()) - throw new IndexOutOfBoundsException("End index (" + from - + length + ") is greater than list size (" + size() - + ")"); - l.getElements(this.from + from, a, offset, length); - } - - public void removeElements(final int from, final int to) { - ensureIndex(from); - ensureIndex(to); - l.removeElements(this.from + from, this.from + to); - this.to -= (to - from); - if (ASSERTS) - assertRange(); - } - - public void addElements(int index, final K a[], int offset, int length) { - ensureIndex(index); - l.addElements(this.from + index, a, offset, length); - this.to += length; - if (ASSERTS) - assertRange(); - } - - public ObjectListIterator listIterator(final int index) { - ensureIndex(index); - - return new AbstractObjectListIterator() { - int pos = index, last = -1; - - public boolean hasNext() { - return pos < size(); - } - public boolean hasPrevious() { - return pos > 0; - } - public K next() { - if (!hasNext()) - throw new NoSuchElementException(); - return l.get(from + (last = pos++)); - } - public K previous() { - if (!hasPrevious()) - throw new NoSuchElementException(); - return l.get(from + (last = --pos)); - } - public int nextIndex() { - return pos; - } - public int previousIndex() { - return pos - 1; - } - public void add(K k) { - if (last == -1) - throw new IllegalStateException(); - ObjectSubList.this.add(pos++, k); - last = -1; - if (ASSERTS) - assertRange(); - } - public void set(K k) { - if (last == -1) - throw new IllegalStateException(); - ObjectSubList.this.set(last, k); - } - public void remove() { - if (last == -1) - throw new IllegalStateException(); - ObjectSubList.this.remove(last); - /* - * If the last operation was a next(), we are removing an - * element *before* us, and we must decrease pos - * correspondingly. - */ - if (last < pos) - pos--; - last = -1; - if (ASSERTS) - assertRange(); - } - }; - } - - public ObjectList subList(final int from, final int to) { - ensureIndex(from); - ensureIndex(to); - if (from > to) - throw new IllegalArgumentException("Start index (" + from - + ") is greater than end index (" + to + ")"); - - return new ObjectSubList(this, from, to); - } - public boolean remove(final Object o) { - int index = indexOf(o); - if (index == -1) - return false; - remove(index); - return true; - } - - } - -} diff --git a/src/main/java/it/unimi/dsi/fastutil/objects/AbstractObjectListIterator.java b/src/main/java/it/unimi/dsi/fastutil/objects/AbstractObjectListIterator.java deleted file mode 100644 index bcf5d8b..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/objects/AbstractObjectListIterator.java +++ /dev/null @@ -1,84 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.objects; - -import it.unimi.dsi.fastutil.objects.AbstractObjectBidirectionalIterator; -import it.unimi.dsi.fastutil.objects.ObjectListIterator; - -/** - * An abstract class facilitating the creation of type-specific - * {@linkplain java.util.ListIterator list iterators}. - * - *

- * This class provides trivial type-specific implementations of - * {@link java.util.ListIterator#set(Object) set()} and - * {@link java.util.ListIterator#add(Object) add()} which throw an - * {@link UnsupportedOperationException}. For primitive types, it also provides - * a trivial implementation of {@link java.util.ListIterator#set(Object) set()} - * and {@link java.util.ListIterator#add(Object) add()} that just invokes the - * type-specific one. - * - * - * @see java.util.ListIterator - */ - -public abstract class AbstractObjectListIterator - extends - AbstractObjectBidirectionalIterator - implements - ObjectListIterator { - - protected AbstractObjectListIterator() { - } - /** This method just throws an {@link UnsupportedOperationException}. */ - public void set(K k) { - throw new UnsupportedOperationException(); - } - /** This method just throws an {@link UnsupportedOperationException}. */ - public void add(K k) { - throw new UnsupportedOperationException(); - } -} diff --git a/src/main/java/it/unimi/dsi/fastutil/objects/AbstractObjectSet.java b/src/main/java/it/unimi/dsi/fastutil/objects/AbstractObjectSet.java deleted file mode 100644 index 65b756c..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/objects/AbstractObjectSet.java +++ /dev/null @@ -1,102 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.objects; - -import it.unimi.dsi.fastutil.objects.AbstractObjectCollection; -import it.unimi.dsi.fastutil.objects.ObjectIterator; -import it.unimi.dsi.fastutil.objects.ObjectSet; - -import java.util.Set; - -/** - * An abstract class providing basic methods for sets implementing a - * type-specific interface. - */ - -public abstract class AbstractObjectSet extends AbstractObjectCollection - implements - Cloneable, - ObjectSet { - - protected AbstractObjectSet() { - } - - public abstract ObjectIterator iterator(); - - public boolean equals(final Object o) { - if (o == this) - return true; - if (!(o instanceof Set)) - return false; - - Set s = (Set) o; - if (s.size() != size()) - return false; - return containsAll(s); - } - - /** - * Returns a hash code for this set. - * - * The hash code of a set is computed by summing the hash codes of its - * elements. - * - * @return a hash code for this set. - */ - - public int hashCode() { - int h = 0, n = size(); - ObjectIterator i = iterator(); - K k; - - while (n-- != 0) { - k = i.next(); // We need k because KEY2JAVAHASH() is a macro with - // repeated evaluation. - h += ((k) == null ? 0 : (k).hashCode()); - } - return h; - } -} diff --git a/src/main/java/it/unimi/dsi/fastutil/objects/Object2IntFunction.java b/src/main/java/it/unimi/dsi/fastutil/objects/Object2IntFunction.java deleted file mode 100644 index 9aae5f7..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/objects/Object2IntFunction.java +++ /dev/null @@ -1,143 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* Primitive-type-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.objects; - -import it.unimi.dsi.fastutil.Function; - -/** - * A type-specific {@link Function}; provides some additional methods that use - * polymorphism to avoid (un)boxing. - * - *

- * Type-specific versions of get(), put() and - * remove() cannot rely on null to denote absence of a - * key. Rather, they return a {@linkplain #defaultReturnValue() default return - * value}, which is set to 0 cast to the return type (false for - * booleans) at creation, but can be changed using the - * defaultReturnValue() method. - * - *

- * For uniformity reasons, even maps returning objects implement the default - * return value (of course, in this case the default return value is initialized - * to null). - * - *

- * Warning: to fall in line as much as possible with the - * {@linkplain java.util.Map standard map interface}, it is strongly suggested - * that standard versions of get(), put() and - * remove() for maps with primitive-type values return - * null to denote missing keys rather than wrap the default - * return value in an object (of course, for maps with object keys and values - * this is not possible, as there is no type-specific version). - * - * @see Function - */ - -public interface Object2IntFunction extends Function { - - /** - * Adds a pair to the map. - * - * @param key - * the key. - * @param value - * the value. - * @return the old value, or the {@linkplain #defaultReturnValue() default - * return value} if no value was present for the given key. - * @see Function#put(Object,Object) - */ - - int put(K key, int value); - - /** - * Returns the value to which the given key is mapped. - * - * @param key - * the key. - * @return the corresponding value, or the - * {@linkplain #defaultReturnValue() default return value} if no - * value was present for the given key. - * @see Function#get(Object) - */ - - int getInt(Object key); - - /** - * Removes the mapping with the given key. - * - * @param key - * the key. - * @return the old value, or the {@linkplain #defaultReturnValue() default - * return value} if no value was present for the given key. - * @see Function#remove(Object) - */ - - int removeInt(Object key); - /** - * Sets the default return value. - * - * This value must be returned by type-specific versions of - * get(), put() and remove() to - * denote that the map does not contain the specified key. It must be 0/ - * false/null by default. - * - * @param rv - * the new default return value. - * @see #defaultReturnValue() - */ - - void defaultReturnValue(int rv); - - /** - * Gets the default return value. - * - * @return the current default return value. - */ - - int defaultReturnValue(); - -} diff --git a/src/main/java/it/unimi/dsi/fastutil/objects/Object2IntMap.java b/src/main/java/it/unimi/dsi/fastutil/objects/Object2IntMap.java deleted file mode 100644 index 40af5e8..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/objects/Object2IntMap.java +++ /dev/null @@ -1,193 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* Primitive-type-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.objects; - -import it.unimi.dsi.fastutil.ints.IntCollection; -import it.unimi.dsi.fastutil.objects.Object2IntFunction; -import it.unimi.dsi.fastutil.objects.ObjectIterator; -import it.unimi.dsi.fastutil.objects.ObjectSet; - -import java.util.Map; - -/** - * A type-specific {@link Map}; provides some additional methods that use - * polymorphism to avoid (un)boxing, and handling of a default return value. - * - *

- * Besides extending the corresponding type-specific - * {@linkplain it.unimi.dsi.fastutil.Function function}, this interface - * strengthens {@link #entrySet()}, {@link #keySet()} and {@link #values()}. - * Maps returning entry sets of type {@link FastEntrySet} support also fast - * iteration. - * - *

- * A submap or subset may or may not have an independent default return value - * (which however must be initialized to the default return value of the - * originator). - * - * @see Map - */ - -public interface Object2IntMap - extends - Object2IntFunction, - Map { - - /** - * An entry set providing fast iteration. - * - *

- * In some cases (e.g., hash-based classes) iteration over an entry set - * requires the creation of a large number of {@link Map.Entry} - * objects. Some fastutil maps might return - * {@linkplain #entrySet() entry set} objects of type - * FastEntrySet: in this case, {@link #fastIterator() - * fastIterator()} will return an iterator that is guaranteed not to create a - * large number of objects, possibly - * by returning always the same entry (of course, mutated). - */ - - public interface FastEntrySet extends ObjectSet> { - /** - * Returns a fast iterator over this entry set; the iterator might - * return always the same entry object, suitably mutated. - * - * @return a fast iterator over this entry set; the iterator might - * return always the same {@link Map.Entry} object, - * suitably mutated. - */ - public ObjectIterator> fastIterator(); - } - - /** - * Returns a set view of the mappings contained in this map. - *

- * Note that this specification strengthens the one given in - * {@link Map#entrySet()}. - * - * @return a set view of the mappings contained in this map. - * @see Map#entrySet() - */ - - ObjectSet> entrySet(); - - /** - * Returns a type-specific set view of the mappings contained in this map. - * - *

- * This method is necessary because there is no inheritance along type - * parameters: it is thus impossible to strengthen {@link #entrySet()} so - * that it returns an {@link ObjectSet} of - * type-specific entries (the latter makes it possible to access keys and - * values with type-specific methods). - * - * @return a type-specific set view of the mappings contained in this map. - * @see #entrySet() - */ - - ObjectSet> object2IntEntrySet(); - - /** - * Returns a set view of the keys contained in this map. - *

- * Note that this specification strengthens the one given in - * {@link Map#keySet()}. - * - * @return a set view of the keys contained in this map. - * @see Map#keySet() - */ - - ObjectSet keySet(); - - /** - * Returns a set view of the values contained in this map. - *

- * Note that this specification strengthens the one given in - * {@link Map#values()}. - * - * @return a set view of the values contained in this map. - * @see Map#values() - */ - - IntCollection values(); - - /** - * @see Map#containsValue(Object) - */ - - boolean containsValue(int value); - - /** - * A type-specific {@link Map.Entry}; provides some additional - * methods that use polymorphism to avoid (un)boxing. - * - * @see Map.Entry - */ - - interface Entry extends Map.Entry { - /** - * {@inheritDoc} - * - * @deprecated Please use the corresponding type-specific method - * instead. - */ - @Deprecated - @Override - Integer getValue(); - - /** - * @see Map.Entry#setValue(Object) - */ - int setValue(int value); - - /** - * @see Map.Entry#getValue() - */ - int getIntValue(); - - } -} diff --git a/src/main/java/it/unimi/dsi/fastutil/objects/Object2IntOpenHashMap.java b/src/main/java/it/unimi/dsi/fastutil/objects/Object2IntOpenHashMap.java deleted file mode 100644 index 91fd646..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/objects/Object2IntOpenHashMap.java +++ /dev/null @@ -1,1348 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* Primitive-type-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.objects; - -import it.unimi.dsi.fastutil.Hash; -import it.unimi.dsi.fastutil.HashCommon; -import it.unimi.dsi.fastutil.ints.AbstractIntCollection; -import it.unimi.dsi.fastutil.ints.IntCollection; -import it.unimi.dsi.fastutil.ints.IntIterator; -import it.unimi.dsi.fastutil.objects.AbstractObject2IntMap; -import it.unimi.dsi.fastutil.objects.AbstractObjectSet; -import it.unimi.dsi.fastutil.objects.Object2IntMap; -import it.unimi.dsi.fastutil.objects.ObjectArrayList; -import it.unimi.dsi.fastutil.objects.ObjectIterator; -import it.unimi.dsi.fastutil.objects.ObjectSet; - -import java.util.Arrays; -import java.util.Map; -import java.util.NoSuchElementException; - -import static it.unimi.dsi.fastutil.HashCommon.arraySize; -import static it.unimi.dsi.fastutil.HashCommon.maxFill; - -/** - * A type-specific hash map with a fast, small-footprint implementation. - * - *

- * Instances of this class use a hash table to represent a map. The table is - * filled up to a specified load factor, and then doubled in size to - * accommodate new entries. If the table is emptied below one fourth of - * the load factor, it is halved in size. However, halving is not performed when - * deleting entries from an iterator, as it would interfere with the iteration - * process. - * - *

- * Note that {@link #clear()} does not modify the hash table size. Rather, a - * family of {@linkplain #trim() trimming methods} lets you control the size of - * the table; this is particularly useful if you reuse instances of this class. - * - * @see Hash - * @see HashCommon - */ - -public class Object2IntOpenHashMap extends AbstractObject2IntMap - implements - java.io.Serializable, - Cloneable, - Hash { - - private static final long serialVersionUID = 0L; - private static final boolean ASSERTS = false; - - /** The array of keys. */ - protected transient K[] key; - - /** The array of values. */ - protected transient int[] value; - - /** The mask for wrapping a position counter. */ - protected transient int mask; - - /** Whether this set contains the key zero. */ - protected transient boolean containsNullKey; - /** The current table size. */ - protected transient int n; - - /** - * Threshold after which we rehash. It must be the table size times - * {@link #f}. - */ - protected transient int maxFill; - - /** Number of entries in the set (including the key zero, if present). */ - protected int size; - - /** The acceptable load factor. */ - protected final float f; - /** Cached set of entries. */ - protected transient Object2IntMap.FastEntrySet entries; - - /** Cached set of keys. */ - protected transient ObjectSet keys; - - /** Cached collection of values. */ - protected transient IntCollection values; - /** - * Creates a new hash map. - * - *

- * The actual table size will be the least power of two greater than - * expected/f. - * - * @param expected - * the expected number of elements in the hash set. - * @param f - * the load factor. - */ - @SuppressWarnings("unchecked") - public Object2IntOpenHashMap(final int expected, final float f) { - - if (f <= 0 || f > 1) - throw new IllegalArgumentException( - "Load factor must be greater than 0 and smaller than or equal to 1"); - if (expected < 0) - throw new IllegalArgumentException( - "The expected number of elements must be nonnegative"); - - this.f = f; - - n = arraySize(expected, f); - mask = n - 1; - maxFill = maxFill(n, f); - key = (K[]) new Object[n + 1]; - value = new int[n + 1]; - - } - /** - * Creates a new hash map with {@link Hash#DEFAULT_LOAD_FACTOR} as load - * factor. - * - * @param expected - * the expected number of elements in the hash map. - */ - - public Object2IntOpenHashMap(final int expected) { - this(expected, DEFAULT_LOAD_FACTOR); - } - /** - * Creates a new hash map with initial expected - * {@link Hash#DEFAULT_INITIAL_SIZE} entries and - * {@link Hash#DEFAULT_LOAD_FACTOR} as load factor. - */ - - public Object2IntOpenHashMap() { - this(DEFAULT_INITIAL_SIZE, DEFAULT_LOAD_FACTOR); - } - /** - * Creates a new hash map copying a given one. - * - * @param m - * a {@link Map} to be copied into the new hash map. - * @param f - * the load factor. - */ - - public Object2IntOpenHashMap(final Map m, - final float f) { - this(m.size(), f); - putAll(m); - } - /** - * Creates a new hash map with {@link Hash#DEFAULT_LOAD_FACTOR} as load - * factor copying a given one. - * - * @param m - * a {@link Map} to be copied into the new hash map. - */ - - public Object2IntOpenHashMap(final Map m) { - this(m, DEFAULT_LOAD_FACTOR); - } - /** - * Creates a new hash map copying a given type-specific one. - * - * @param m - * a type-specific map to be copied into the new hash map. - * @param f - * the load factor. - */ - - public Object2IntOpenHashMap(final Object2IntMap m, final float f) { - this(m.size(), f); - putAll(m); - } - /** - * Creates a new hash map with {@link Hash#DEFAULT_LOAD_FACTOR} as load - * factor copying a given type-specific one. - * - * @param m - * a type-specific map to be copied into the new hash map. - */ - - public Object2IntOpenHashMap(final Object2IntMap m) { - this(m, DEFAULT_LOAD_FACTOR); - } - /** - * Creates a new hash map using the elements of two parallel arrays. - * - * @param k - * the array of keys of the new hash map. - * @param v - * the array of corresponding values in the new hash map. - * @param f - * the load factor. - * @throws IllegalArgumentException - * if k and v have different lengths. - */ - - public Object2IntOpenHashMap(final K[] k, final int[] v, final float f) { - this(k.length, f); - if (k.length != v.length) - throw new IllegalArgumentException( - "The key array and the value array have different lengths (" - + k.length + " and " + v.length + ")"); - for (int i = 0; i < k.length; i++) - this.put(k[i], v[i]); - } - /** - * Creates a new hash map with {@link Hash#DEFAULT_LOAD_FACTOR} as load - * factor using the elements of two parallel arrays. - * - * @param k - * the array of keys of the new hash map. - * @param v - * the array of corresponding values in the new hash map. - * @throws IllegalArgumentException - * if k and v have different lengths. - */ - - public Object2IntOpenHashMap(final K[] k, final int[] v) { - this(k, v, DEFAULT_LOAD_FACTOR); - } - private int realSize() { - return containsNullKey ? size - 1 : size; - } - - private void ensureCapacity(final int capacity) { - final int needed = arraySize(capacity, f); - if (needed > n) - rehash(needed); - } - - private void tryCapacity(final long capacity) { - final int needed = (int) Math.min( - 1 << 30, - Math.max(2, HashCommon.nextPowerOfTwo((long) Math.ceil(capacity - / f)))); - if (needed > n) - rehash(needed); - } - - private int removeEntry(final int pos) { - final int oldValue = value[pos]; - - size--; - - shiftKeys(pos); - if (size < maxFill / 4 && n > DEFAULT_INITIAL_SIZE) - rehash(n / 2); - return oldValue; - } - - private int removeNullEntry() { - containsNullKey = false; - - key[n] = null; - - final int oldValue = value[n]; - - size--; - - if (size < maxFill / 4 && n > DEFAULT_INITIAL_SIZE) - rehash(n / 2); - return oldValue; - } - - /** {@inheritDoc} */ - public void putAll(Map m) { - if (f <= .5) - ensureCapacity(m.size()); // The resulting map will be sized for - // m.size() elements - else - tryCapacity(size() + m.size()); // The resulting map will be - // tentatively sized for size() + - // m.size() elements - super.putAll(m); - } - - private int insert(final K k, final int v) { - int pos; - - if (((k) == null)) { - if (containsNullKey) - return n; - containsNullKey = true; - pos = n; - } else { - K curr; - final K[] key = this.key; - - // The starting point. - if (!((curr = key[pos = ( - HashCommon.mix((k) - .hashCode())) & mask]) == null)) { - if (((curr).equals(k))) - return pos; - while (!((curr = key[pos = (pos + 1) & mask]) == null)) - if (((curr).equals(k))) - return pos; - } - } - - key[pos] = k; - value[pos] = v; - if (size++ >= maxFill) - rehash(arraySize(size + 1, f)); - if (ASSERTS) - checkTable(); - return -1; - } - - public int put(final K k, final int v) { - final int pos = insert(k, v); - if (pos < 0) - return defRetValue; - final int oldValue = value[pos]; - value[pos] = v; - return oldValue; - } - - /** - * {@inheritDoc} - * - * @deprecated Please use the corresponding type-specific method instead. - */ - @Deprecated - @Override - public Integer put(final K ok, final Integer ov) { - final int v = ((ov).intValue()); - - final int pos = insert((ok), v); - if (pos < 0) - return (null); - final int oldValue = value[pos]; - value[pos] = v; - return (Integer.valueOf(oldValue)); - } - - private int addToValue(final int pos, final int incr) { - final int oldValue = value[pos]; - - value[pos] = oldValue + incr; - - return oldValue; - } - - /** - * Adds an increment to value currently associated with a key. - * - *

- * Note that this method respects the {@linkplain #defaultReturnValue() - * default return value} semantics: when called with a key that does not - * currently appears in the map, the key will be associated with the default - * return value plus the given increment. - * - * @param k - * the key. - * @param incr - * the increment. - * @return the old value, or the {@linkplain #defaultReturnValue() default - * return value} if no value was present for the given key. - */ - public int addTo(final K k, final int incr) { - int pos; - - if (((k) == null)) { - if (containsNullKey) - return addToValue(n, incr); - pos = n; - containsNullKey = true; - } else { - K curr; - final K[] key = this.key; - - // The starting point. - if (!((curr = key[pos = ( - HashCommon.mix((k) - .hashCode())) & mask]) == null)) { - if (((curr).equals(k))) - return addToValue(pos, incr); - while (!((curr = key[pos = (pos + 1) & mask]) == null)) - if (((curr).equals(k))) - return addToValue(pos, incr); - } - } - - key[pos] = k; - - value[pos] = defRetValue + incr; - if (size++ >= maxFill) - rehash(arraySize(size + 1, f)); - if (ASSERTS) - checkTable(); - return defRetValue; - } - - /** - * Shifts left entries with the specified hash code, starting at the - * specified position, and empties the resulting free entry. - * - * @param pos - * a starting position. - */ - protected final void shiftKeys(int pos) { - // Shift entries with the same hash. - int last, slot; - K curr; - final K[] key = this.key; - - for (;;) { - pos = ((last = pos) + 1) & mask; - - for (;;) { - if (((curr = key[pos]) == null)) { - key[last] = (null); - - return; - } - slot = (HashCommon.mix((curr).hashCode())) - & mask; - if (last <= pos ? last >= slot || slot > pos : last >= slot - && slot > pos) - break; - pos = (pos + 1) & mask; - } - - key[last] = curr; - value[last] = value[pos]; - - } - } - - @SuppressWarnings("unchecked") - public int removeInt(final Object k) { - if ((((K) k) == null)) { - if (containsNullKey) - return removeNullEntry(); - return defRetValue; - } - - K curr; - final K[] key = this.key; - int pos; - - // The starting point. - if (((curr = key[pos = ( - HashCommon.mix((k) - .hashCode())) & mask]) == null)) - return defRetValue; - if (((k).equals(curr))) - return removeEntry(pos); - while (true) { - if (((curr = key[pos = (pos + 1) & mask]) == null)) - return defRetValue; - if (((k).equals(curr))) - return removeEntry(pos); - } - } - - /** - * {@inheritDoc} - * - * @deprecated Please use the corresponding type-specific method instead. - */ - @Deprecated - @Override - @SuppressWarnings("unchecked") - public Integer remove(final Object ok) { - final K k = (K) (ok); - if (((k) == null)) { - if (containsNullKey) - return (Integer.valueOf(removeNullEntry())); - return (null); - } - - K curr; - final K[] key = this.key; - int pos; - - // The starting point. - if (((curr = key[pos = ( - HashCommon.mix((k) - .hashCode())) & mask]) == null)) - return (null); - if (((curr).equals(k))) - return (Integer.valueOf(removeEntry(pos))); - while (true) { - if (((curr = key[pos = (pos + 1) & mask]) == null)) - return (null); - if (((curr).equals(k))) - return (Integer.valueOf(removeEntry(pos))); - } - } - @SuppressWarnings("unchecked") - public int getInt(final Object k) { - if ((((K) k) == null)) - return containsNullKey ? value[n] : defRetValue; - - K curr; - final K[] key = this.key; - int pos; - - // The starting point. - if (((curr = key[pos = ( - HashCommon.mix((k) - .hashCode())) & mask]) == null)) - return defRetValue; - if (((k).equals(curr))) - return value[pos]; - // There's always an unused entry. - while (true) { - if (((curr = key[pos = (pos + 1) & mask]) == null)) - return defRetValue; - if (((k).equals(curr))) - return value[pos]; - } - } - - @SuppressWarnings("unchecked") - public boolean containsKey(final Object k) { - if ((((K) k) == null)) - return containsNullKey; - - K curr; - final K[] key = this.key; - int pos; - - // The starting point. - if (((curr = key[pos = ( - HashCommon.mix((k) - .hashCode())) & mask]) == null)) - return false; - if (((k).equals(curr))) - return true; - // There's always an unused entry. - while (true) { - if (((curr = key[pos = (pos + 1) & mask]) == null)) - return false; - if (((k).equals(curr))) - return true; - } - } - - public boolean containsValue(final int v) { - final int value[] = this.value; - final K key[] = this.key; - if (containsNullKey && ((value[n]) == (v))) - return true; - for (int i = n; i-- != 0;) - if (!((key[i]) == null) && ((value[i]) == (v))) - return true; - return false; - } - - /* - * Removes all elements from this map. - * - *

To increase object reuse, this method does not change the table size. - * If you want to reduce the table size, you must use {@link #trim()}. - */ - public void clear() { - if (size == 0) - return; - size = 0; - containsNullKey = false; - - Arrays.fill(key, (null)); - - } - - public int size() { - return size; - } - - public boolean isEmpty() { - return size == 0; - } - - /** - * A no-op for backward compatibility. - * - * @param growthFactor - * unused. - * @deprecated Since fastutil 6.1.0, hash tables are doubled - * when they are too full. - */ - @Deprecated - public void growthFactor(int growthFactor) { - } - - /** - * Gets the growth factor (2). - * - * @return the growth factor of this set, which is fixed (2). - * @see #growthFactor(int) - * @deprecated Since fastutil 6.1.0, hash tables are doubled - * when they are too full. - */ - @Deprecated - public int growthFactor() { - return 16; - } - - /** - * The entry class for a hash map does not record key and value, but rather - * the position in the hash table of the corresponding entry. This is - * necessary so that calls to {@link Map.Entry#setValue(Object)} - * are reflected in the map - */ - - final class MapEntry - implements - Object2IntMap.Entry, - Map.Entry { - // The table index this entry refers to, or -1 if this entry has been - // deleted. - int index; - - MapEntry(final int index) { - this.index = index; - } - - MapEntry() { - } - - public K getKey() { - return (key[index]); - } - /** - * {@inheritDoc} - * - * @deprecated Please use the corresponding type-specific method - * instead. - */ - @Deprecated - public Integer getValue() { - return (Integer.valueOf(value[index])); - } - - public int getIntValue() { - return value[index]; - } - - public int setValue(final int v) { - final int oldValue = value[index]; - value[index] = v; - return oldValue; - } - - public Integer setValue(final Integer v) { - return (Integer.valueOf(setValue(((v).intValue())))); - } - - @SuppressWarnings("unchecked") - public boolean equals(final Object o) { - if (!(o instanceof Map.Entry)) - return false; - Map.Entry e = (Map.Entry) o; - - return ((key[index]) == null - ? ((e.getKey())) == null - : (key[index]).equals((e.getKey()))) - && ((value[index]) == (((e.getValue()).intValue()))); - } - - public int hashCode() { - return ((key[index]) == null ? 0 : (key[index]).hashCode()) - ^ (value[index]); - } - - public String toString() { - return key[index] + "=>" + value[index]; - } - } - /** An iterator over a hash map. */ - - private class MapIterator { - /** - * The index of the last entry returned, if positive or zero; initially, - * {@link #n}. If negative, the last entry returned was that of the key - * of index {@code - pos - 1} from the {@link #wrapped} list. - */ - int pos = n; - /** - * The index of the last entry that has been returned (more precisely, - * the value of {@link #pos} if {@link #pos} is positive, or - * {@link Integer#MIN_VALUE} if {@link #pos} is negative). It is -1 if - * either we did not return an entry yet, or the last returned entry has - * been removed. - */ - int last = -1; - /** - * A downward counter measuring how many entries must still be returned. - */ - int c = size; - /** - * A boolean telling us whether we should return the entry with the null - * key. - */ - boolean mustReturnNullKey = it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap.this.containsNullKey; - /** - * A lazily allocated list containing keys of entries that have wrapped - * around the table because of removals. - */ - ObjectArrayList wrapped; - - public boolean hasNext() { - return c != 0; - } - - public int nextEntry() { - if (!hasNext()) - throw new NoSuchElementException(); - - c--; - if (mustReturnNullKey) { - mustReturnNullKey = false; - return last = n; - } - - final K key[] = it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap.this.key; - - for (;;) { - if (--pos < 0) { - // We are just enumerating elements from the wrapped list. - last = Integer.MIN_VALUE; - final K k = wrapped.get(-pos - 1); - int p = ( - HashCommon.mix((k) - .hashCode())) & mask; - while (!((k).equals(key[p]))) - p = (p + 1) & mask; - return p; - } - if (!((key[pos]) == null)) - return last = pos; - } - } - - /** - * Shifts left entries with the specified hash code, starting at the - * specified position, and empties the resulting free entry. - * - * @param pos - * a starting position. - */ - private final void shiftKeys(int pos) { - // Shift entries with the same hash. - int last, slot; - K curr; - final K[] key = it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap.this.key; - - for (;;) { - pos = ((last = pos) + 1) & mask; - - for (;;) { - if (((curr = key[pos]) == null)) { - key[last] = (null); - - return; - } - slot = ( - HashCommon.mix((curr) - .hashCode())) & mask; - if (last <= pos ? last >= slot || slot > pos : last >= slot - && slot > pos) - break; - pos = (pos + 1) & mask; - } - - if (pos < last) { // Wrapped entry. - if (wrapped == null) - wrapped = new ObjectArrayList(2); - wrapped.add(key[pos]); - } - - key[last] = curr; - value[last] = value[pos]; - } - } - - public void remove() { - if (last == -1) - throw new IllegalStateException(); - if (last == n) { - containsNullKey = false; - - key[n] = null; - - } else if (pos >= 0) - shiftKeys(last); - else { - // We're removing wrapped entries. - - it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap.this.remove(wrapped.set(-pos - 1, null)); - - last = -1; // Note that we must not decrement size - return; - } - - size--; - last = -1; // You can no longer remove this entry. - if (ASSERTS) - checkTable(); - } - - public int skip(final int n) { - int i = n; - while (i-- != 0 && hasNext()) - nextEntry(); - return n - i - 1; - } - } - - private class EntryIterator extends MapIterator - implements - ObjectIterator> { - private MapEntry entry; - - public Object2IntMap.Entry next() { - return entry = new MapEntry(nextEntry()); - } - - @Override - public void remove() { - super.remove(); - entry.index = -1; // You cannot use a deleted entry. - } - } - - private class FastEntryIterator extends MapIterator - implements - ObjectIterator> { - private final MapEntry entry = new MapEntry(); - public MapEntry next() { - entry.index = nextEntry(); - return entry; - } - } - private final class MapEntrySet - extends - AbstractObjectSet> - implements Object2IntMap.FastEntrySet { - - public ObjectIterator> iterator() { - return new EntryIterator(); - } - - public ObjectIterator> fastIterator() { - return new FastEntryIterator(); - } - - @SuppressWarnings("unchecked") - public boolean contains(final Object o) { - if (!(o instanceof Map.Entry)) - return false; - final Map.Entry e = (Map.Entry) o; - - if (e.getValue() == null || !(e.getValue() instanceof Integer)) - return false; - - final K k = ((K) e.getKey()); - final int v = ((((Integer) (e.getValue())).intValue())); - - if (((k) == null)) - return it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap.this.containsNullKey - && ((value[n]) == (v)); - - K curr; - final K[] key = it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap.this.key; - int pos; - - // The starting point. - if (((curr = key[pos = ( - HashCommon.mix((k) - .hashCode())) & mask]) == null)) - return false; - if (((k).equals(curr))) - return ((value[pos]) == (v)); - // There's always an unused entry. - while (true) { - if (((curr = key[pos = (pos + 1) & mask]) == null)) - return false; - if (((k).equals(curr))) - return ((value[pos]) == (v)); - } - } - - @SuppressWarnings("unchecked") - public boolean remove(final Object o) { - if (!(o instanceof Map.Entry)) - return false; - final Map.Entry e = (Map.Entry) o; - - if (e.getValue() == null || !(e.getValue() instanceof Integer)) - return false; - - final K k = ((K) e.getKey()); - final int v = ((((Integer) (e.getValue())).intValue())); - - if (((k) == null)) { - if (containsNullKey && ((value[n]) == (v))) { - removeNullEntry(); - return true; - } - return false; - } - - K curr; - final K[] key = it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap.this.key; - int pos; - - // The starting point. - if (((curr = key[pos = ( - HashCommon.mix((k) - .hashCode())) & mask]) == null)) - return false; - if (((curr).equals(k))) { - if (((value[pos]) == (v))) { - removeEntry(pos); - return true; - } - return false; - } - - while (true) { - if (((curr = key[pos = (pos + 1) & mask]) == null)) - return false; - if (((curr).equals(k))) { - if (((value[pos]) == (v))) { - removeEntry(pos); - return true; - } - } - } - } - - public int size() { - return size; - } - - public void clear() { - it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap.this.clear(); - } - } - - public Object2IntMap.FastEntrySet object2IntEntrySet() { - if (entries == null) - entries = new MapEntrySet(); - - return entries; - } - - /** - * An iterator on keys. - * - *

- * We simply override the {@link java.util.ListIterator#next()}/ - * {@link java.util.ListIterator#previous()} methods (and possibly their - * type-specific counterparts) so that they return keys instead of entries. - */ - private final class KeyIterator extends MapIterator - implements - ObjectIterator { - - public KeyIterator() { - super(); - } - public K next() { - return key[nextEntry()]; - } - - } - private final class KeySet extends AbstractObjectSet { - - public ObjectIterator iterator() { - return new KeyIterator(); - } - - public int size() { - return size; - } - - public boolean contains(Object k) { - return containsKey(k); - } - - public boolean remove(Object k) { - final int oldSize = size; - it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap.this.remove(k); - return size != oldSize; - } - - public void clear() { - it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap.this.clear(); - } - } - - public ObjectSet keySet() { - - if (keys == null) - keys = new KeySet(); - return keys; - } - - /** - * An iterator on values. - * - *

- * We simply override the {@link java.util.ListIterator#next()}/ - * {@link java.util.ListIterator#previous()} methods (and possibly their - * type-specific counterparts) so that they return values instead of - * entries. - */ - private final class ValueIterator extends MapIterator - implements - IntIterator { - - public ValueIterator() { - super(); - } - public int nextInt() { - return value[nextEntry()]; - } - - /** - * {@inheritDoc} - * - * @deprecated Please use the corresponding type-specific method - * instead. - */ - @Deprecated - @Override - public Integer next() { - return (Integer.valueOf(value[nextEntry()])); - } - - } - - public IntCollection values() { - if (values == null) - values = new AbstractIntCollection() { - - public IntIterator iterator() { - return new ValueIterator(); - } - - public int size() { - return size; - } - - public boolean contains(int v) { - return containsValue(v); - } - - public void clear() { - it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap.this.clear(); - } - }; - - return values; - } - - /** - * A no-op for backward compatibility. The kind of tables implemented by - * this class never need rehashing. - * - *

- * If you need to reduce the table size to fit exactly this set, use - * {@link #trim()}. - * - * @return true. - * @see #trim() - * @deprecated A no-op. - */ - - @Deprecated - public boolean rehash() { - return true; - } - - /** - * Rehashes the map, making the table as small as possible. - * - *

- * This method rehashes the table to the smallest size satisfying the load - * factor. It can be used when the set will not be changed anymore, so to - * optimize access speed and size. - * - *

- * If the table size is already the minimum possible, this method does - * nothing. - * - * @return true if there was enough memory to trim the map. - * @see #trim(int) - */ - - public boolean trim() { - final int l = arraySize(size, f); - if (l >= n || size > maxFill(l, f)) - return true; - try { - rehash(l); - } catch (OutOfMemoryError cantDoIt) { - return false; - } - return true; - } - - /** - * Rehashes this map if the table is too large. - * - *

- * Let N be the smallest table size that can hold - * max(n,{@link #size()}) entries, still satisfying the load - * factor. If the current table size is smaller than or equal to - * N, this method does nothing. Otherwise, it rehashes this map - * in a table of size N. - * - *

- * This method is useful when reusing maps. {@linkplain #clear() Clearing a - * map} leaves the table size untouched. If you are reusing a map many times, - * you can call this method with a typical size to avoid keeping around a - * very large table just because of a few large transient maps. - * - * @param n - * the threshold for the trimming. - * @return true if there was enough memory to trim the map. - * @see #trim() - */ - - public boolean trim(final int n) { - final int l = HashCommon.nextPowerOfTwo((int) Math.ceil(n / f)); - if (l >= n || size > maxFill(l, f)) - return true; - try { - rehash(l); - } catch (OutOfMemoryError cantDoIt) { - return false; - } - return true; - } - - /** - * Rehashes the map. - * - *

- * This method implements the basic rehashing strategy, and may be overriden - * by subclasses implementing different rehashing strategies (e.g., - * disk-based rehashing). However, you should not override this method - * unless you understand the internal workings of this class. - * - * @param newN - * the new size - */ - - @SuppressWarnings("unchecked") - protected void rehash(final int newN) { - final K key[] = this.key; - final int value[] = this.value; - - final int mask = newN - 1; // Note that this is used by the hashing - // macro - final K newKey[] = (K[]) new Object[newN + 1]; - final int newValue[] = new int[newN + 1]; - int i = n, pos; - - for (int j = realSize(); j-- != 0;) { - while (((key[--i]) == null)); - - if (!((newKey[pos = ( - HashCommon.mix((key[i]) - .hashCode())) & mask]) == null)) - while (!((newKey[pos = (pos + 1) & mask]) == null)); - - newKey[pos] = key[i]; - newValue[pos] = value[i]; - } - - newValue[newN] = value[n]; - - n = newN; - this.mask = mask; - maxFill = maxFill(n, f); - this.key = newKey; - this.value = newValue; - } - - /** - * Returns a deep copy of this map. - * - *

- * This method performs a deep copy of this hash map; the data stored in the - * map, however, is not cloned. Note that this makes a difference only for - * object keys. - * - * @return a deep copy of this map. - */ - - @SuppressWarnings("unchecked") - public it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap clone() { - it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap c; - try { - c = (it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap) super.clone(); - } catch (CloneNotSupportedException cantHappen) { - throw new InternalError(); - } - - c.keys = null; - c.values = null; - c.entries = null; - c.containsNullKey = containsNullKey; - - c.key = key.clone(); - c.value = value.clone(); - - return c; - } - - /** - * Returns a hash code for this map. - * - * This method overrides the generic method provided by the superclass. - * Since equals() is not overriden, it is important that the - * value returned by this method is the same value as the one returned by - * the overriden method. - * - * @return a hash code for this map. - */ - - public int hashCode() { - int h = 0; - for (int j = realSize(), i = 0, t = 0; j-- != 0;) { - while (((key[i]) == null)) - i++; - - if (this != key[i]) - - t = ((key[i]).hashCode()); - - t ^= (value[i]); - h += t; - i++; - } - // Zero / null keys have hash zero. - if (containsNullKey) - h += (value[n]); - return h; - } - - private void writeObject(java.io.ObjectOutputStream s) - throws java.io.IOException { - final K key[] = this.key; - final int value[] = this.value; - final MapIterator i = new MapIterator(); - - s.defaultWriteObject(); - - for (int j = size, e; j-- != 0;) { - e = i.nextEntry(); - s.writeObject(key[e]); - s.writeInt(value[e]); - } - } - - @SuppressWarnings("unchecked") - private void readObject(java.io.ObjectInputStream s) - throws java.io.IOException, ClassNotFoundException { - s.defaultReadObject(); - - n = arraySize(size, f); - maxFill = maxFill(n, f); - mask = n - 1; - - final K key[] = this.key = (K[]) new Object[n + 1]; - final int value[] = this.value = new int[n + 1]; - - K k; - int v; - - for (int i = size, pos; i-- != 0;) { - - k = (K) s.readObject(); - v = s.readInt(); - - if (((k) == null)) { - pos = n; - containsNullKey = true; - } else { - pos = (HashCommon.mix((k).hashCode())) - & mask; - while (!((key[pos]) == null)) - pos = (pos + 1) & mask; - } - - key[pos] = k; - value[pos] = v; - } - if (ASSERTS) - checkTable(); - } - private void checkTable() { - } -} diff --git a/src/main/java/it/unimi/dsi/fastutil/objects/ObjectArrayList.java b/src/main/java/it/unimi/dsi/fastutil/objects/ObjectArrayList.java deleted file mode 100644 index 36313c3..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/objects/ObjectArrayList.java +++ /dev/null @@ -1,737 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.objects; - -import it.unimi.dsi.fastutil.objects.AbstractObjectList; -import it.unimi.dsi.fastutil.objects.AbstractObjectListIterator; -import it.unimi.dsi.fastutil.objects.ObjectArrays; -import it.unimi.dsi.fastutil.objects.ObjectCollection; -import it.unimi.dsi.fastutil.objects.ObjectIterator; -import it.unimi.dsi.fastutil.objects.ObjectIterators; -import it.unimi.dsi.fastutil.objects.ObjectList; -import it.unimi.dsi.fastutil.objects.ObjectListIterator; - -import java.util.Arrays; -import java.util.Collection; -import java.util.Iterator; -import java.util.NoSuchElementException; -import java.util.RandomAccess; - -/** - * A type-specific array-based list; provides some additional methods that use - * polymorphism to avoid (un)boxing. - * - *

- * This class implements a lightweight, fast, open, optimized, reuse-oriented - * version of array-based lists. Instances of this class represent a list with - * an array that is enlarged as needed when new entries are created (by doubling - * the current length), but is never made smaller (even on a - * {@link #clear()}). A family of {@linkplain #trim() trimming methods} lets you - * control the size of the backing array; this is particularly useful if you - * reuse instances of this class. Range checks are equivalent to those of - * {@link java.util}'s classes, but they are delayed as much as possible. - * - *

- * The backing array is exposed by the {@link #elements()} method. If an - * instance of this class was created {@linkplain #wrap(Object[],int) by - * wrapping}, backing-array reallocations will be performed using reflection, so - * that {@link #elements()} can return an array of the same type of the original - * array: the comments about efficiency made in - * {@link ObjectArrays} apply here. Moreover, you - * must take into consideration that assignment to an array not of type - * {@code Object[]} is slower due to type checking. - * - *

- * This class implements the bulk methods removeElements(), - * addElements() and getElements() using - * high-performance system calls (e.g., - * {@link System#arraycopy(Object,int,Object,int,int) System.arraycopy()} instead - * of expensive loops. - * - * @see java.util.ArrayList - */ - -public class ObjectArrayList extends AbstractObjectList - implements - RandomAccess, - Cloneable, - java.io.Serializable { - private static final long serialVersionUID = -7046029254386353131L; - - /** The initial default capacity of an array list. */ - public final static int DEFAULT_INITIAL_CAPACITY = 16; - - /** - * Whether the backing array was passed to wrap(). In this - * case, we must reallocate with the same type of array. - */ - protected final boolean wrapped; - - /** The backing array. */ - protected transient K a[]; - - /** - * The current actual size of the list (never greater than the backing-array - * length). - */ - protected int size; - - private static final boolean ASSERTS = false; - - /** - * Creates a new array list using a given array. - * - *

- * This constructor is only meant to be used by the wrapping methods. - * - * @param a - * the array that will be used to back this array list. - */ - - @SuppressWarnings("unused") - protected ObjectArrayList(final K a[], boolean dummy) { - this.a = a; - - this.wrapped = true; - - } - - /** - * Creates a new array list with given capacity. - * - * @param capacity - * the initial capacity of the array list (may be 0). - */ - - @SuppressWarnings("unchecked") - public ObjectArrayList(final int capacity) { - if (capacity < 0) - throw new IllegalArgumentException("Initial capacity (" + capacity - + ") is negative"); - - a = (K[]) new Object[capacity]; - - wrapped = false; - - } - - /** - * Creates a new array list with {@link #DEFAULT_INITIAL_CAPACITY} capacity. - */ - - public ObjectArrayList() { - this(DEFAULT_INITIAL_CAPACITY); - } - - /** - * Creates a new array list and fills it with a given collection. - * - * @param c - * a collection that will be used to fill the array list. - */ - - public ObjectArrayList(final Collection c) { - this(c.size()); - - size = ObjectIterators.unwrap(c.iterator(), a); - - } - - /** - * Creates a new array list and fills it with a given type-specific - * collection. - * - * @param c - * a type-specific collection that will be used to fill the array - * list. - */ - - public ObjectArrayList(final ObjectCollection c) { - this(c.size()); - size = ObjectIterators.unwrap(c.iterator(), a); - } - - /** - * Creates a new array list and fills it with a given type-specific list. - * - * @param l - * a type-specific list that will be used to fill the array list. - */ - - public ObjectArrayList(final ObjectList l) { - this(l.size()); - l.getElements(0, a, 0, size = l.size()); - } - - /** - * Creates a new array list and fills it with the elements of a given array. - * - * @param a - * an array whose elements will be used to fill the array list. - */ - - public ObjectArrayList(final K a[]) { - this(a, 0, a.length); - } - - /** - * Creates a new array list and fills it with the elements of a given array. - * - * @param a - * an array whose elements will be used to fill the array list. - * @param offset - * the first element to use. - * @param length - * the number of elements to use. - */ - - public ObjectArrayList(final K a[], final int offset, final int length) { - this(length); - System.arraycopy(a, offset, this.a, 0, length); - size = length; - } - - /** - * Creates a new array list and fills it with the elements returned by an - * iterator.. - * - * @param i - * an iterator whose returned elements will fill the array list. - */ - - public ObjectArrayList(final Iterator i) { - this(); - while (i.hasNext()) - this.add(i.next()); - } - - /** - * Creates a new array list and fills it with the elements returned by a - * type-specific iterator.. - * - * @param i - * a type-specific iterator whose returned elements will fill the - * array list. - */ - - public ObjectArrayList(final ObjectIterator i) { - this(); - while (i.hasNext()) - this.add(i.next()); - } - /** - * Returns the backing array of this list. - * - *

- * If this array list was created by wrapping a given array, it is - * guaranteed that the type of the returned array will be the same. - * Otherwise, the returned array will be of type {@link Object Object[]} (in - * spite of the declared return type). - * - *

- * Warning: This behaviour may cause (unfathomable) - * run-time errors if a method expects an array actually of type - * K[], but this methods returns an array of type - * {@link Object Object[]}. - * - * @return the backing array. - */ - - public K[] elements() { - return a; - } - - /** - * Wraps a given array into an array list of given size. - * - *

- * Note it is guaranteed that the type of the array returned by - * {@link #elements()} will be the same (see the comments in the class - * documentation). - * - * @param a - * an array to wrap. - * @param length - * the length of the resulting array list. - * @return a new array list of the given size, wrapping the given array. - */ - - public static it.unimi.dsi.fastutil.objects.ObjectArrayList wrap(final K a[], final int length) { - if (length > a.length) - throw new IllegalArgumentException("The specified length (" - + length + ") is greater than the array size (" + a.length - + ")"); - final it.unimi.dsi.fastutil.objects.ObjectArrayList l = new it.unimi.dsi.fastutil.objects.ObjectArrayList(a, false); - l.size = length; - return l; - } - - /** - * Wraps a given array into an array list. - * - *

- * Note it is guaranteed that the type of the array returned by - * {@link #elements()} will be the same (see the comments in the class - * documentation). - * - * @param a - * an array to wrap. - * @return a new array list wrapping the given array. - */ - - public static it.unimi.dsi.fastutil.objects.ObjectArrayList wrap(final K a[]) { - return wrap(a, a.length); - } - - /** - * Ensures that this array list can contain the given number of entries - * without resizing. - * - * @param capacity - * the new minimum capacity for this array list. - */ - @SuppressWarnings("unchecked") - public void ensureCapacity(final int capacity) { - - if (wrapped) - a = ObjectArrays.ensureCapacity(a, capacity, size); - else { - if (capacity > a.length) { - final Object t[] = new Object[capacity]; - System.arraycopy(a, 0, t, 0, size); - a = (K[]) t; - } - } - - if (ASSERTS) - assert size <= a.length; - } - - /** - * Grows this array list, ensuring that it can contain the given number of - * entries without resizing, and in case enlarging it at least by a factor - * of two. - * - * @param capacity - * the new minimum capacity for this array list. - */ - @SuppressWarnings("unchecked") - private void grow(final int capacity) { - - if (wrapped) - a = ObjectArrays.grow(a, capacity, size); - else { - if (capacity > a.length) { - final int newLength = (int) Math.max(Math.min(2L * a.length, - it.unimi.dsi.fastutil.Arrays.MAX_ARRAY_SIZE), capacity); - final Object t[] = new Object[newLength]; - System.arraycopy(a, 0, t, 0, size); - a = (K[]) t; - } - } - - if (ASSERTS) - assert size <= a.length; - } - - public void add(final int index, final K k) { - ensureIndex(index); - grow(size + 1); - if (index != size) - System.arraycopy(a, index, a, index + 1, size - index); - a[index] = k; - size++; - if (ASSERTS) - assert size <= a.length; - } - - public boolean add(final K k) { - grow(size + 1); - a[size++] = k; - if (ASSERTS) - assert size <= a.length; - return true; - } - - public K get(final int index) { - if (index >= size) - throw new IndexOutOfBoundsException("Index (" + index - + ") is greater than or equal to list size (" + size + ")"); - return a[index]; - } - - public int indexOf(final Object k) { - for (int i = 0; i < size; i++) - if (((k) == null ? (a[i]) == null : (k).equals(a[i]))) - return i; - return -1; - } - - public int lastIndexOf(final Object k) { - for (int i = size; i-- != 0;) - if (((k) == null ? (a[i]) == null : (k).equals(a[i]))) - return i; - return -1; - } - - public K remove(final int index) { - if (index >= size) - throw new IndexOutOfBoundsException("Index (" + index - + ") is greater than or equal to list size (" + size + ")"); - final K old = a[index]; - size--; - if (index != size) - System.arraycopy(a, index + 1, a, index, size - index); - - a[size] = null; - - if (ASSERTS) - assert size <= a.length; - return old; - } - - public boolean rem(final Object k) { - int index = indexOf(k); - if (index == -1) - return false; - remove(index); - if (ASSERTS) - assert size <= a.length; - return true; - } - - public boolean remove(final Object o) { - return rem(o); - } - - public K set(final int index, final K k) { - if (index >= size) - throw new IndexOutOfBoundsException("Index (" + index - + ") is greater than or equal to list size (" + size + ")"); - K old = a[index]; - a[index] = k; - return old; - } - - public void clear() { - - Arrays.fill(a, 0, size, null); - - size = 0; - if (ASSERTS) - assert size <= a.length; - } - - public int size() { - return size; - } - - public void size(final int size) { - if (size > a.length) - ensureCapacity(size); - if (size > this.size) - Arrays.fill(a, this.size, size, (null)); - - else - Arrays.fill(a, size, this.size, (null)); - - this.size = size; - } - - public boolean isEmpty() { - return size == 0; - } - - /** - * Trims this array list so that the capacity is equal to the size. - * - * @see java.util.ArrayList#trimToSize() - */ - public void trim() { - trim(0); - } - - /** - * Trims the backing array if it is too large. - * - * If the current array length is smaller than or equal to n, - * this method does nothing. Otherwise, it trims the array length to the - * maximum between n and {@link #size()}. - * - *

- * This method is useful when reusing lists. {@linkplain #clear() Clearing a - * list} leaves the array length untouched. If you are reusing a list many - * times, you can call this method with a typical size to avoid keeping - * around a very large array just because of a few large transient lists. - * - * @param n - * the threshold for the trimming. - */ - - @SuppressWarnings("unchecked") - public void trim(final int n) { - // TODO: use Arrays.trim() and preserve type only if necessary - if (n >= a.length || size == a.length) - return; - final K t[] = (K[]) new Object[Math.max(n, size)]; - System.arraycopy(a, 0, t, 0, size); - a = t; - if (ASSERTS) - assert size <= a.length; - } - - /** - * Copies element of this type-specific list into the given array using - * optimized system calls. - * - * @param from - * the start index (inclusive). - * @param a - * the destination array. - * @param offset - * the offset into the destination array where to store the first - * element copied. - * @param length - * the number of elements to be copied. - */ - - public void getElements(final int from, final Object[] a, final int offset, - final int length) { - ObjectArrays.ensureOffsetLength(a, offset, length); - System.arraycopy(this.a, from, a, offset, length); - } - - /** - * Removes elements of this type-specific list using optimized system calls. - * - * @param from - * the start index (inclusive). - * @param to - * the end index (exclusive). - */ - public void removeElements(final int from, final int to) { - it.unimi.dsi.fastutil.Arrays.ensureFromTo(size, from, to); - System.arraycopy(a, to, a, from, size - to); - size -= (to - from); - - int i = to - from; - while (i-- != 0) - a[size + i] = null; - - } - - /** - * Adds elements to this type-specific list using optimized system calls. - * - * @param index - * the index at which to add elements. - * @param a - * the array containing the elements. - * @param offset - * the offset of the first element to add. - * @param length - * the number of elements to add. - */ - public void addElements(final int index, final K a[], final int offset, - final int length) { - ensureIndex(index); - ObjectArrays.ensureOffsetLength(a, offset, length); - grow(size + length); - System.arraycopy(this.a, index, this.a, index + length, size - index); - System.arraycopy(a, offset, this.a, index, length); - size += length; - } - @Override - public boolean removeAll(final Collection c) { - final Object[] a = this.a; - int j = 0; - for (int i = 0; i < size; i++) - if (!c.contains(a[i])) - a[j++] = a[i]; - Arrays.fill(a, j, size, null); - final boolean modified = size != j; - size = j; - return modified; - } - - public ObjectListIterator listIterator(final int index) { - ensureIndex(index); - - return new AbstractObjectListIterator() { - int pos = index, last = -1; - - public boolean hasNext() { - return pos < size; - } - public boolean hasPrevious() { - return pos > 0; - } - public K next() { - if (!hasNext()) - throw new NoSuchElementException(); - return a[last = pos++]; - } - public K previous() { - if (!hasPrevious()) - throw new NoSuchElementException(); - return a[last = --pos]; - } - public int nextIndex() { - return pos; - } - public int previousIndex() { - return pos - 1; - } - public void add(K k) { - it.unimi.dsi.fastutil.objects.ObjectArrayList.this.add(pos++, k); - last = -1; - } - public void set(K k) { - if (last == -1) - throw new IllegalStateException(); - it.unimi.dsi.fastutil.objects.ObjectArrayList.this.set(last, k); - } - public void remove() { - if (last == -1) - throw new IllegalStateException(); - it.unimi.dsi.fastutil.objects.ObjectArrayList.this.remove(last); - /* - * If the last operation was a next(), we are removing an - * element *before* us, and we must decrease pos - * correspondingly. - */ - if (last < pos) - pos--; - last = -1; - } - }; - } - - public it.unimi.dsi.fastutil.objects.ObjectArrayList clone() { - it.unimi.dsi.fastutil.objects.ObjectArrayList c = new it.unimi.dsi.fastutil.objects.ObjectArrayList(size); - System.arraycopy(a, 0, c.a, 0, size); - c.size = size; - return c; - } - - private boolean valEquals(final K a, final K b) { - return a == null ? b == null : a.equals(b); - } - - /** - * Compares this type-specific array list to another one. - * - *

- * This method exists only for sake of efficiency. The implementation - * inherited from the abstract implementation would already work. - * - * @param l - * a type-specific array list. - * @return true if the argument contains the same elements of this - * type-specific array list. - */ - public boolean equals(final it.unimi.dsi.fastutil.objects.ObjectArrayList l) { - if (l == this) - return true; - int s = size(); - if (s != l.size()) - return false; - final K[] a1 = a; - final K[] a2 = l.a; - - while (s-- != 0) - if (!valEquals(a1[s], a2[s])) - return false; - - return true; - } - - /** - * Compares this array list to another array list. - * - *

- * This method exists only for sake of efficiency. The implementation - * inherited from the abstract implementation would already work. - * - * @param l - * an array list. - * @return a negative integer, zero, or a positive integer as this list is - * lexicographically less than, equal to, or greater than the - * argument. - */ - @SuppressWarnings("unchecked") - public int compareTo(final it.unimi.dsi.fastutil.objects.ObjectArrayList l) { - final int s1 = size(), s2 = l.size(); - final K a1[] = a, a2[] = l.a; - K e1, e2; - int r, i; - - for (i = 0; i < s1 && i < s2; i++) { - e1 = a1[i]; - e2 = a2[i]; - if ((r = (((Comparable) (e1)).compareTo(e2))) != 0) - return r; - } - - return i < s2 ? -1 : (i < s1 ? 1 : 0); - } - - private void writeObject(java.io.ObjectOutputStream s) - throws java.io.IOException { - s.defaultWriteObject(); - for (int i = 0; i < size; i++) - s.writeObject(a[i]); - } - - @SuppressWarnings("unchecked") - private void readObject(java.io.ObjectInputStream s) - throws java.io.IOException, ClassNotFoundException { - s.defaultReadObject(); - a = (K[]) new Object[size]; - for (int i = 0; i < size; i++) - a[i] = (K) s.readObject(); - } -} diff --git a/src/main/java/it/unimi/dsi/fastutil/objects/ObjectArraySet.java b/src/main/java/it/unimi/dsi/fastutil/objects/ObjectArraySet.java deleted file mode 100644 index 07d064a..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/objects/ObjectArraySet.java +++ /dev/null @@ -1,277 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2007-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.objects; - -import it.unimi.dsi.fastutil.objects.AbstractObjectIterator; -import it.unimi.dsi.fastutil.objects.AbstractObjectSet; -import it.unimi.dsi.fastutil.objects.ObjectArrays; -import it.unimi.dsi.fastutil.objects.ObjectCollection; -import it.unimi.dsi.fastutil.objects.ObjectIterator; - -import java.util.Collection; -import java.util.NoSuchElementException; - -/** - * A simple, brute-force implementation of a set based on a backing array. - * - *

- * The main purpose of this implementation is that of wrapping cleanly the - * brute-force approach to the storage of a very small number of items: just put - * them into an array and scan linearly to find an item. - */ - -public class ObjectArraySet extends AbstractObjectSet - implements - java.io.Serializable, - Cloneable { - - private static final long serialVersionUID = 1L; - /** The backing array (valid up to {@link #size}, excluded). */ - private transient Object[] a; - /** The number of valid entries in {@link #a}. */ - private int size; - - /** - * Creates a new array set using the given backing array. The resulting set - * will have as many elements as the array. - * - *

- * It is responsibility of the caller that the elements of a - * are distinct. - * - * @param a - * the backing array. - */ - public ObjectArraySet(final Object[] a) { - this.a = a; - size = a.length; - } - - /** - * Creates a new empty array set. - */ - public ObjectArraySet() { - this.a = ObjectArrays.EMPTY_ARRAY; - } - - /** - * Creates a new empty array set of given initial capacity. - * - * @param capacity - * the initial capacity. - */ - public ObjectArraySet(final int capacity) { - this.a = new Object[capacity]; - } - - /** - * Creates a new array set copying the contents of a given collection. - * - * @param c - * a collection. - */ - public ObjectArraySet(ObjectCollection c) { - this(c.size()); - addAll(c); - } - - /** - * Creates a new array set copying the contents of a given set. - * - * @param c - * a collection. - */ - public ObjectArraySet(final Collection c) { - this(c.size()); - addAll(c); - } - - /** - * Creates a new array set using the given backing array and the given - * number of elements of the array. - * - *

- * It is responsibility of the caller that the first size - * elements of a are distinct. - * - * @param a - * the backing array. - * @param size - * the number of valid elements in a. - */ - public ObjectArraySet(final Object[] a, final int size) { - this.a = a; - this.size = size; - if (size > a.length) - throw new IllegalArgumentException("The provided size (" + size - + ") is larger than or equal to the array size (" - + a.length + ")"); - } - - private int findKey(final Object o) { - for (int i = size; i-- != 0;) - if (((a[i]) == null ? (o) == null : (a[i]).equals(o))) - return i; - return -1; - } - - @Override - @SuppressWarnings("unchecked") - public ObjectIterator iterator() { - return new AbstractObjectIterator() { - int next = 0; - - public boolean hasNext() { - return next < size; - } - - public K next() { - if (!hasNext()) - throw new NoSuchElementException(); - return (K) a[next++]; - } - - public void remove() { - final int tail = size-- - next--; - System.arraycopy(a, next + 1, a, next, tail); - - a[size] = null; - - } - }; - } - - public boolean contains(final Object k) { - return findKey(k) != -1; - } - - public int size() { - return size; - } - - @Override - public boolean remove(final Object k) { - final int pos = findKey(k); - if (pos == -1) - return false; - final int tail = size - pos - 1; - for (int i = 0; i < tail; i++) - a[pos + i] = a[pos + i + 1]; - size--; - - a[size] = null; - - return true; - } - - @Override - public boolean add(final K k) { - final int pos = findKey(k); - if (pos != -1) - return false; - if (size == a.length) { - final Object[] b = new Object[size == 0 ? 2 : size * 2]; - for (int i = size; i-- != 0;) - b[i] = a[i]; - a = b; - } - a[size++] = k; - return true; - } - - @Override - public void clear() { - - for (int i = size; i-- != 0;) - a[i] = null; - - size = 0; - } - - @Override - public boolean isEmpty() { - return size == 0; - } - - /** - * Returns a deep copy of this set. - * - *

- * This method performs a deep copy of this hash set; the data stored in the - * set, however, is not cloned. Note that this makes a difference only for - * object keys. - * - * @return a deep copy of this set. - */ - - @SuppressWarnings("unchecked") - public it.unimi.dsi.fastutil.objects.ObjectArraySet clone() { - it.unimi.dsi.fastutil.objects.ObjectArraySet c; - try { - c = (it.unimi.dsi.fastutil.objects.ObjectArraySet) super.clone(); - } catch (CloneNotSupportedException cantHappen) { - throw new InternalError(); - } - c.a = a.clone(); - return c; - } - - private void writeObject(java.io.ObjectOutputStream s) - throws java.io.IOException { - s.defaultWriteObject(); - for (int i = 0; i < size; i++) - s.writeObject(a[i]); - } - - private void readObject(java.io.ObjectInputStream s) - throws java.io.IOException, ClassNotFoundException { - s.defaultReadObject(); - a = new Object[size]; - for (int i = 0; i < size; i++) - a[i] = s.readObject(); - } - -} diff --git a/src/main/java/it/unimi/dsi/fastutil/objects/ObjectArrays.java b/src/main/java/it/unimi/dsi/fastutil/objects/ObjectArrays.java deleted file mode 100644 index 210b4b3..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/objects/ObjectArrays.java +++ /dev/null @@ -1,2225 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * - * - * For the sorting and binary search code: - * - * Copyright (C) 1999 CERN - European Organization for Nuclear Research. - * - * Permission to use, copy, modify, distribute and sell this software and - * its documentation for any purpose is hereby granted without fee, - * provided that the above copyright notice appear in all copies and that - * both that copyright notice and this permission notice appear in - * supporting documentation. CERN makes no representations about the - * suitability of this software for any purpose. It is provided "as is" - * without expressed or implied warranty. - */ - -package it.unimi.dsi.fastutil.objects; - -import it.unimi.dsi.fastutil.Arrays; -import it.unimi.dsi.fastutil.Hash; -import it.unimi.dsi.fastutil.ints.IntArrays; - -import java.util.Comparator; -import java.util.Random; -import java.util.concurrent.ForkJoinPool; -import java.util.concurrent.RecursiveAction; - -/** - * A class providing static methods and objects that do useful things with - * type-specific arrays. - * - * In particular, the ensureCapacity(), grow(), - * trim() and setLength() methods allow to handle - * arrays much like array lists. This can be very useful when efficiency (or - * syntactic simplicity) reasons make array lists unsuitable. - * - *

- * Warning: if your array is not of type {@code Object[]}, - * {@link #ensureCapacity(Object[],int,int)} and {@link #grow(Object[],int,int)} - * will use {@linkplain java.lang.reflect.Array#newInstance(Class,int) - * reflection} to preserve your array type. Reflection is - * significantly slower than using new. This phenomenon is - * particularly evident in the first growth phases of an array reallocated with - * doubling (or similar) logic. - * - *

Sorting

- * - *

- * There are several sorting methods available. The main theme is that of - * letting you choose the sorting algorithm you prefer (i.e., trading stability - * of mergesort for no memory allocation in quicksort). Several algorithms - * provide a parallel version, that will use the - * {@linkplain Runtime#availableProcessors() number of cores available}. - * - *

- * All comparison-based algorithm have an implementation based on a - * type-specific comparator. - * - *

- * If you are fine with not knowing exactly which algorithm will be run (in - * particular, not knowing exactly whether a support array will be allocated), - * the dual-pivot parallel sorts in {@link java.util.Arrays} are about 50% - * faster than the classical single-pivot implementation used here. - * - *

- * In any case, if sorting time is important I suggest that you benchmark your - * sorting load with your data distribution and on your architecture. - * - * @see java.util.Arrays - */ - -public class ObjectArrays { - - private ObjectArrays() { - } - - /** A static, final, empty array. */ - public final static Object[] EMPTY_ARRAY = {}; - - /** - * Creates a new array using a the given one as prototype. - * - *

- * This method returns a new array of the given length whose element are of - * the same class as of those of prototype. In case of an empty - * array, it tries to return {@link #EMPTY_ARRAY}, if possible. - * - * @param prototype - * an array that will be used to type the new one. - * @param length - * the length of the new array. - * @return a new array of given type and length. - */ - - @SuppressWarnings("unchecked") - private static K[] newArray(final K[] prototype, final int length) { - final Class klass = prototype.getClass(); - if (klass == Object[].class) - return (K[]) (length == 0 ? EMPTY_ARRAY : new Object[length]); - return (K[]) java.lang.reflect.Array.newInstance( - klass.getComponentType(), length); - } - - /** - * Ensures that an array can contain the given number of entries. - * - *

- * If you cannot foresee whether this array will need again to be enlarged, - * you should probably use grow() instead. - * - * @param array - * an array. - * @param length - * the new minimum length for this array. - * @return array, if it contains length entries or - * more; otherwise, an array with length entries whose - * first array.length entries are the same as those of - * array. - */ - public static K[] ensureCapacity(final K[] array, final int length) { - if (length > array.length) { - final K t[] = - - newArray(array, length); - - System.arraycopy(array, 0, t, 0, array.length); - return t; - } - return array; - } - - /** - * Ensures that an array can contain the given number of entries, preserving - * just a part of the array. - * - * @param array - * an array. - * @param length - * the new minimum length for this array. - * @param preserve - * the number of elements of the array that must be preserved in - * case a new allocation is necessary. - * @return array, if it can contain length entries - * or more; otherwise, an array with length entries - * whose first preserve entries are the same as those - * of array. - */ - public static K[] ensureCapacity(final K[] array, final int length, - final int preserve) { - if (length > array.length) { - final K t[] = - - newArray(array, length); - - System.arraycopy(array, 0, t, 0, preserve); - return t; - } - return array; - } - - /** - * Grows the given array to the maximum between the given length and the - * current length multiplied by two, provided that the given length is - * larger than the current length. - * - *

- * If you want complete control on the array growth, you should probably use - * ensureCapacity() instead. - * - * @param array - * an array. - * @param length - * the new minimum length for this array. - * @return array, if it can contain length - * entries; otherwise, an array with max(length, - * array.length/φ) entries whose first - * array.length entries are the same as those of - * array. - * */ - - public static K[] grow(final K[] array, final int length) { - if (length > array.length) { - final int newLength = (int) Math.max( - Math.min(2L * array.length, Arrays.MAX_ARRAY_SIZE), length); - final K t[] = - - newArray(array, newLength); - - System.arraycopy(array, 0, t, 0, array.length); - return t; - } - return array; - } - - /** - * Grows the given array to the maximum between the given length and the - * current length multiplied by two, provided that the given length is - * larger than the current length, preserving just a part of the array. - * - *

- * If you want complete control on the array growth, you should probably use - * ensureCapacity() instead. - * - * @param array - * an array. - * @param length - * the new minimum length for this array. - * @param preserve - * the number of elements of the array that must be preserved in - * case a new allocation is necessary. - * @return array, if it can contain length - * entries; otherwise, an array with max(length, - * array.length/φ) entries whose first - * preserve entries are the same as those of - * array. - * */ - - public static K[] grow(final K[] array, final int length, - final int preserve) { - - if (length > array.length) { - final int newLength = (int) Math.max( - Math.min(2L * array.length, Arrays.MAX_ARRAY_SIZE), length); - - final K t[] = - - newArray(array, newLength); - - System.arraycopy(array, 0, t, 0, preserve); - - return t; - } - return array; - - } - - /** - * Trims the given array to the given length. - * - * @param array - * an array. - * @param length - * the new maximum length for the array. - * @return array, if it contains length entries or - * less; otherwise, an array with length entries whose - * entries are the same as the first length entries of - * array. - * - */ - - public static K[] trim(final K[] array, final int length) { - if (length >= array.length) - return array; - final K t[] = - - newArray(array, length); - - System.arraycopy(array, 0, t, 0, length); - return t; - } - - /** - * Sets the length of the given array. - * - * @param array - * an array. - * @param length - * the new length for the array. - * @return array, if it contains exactly length - * entries; otherwise, if it contains more than - * length entries, an array with length - * entries whose entries are the same as the first - * length entries of array; otherwise, an - * array with length entries whose first - * array.length entries are the same as those of - * array. - * - */ - - public static K[] setLength(final K[] array, final int length) { - if (length == array.length) - return array; - if (length < array.length) - return trim(array, length); - return ensureCapacity(array, length); - } - - /** - * Returns a copy of a portion of an array. - * - * @param array - * an array. - * @param offset - * the first element to copy. - * @param length - * the number of elements to copy. - * @return a new array containing length elements of - * array starting at offset. - */ - - public static K[] copy(final K[] array, final int offset, - final int length) { - ensureOffsetLength(array, offset, length); - final K[] a = - - newArray(array, length); - - System.arraycopy(array, offset, a, 0, length); - return a; - } - - /** - * Returns a copy of an array. - * - * @param array - * an array. - * @return a copy of array. - */ - - public static K[] copy(final K[] array) { - return array.clone(); - } - - /** - * Fills the given array with the given value. - * - * @param array - * an array. - * @param value - * the new value for all elements of the array. - * @deprecated Please use the corresponding {@link java.util.Arrays} method. - */ - - @Deprecated - public static void fill(final K[] array, final K value) { - int i = array.length; - while (i-- != 0) - array[i] = value; - } - - /** - * Fills a portion of the given array with the given value. - * - * @param array - * an array. - * @param from - * the starting index of the portion to fill (inclusive). - * @param to - * the end index of the portion to fill (exclusive). - * @param value - * the new value for all elements of the specified portion of the - * array. - * @deprecated Please use the corresponding {@link java.util.Arrays} method. - */ - - @Deprecated - public static void fill(final K[] array, final int from, int to, - final K value) { - ensureFromTo(array, from, to); - if (from == 0) - while (to-- != 0) - array[to] = value; - else - for (int i = from; i < to; i++) - array[i] = value; - } - - /** - * Returns true if the two arrays are elementwise equal. - * - * @param a1 - * an array. - * @param a2 - * another array. - * @return true if the two arrays are of the same length, and their elements - * are equal. - * @deprecated Please use the corresponding {@link java.util.Arrays} method, - * which is intrinsified in recent JVMs. - */ - - @Deprecated - public static boolean equals(final K[] a1, final K a2[]) { - int i = a1.length; - if (i != a2.length) - return false; - while (i-- != 0) - if (!((a1[i]) == null ? (a2[i]) == null : (a1[i]).equals(a2[i]))) - return false; - return true; - } - - /** - * Ensures that a range given by its first (inclusive) and last (exclusive) - * elements fits an array. - * - *

- * This method may be used whenever an array range check is needed. - * - * @param a - * an array. - * @param from - * a start index (inclusive). - * @param to - * an end index (exclusive). - * @throws IllegalArgumentException - * if from is greater than to. - * @throws ArrayIndexOutOfBoundsException - * if from or to are greater than the - * array length or negative. - */ - public static void ensureFromTo(final K[] a, final int from, - final int to) { - Arrays.ensureFromTo(a.length, from, to); - } - - /** - * Ensures that a range given by an offset and a length fits an array. - * - *

- * This method may be used whenever an array range check is needed. - * - * @param a - * an array. - * @param offset - * a start index. - * @param length - * a length (the number of elements in the range). - * @throws IllegalArgumentException - * if length is negative. - * @throws ArrayIndexOutOfBoundsException - * if offset is negative or offset+ - * length is greater than the array length. - */ - public static void ensureOffsetLength(final K[] a, final int offset, - final int length) { - Arrays.ensureOffsetLength(a.length, offset, length); - } - - /** - * Ensures that two arrays are of the same length. - * - * @param a - * an array. - * @param b - * another array. - * @throws IllegalArgumentException - * if the two argument arrays are not of the same length. - */ - public static void ensureSameLength(final K[] a, final K[] b) { - if (a.length != b.length) - throw new IllegalArgumentException("Array size mismatch: " - + a.length + " != " + b.length); - } - - private static final int QUICKSORT_NO_REC = 16; - private static final int PARALLEL_QUICKSORT_NO_FORK = 8192; - private static final int QUICKSORT_MEDIAN_OF_9 = 128; - private static final int MERGESORT_NO_REC = 16; - - /** - * Swaps two elements of an anrray. - * - * @param x - * an array. - * @param a - * a position in {@code x}. - * @param b - * another position in {@code x}. - */ - public static void swap(final K x[], final int a, final int b) { - final K t = x[a]; - x[a] = x[b]; - x[b] = t; - } - - /** - * Swaps two sequences of elements of an array. - * - * @param x - * an array. - * @param a - * a position in {@code x}. - * @param b - * another position in {@code x}. - * @param n - * the number of elements to exchange starting at {@code a} and - * {@code b}. - */ - public static void swap(final K[] x, int a, int b, final int n) { - for (int i = 0; i < n; i++, a++, b++) - swap(x, a, b); - } - - private static int med3(final K x[], final int a, final int b, - final int c, Comparator comp) { - final int ab = comp.compare(x[a], x[b]); - final int ac = comp.compare(x[a], x[c]); - final int bc = comp.compare(x[b], x[c]); - return (ab < 0 ? (bc < 0 ? b : ac < 0 ? c : a) : (bc > 0 ? b : ac > 0 - ? c - : a)); - } - - private static void selectionSort(final K[] a, final int from, - final int to, final Comparator comp) { - for (int i = from; i < to - 1; i++) { - int m = i; - for (int j = i + 1; j < to; j++) - if (comp.compare(a[j], a[m]) < 0) - m = j; - if (m != i) { - final K u = a[i]; - a[i] = a[m]; - a[m] = u; - } - } - } - - private static void insertionSort(final K[] a, final int from, - final int to, final Comparator comp) { - for (int i = from; ++i < to;) { - K t = a[i]; - int j = i; - for (K u = a[j - 1]; comp.compare(t, u) < 0; u = a[--j - 1]) { - a[j] = u; - if (from == j - 1) { - --j; - break; - } - } - a[j] = t; - } - } - - /** - * Sorts the specified range of elements according to the order induced by - * the specified comparator using quicksort. - * - *

- * The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley - * and M. Douglas McIlroy, “Engineering a Sort Function”, - * Software: Practice and Experience, 23(11), pages 1249−1265, - * 1993. - * - *

- * Note that this implementation does not allocate any object, contrarily to - * the implementation used to sort primitive types in - * {@link java.util.Arrays}, which switches to mergesort on large inputs. - * - * @param x - * the array to be sorted. - * @param from - * the index of the first element (inclusive) to be sorted. - * @param to - * the index of the last element (exclusive) to be sorted. - * @param comp - * the comparator to determine the sorting order. - * - */ - public static void quickSort(final K[] x, final int from, final int to, - final Comparator comp) { - final int len = to - from; - // Selection sort on smallest arrays - if (len < QUICKSORT_NO_REC) { - selectionSort(x, from, to, comp); - return; - } - - // Choose a partition element, v - int m = from + len / 2; - int l = from; - int n = to - 1; - if (len > QUICKSORT_MEDIAN_OF_9) { // Big arrays, pseudomedian of 9 - int s = len / 8; - l = med3(x, l, l + s, l + 2 * s, comp); - m = med3(x, m - s, m, m + s, comp); - n = med3(x, n - 2 * s, n - s, n, comp); - } - m = med3(x, l, m, n, comp); // Mid-size, med of 3 - - final K v = x[m]; - - // Establish Invariant: v* (v)* v* - int a = from, b = a, c = to - 1, d = c; - while (true) { - int comparison; - while (b <= c && (comparison = comp.compare(x[b], v)) <= 0) { - if (comparison == 0) - swap(x, a++, b); - b++; - } - while (c >= b && (comparison = comp.compare(x[c], v)) >= 0) { - if (comparison == 0) - swap(x, c, d--); - c--; - } - if (b > c) - break; - swap(x, b++, c--); - } - - // Swap partition elements back to middle - int s; - s = Math.min(a - from, b - a); - swap(x, from, b - s, s); - s = Math.min(d - c, to - d - 1); - swap(x, b, to - s, s); - - // Recursively sort non-partition-elements - if ((s = b - a) > 1) - quickSort(x, from, from + s, comp); - if ((s = d - c) > 1) - quickSort(x, to - s, to, comp); - } - - /** - * Sorts an array according to the order induced by the specified comparator - * using quicksort. - * - *

- * The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley - * and M. Douglas McIlroy, “Engineering a Sort Function”, - * Software: Practice and Experience, 23(11), pages 1249−1265, - * 1993. - * - *

- * Note that this implementation does not allocate any object, contrarily to - * the implementation used to sort primitive types in - * {@link java.util.Arrays}, which switches to mergesort on large inputs. - * - * @param x - * the array to be sorted. - * @param comp - * the comparator to determine the sorting order. - * - */ - public static void quickSort(final K[] x, final Comparator comp) { - quickSort(x, 0, x.length, comp); - } - - protected static class ForkJoinQuickSortComp extends RecursiveAction { - private static final long serialVersionUID = 1L; - private final int from; - private final int to; - private final K[] x; - private final Comparator comp; - - public ForkJoinQuickSortComp(final K[] x, final int from, final int to, - final Comparator comp) { - this.from = from; - this.to = to; - this.x = x; - this.comp = comp; - } - - @Override - protected void compute() { - final K[] x = this.x; - final int len = to - from; - if (len < PARALLEL_QUICKSORT_NO_FORK) { - quickSort(x, from, to, comp); - return; - } - // Choose a partition element, v - int m = from + len / 2; - int l = from; - int n = to - 1; - int s = len / 8; - l = med3(x, l, l + s, l + 2 * s, comp); - m = med3(x, m - s, m, m + s, comp); - n = med3(x, n - 2 * s, n - s, n, comp); - m = med3(x, l, m, n, comp); - final K v = x[m]; - // Establish Invariant: v* (v)* v* - int a = from, b = a, c = to - 1, d = c; - while (true) { - int comparison; - while (b <= c && (comparison = comp.compare(x[b], v)) <= 0) { - if (comparison == 0) - swap(x, a++, b); - b++; - } - while (c >= b && (comparison = comp.compare(x[c], v)) >= 0) { - if (comparison == 0) - swap(x, c, d--); - c--; - } - if (b > c) - break; - swap(x, b++, c--); - } - // Swap partition elements back to middle - int t; - s = Math.min(a - from, b - a); - swap(x, from, b - s, s); - s = Math.min(d - c, to - d - 1); - swap(x, b, to - s, s); - // Recursively sort non-partition-elements - s = b - a; - t = d - c; - if (s > 1 && t > 1) - invokeAll( - new ForkJoinQuickSortComp(x, from, from + s, comp), - new ForkJoinQuickSortComp(x, to - t, to, comp)); - else if (s > 1) - invokeAll(new ForkJoinQuickSortComp(x, from, from + s, comp)); - else - invokeAll(new ForkJoinQuickSortComp(x, to - t, to, comp)); - } - } - - /** - * Sorts the specified range of elements according to the order induced by - * the specified comparator using a parallel quicksort. - * - *

- * The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley - * and M. Douglas McIlroy, “Engineering a Sort Function”, - * Software: Practice and Experience, 23(11), pages 1249−1265, - * 1993. - * - *

- * This implementation uses a {@link ForkJoinPool} executor service with - * {@link Runtime#availableProcessors()} parallel threads. - * - * @param x - * the array to be sorted. - * @param from - * the index of the first element (inclusive) to be sorted. - * @param to - * the index of the last element (exclusive) to be sorted. - * @param comp - * the comparator to determine the sorting order. - */ - public static void parallelQuickSort(final K[] x, final int from, - final int to, final Comparator comp) { - if (to - from < PARALLEL_QUICKSORT_NO_FORK) - quickSort(x, from, to, comp); - else { - final ForkJoinPool pool = new ForkJoinPool(Runtime.getRuntime() - .availableProcessors()); - pool.invoke(new ForkJoinQuickSortComp(x, from, to, comp)); - pool.shutdown(); - } - } - - /** - * Sorts an array according to the order induced by the specified comparator - * using a parallel quicksort. - * - *

- * The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley - * and M. Douglas McIlroy, “Engineering a Sort Function”, - * Software: Practice and Experience, 23(11), pages 1249−1265, - * 1993. - * - *

- * This implementation uses a {@link ForkJoinPool} executor service with - * {@link Runtime#availableProcessors()} parallel threads. - * - * @param x - * the array to be sorted. - * @param comp - * the comparator to determine the sorting order. - */ - public static void parallelQuickSort(final K[] x, - final Comparator comp) { - parallelQuickSort(x, 0, x.length, comp); - } - - @SuppressWarnings("unchecked") - private static int med3(final K x[], final int a, final int b, - final int c) { - final int ab = (((Comparable) (x[a])).compareTo(x[b])); - final int ac = (((Comparable) (x[a])).compareTo(x[c])); - final int bc = (((Comparable) (x[b])).compareTo(x[c])); - return (ab < 0 ? (bc < 0 ? b : ac < 0 ? c : a) : (bc > 0 ? b : ac > 0 - ? c - : a)); - } - - @SuppressWarnings("unchecked") - private static void selectionSort(final K[] a, final int from, - final int to) { - for (int i = from; i < to - 1; i++) { - int m = i; - for (int j = i + 1; j < to; j++) - if ((((Comparable) (a[j])).compareTo(a[m]) < 0)) - m = j; - if (m != i) { - final K u = a[i]; - a[i] = a[m]; - a[m] = u; - } - } - } - - @SuppressWarnings("unchecked") - private static void insertionSort(final K[] a, final int from, - final int to) { - for (int i = from; ++i < to;) { - K t = a[i]; - int j = i; - for (K u = a[j - 1]; (((Comparable) (t)).compareTo(u) < 0); u = a[--j - 1]) { - a[j] = u; - if (from == j - 1) { - --j; - break; - } - } - a[j] = t; - } - } - - /** - * Sorts the specified range of elements according to the natural ascending - * order using quicksort. - * - *

- * The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley - * and M. Douglas McIlroy, “Engineering a Sort Function”, - * Software: Practice and Experience, 23(11), pages 1249−1265, - * 1993. - * - *

- * Note that this implementation does not allocate any object, contrarily to - * the implementation used to sort primitive types in - * {@link java.util.Arrays}, which switches to mergesort on large inputs. - * - * @param x - * the array to be sorted. - * @param from - * the index of the first element (inclusive) to be sorted. - * @param to - * the index of the last element (exclusive) to be sorted. - */ - - @SuppressWarnings("unchecked") - public static void quickSort(final K[] x, final int from, final int to) { - final int len = to - from; - // Selection sort on smallest arrays - if (len < QUICKSORT_NO_REC) { - selectionSort(x, from, to); - return; - } - - // Choose a partition element, v - int m = from + len / 2; - int l = from; - int n = to - 1; - if (len > QUICKSORT_MEDIAN_OF_9) { // Big arrays, pseudomedian of 9 - int s = len / 8; - l = med3(x, l, l + s, l + 2 * s); - m = med3(x, m - s, m, m + s); - n = med3(x, n - 2 * s, n - s, n); - } - m = med3(x, l, m, n); // Mid-size, med of 3 - - final K v = x[m]; - - // Establish Invariant: v* (v)* v* - int a = from, b = a, c = to - 1, d = c; - while (true) { - int comparison; - while (b <= c - && (comparison = (((Comparable) (x[b])).compareTo(v))) <= 0) { - if (comparison == 0) - swap(x, a++, b); - b++; - } - while (c >= b - && (comparison = (((Comparable) (x[c])).compareTo(v))) >= 0) { - if (comparison == 0) - swap(x, c, d--); - c--; - } - if (b > c) - break; - swap(x, b++, c--); - } - - // Swap partition elements back to middle - int s; - s = Math.min(a - from, b - a); - swap(x, from, b - s, s); - s = Math.min(d - c, to - d - 1); - swap(x, b, to - s, s); - - // Recursively sort non-partition-elements - if ((s = b - a) > 1) - quickSort(x, from, from + s); - if ((s = d - c) > 1) - quickSort(x, to - s, to); - } - - /** - * Sorts an array according to the natural ascending order using quicksort. - * - *

- * The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley - * and M. Douglas McIlroy, “Engineering a Sort Function”, - * Software: Practice and Experience, 23(11), pages 1249−1265, - * 1993. - * - *

- * Note that this implementation does not allocate any object, contrarily to - * the implementation used to sort primitive types in - * {@link java.util.Arrays}, which switches to mergesort on large inputs. - * - * @param x - * the array to be sorted. - * - */ - public static void quickSort(final K[] x) { - quickSort(x, 0, x.length); - } - - protected static class ForkJoinQuickSort extends RecursiveAction { - private static final long serialVersionUID = 1L; - private final int from; - private final int to; - private final K[] x; - - public ForkJoinQuickSort(final K[] x, final int from, final int to) { - this.from = from; - this.to = to; - this.x = x; - } - - @Override - @SuppressWarnings("unchecked") - protected void compute() { - final K[] x = this.x; - final int len = to - from; - if (len < PARALLEL_QUICKSORT_NO_FORK) { - quickSort(x, from, to); - return; - } - // Choose a partition element, v - int m = from + len / 2; - int l = from; - int n = to - 1; - int s = len / 8; - l = med3(x, l, l + s, l + 2 * s); - m = med3(x, m - s, m, m + s); - n = med3(x, n - 2 * s, n - s, n); - m = med3(x, l, m, n); - final K v = x[m]; - // Establish Invariant: v* (v)* v* - int a = from, b = a, c = to - 1, d = c; - while (true) { - int comparison; - while (b <= c - && (comparison = (((Comparable) (x[b])).compareTo(v))) <= 0) { - if (comparison == 0) - swap(x, a++, b); - b++; - } - while (c >= b - && (comparison = (((Comparable) (x[c])).compareTo(v))) >= 0) { - if (comparison == 0) - swap(x, c, d--); - c--; - } - if (b > c) - break; - swap(x, b++, c--); - } - // Swap partition elements back to middle - int t; - s = Math.min(a - from, b - a); - swap(x, from, b - s, s); - s = Math.min(d - c, to - d - 1); - swap(x, b, to - s, s); - // Recursively sort non-partition-elements - s = b - a; - t = d - c; - if (s > 1 && t > 1) - invokeAll(new ForkJoinQuickSort(x, from, from + s), - new ForkJoinQuickSort(x, to - t, to)); - else if (s > 1) - invokeAll(new ForkJoinQuickSort(x, from, from + s)); - else - invokeAll(new ForkJoinQuickSort(x, to - t, to)); - } - } - - /** - * Sorts the specified range of elements according to the natural ascending - * order using a parallel quicksort. - * - *

- * The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley - * and M. Douglas McIlroy, “Engineering a Sort Function”, - * Software: Practice and Experience, 23(11), pages 1249−1265, - * 1993. - * - *

- * This implementation uses a {@link ForkJoinPool} executor service with - * {@link Runtime#availableProcessors()} parallel threads. - * - * @param x - * the array to be sorted. - * @param from - * the index of the first element (inclusive) to be sorted. - * @param to - * the index of the last element (exclusive) to be sorted. - */ - public static void parallelQuickSort(final K[] x, final int from, - final int to) { - if (to - from < PARALLEL_QUICKSORT_NO_FORK) - quickSort(x, from, to); - else { - final ForkJoinPool pool = new ForkJoinPool(Runtime.getRuntime() - .availableProcessors()); - pool.invoke(new ForkJoinQuickSort(x, from, to)); - pool.shutdown(); - } - } - - /** - * Sorts an array according to the natural ascending order using a parallel - * quicksort. - * - *

- * The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley - * and M. Douglas McIlroy, “Engineering a Sort Function”, - * Software: Practice and Experience, 23(11), pages 1249−1265, - * 1993. - * - *

- * This implementation uses a {@link ForkJoinPool} executor service with - * {@link Runtime#availableProcessors()} parallel threads. - * - * @param x - * the array to be sorted. - * - */ - public static void parallelQuickSort(final K[] x) { - parallelQuickSort(x, 0, x.length); - } - - @SuppressWarnings("unchecked") - private static int med3Indirect(final int perm[], final K x[], - final int a, final int b, final int c) { - final K aa = x[perm[a]]; - final K bb = x[perm[b]]; - final K cc = x[perm[c]]; - final int ab = (((Comparable) (aa)).compareTo(bb)); - final int ac = (((Comparable) (aa)).compareTo(cc)); - final int bc = (((Comparable) (bb)).compareTo(cc)); - return (ab < 0 ? (bc < 0 ? b : ac < 0 ? c : a) : (bc > 0 ? b : ac > 0 - ? c - : a)); - } - - @SuppressWarnings("unchecked") - private static void insertionSortIndirect(final int[] perm, - final K[] a, final int from, final int to) { - for (int i = from; ++i < to;) { - int t = perm[i]; - int j = i; - for (int u = perm[j - 1]; (((Comparable) (a[t])).compareTo(a[u]) < 0); u = perm[--j - 1]) { - perm[j] = u; - if (from == j - 1) { - --j; - break; - } - } - perm[j] = t; - } - } - - /** - * Sorts the specified range of elements according to the natural ascending - * order using indirect quicksort. - * - *

- * The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley - * and M. Douglas McIlroy, “Engineering a Sort Function”, - * Software: Practice and Experience, 23(11), pages 1249−1265, - * 1993. - * - *

- * This method implement an indirect sort. The elements of - * perm (which must be exactly the numbers in the interval - * [0..perm.length)) will be permuted so that - * x[ perm[ i ] ] ≤ x[ perm[ i + 1 ] ]. - * - *

- * Note that this implementation does not allocate any object, contrarily to - * the implementation used to sort primitive types in - * {@link java.util.Arrays}, which switches to mergesort on large inputs. - * - * @param perm - * a permutation array indexing {@code x}. - * @param x - * the array to be sorted. - * @param from - * the index of the first element (inclusive) to be sorted. - * @param to - * the index of the last element (exclusive) to be sorted. - */ - - @SuppressWarnings("unchecked") - public static void quickSortIndirect(final int[] perm, final K[] x, - final int from, final int to) { - final int len = to - from; - // Selection sort on smallest arrays - if (len < QUICKSORT_NO_REC) { - insertionSortIndirect(perm, x, from, to); - return; - } - - // Choose a partition element, v - int m = from + len / 2; - int l = from; - int n = to - 1; - if (len > QUICKSORT_MEDIAN_OF_9) { // Big arrays, pseudomedian of 9 - int s = len / 8; - l = med3Indirect(perm, x, l, l + s, l + 2 * s); - m = med3Indirect(perm, x, m - s, m, m + s); - n = med3Indirect(perm, x, n - 2 * s, n - s, n); - } - m = med3Indirect(perm, x, l, m, n); // Mid-size, med of 3 - - final K v = x[perm[m]]; - - // Establish Invariant: v* (v)* v* - int a = from, b = a, c = to - 1, d = c; - while (true) { - int comparison; - while (b <= c - && (comparison = (((Comparable) (x[perm[b]])) - .compareTo(v))) <= 0) { - if (comparison == 0) - IntArrays.swap(perm, a++, b); - b++; - } - while (c >= b - && (comparison = (((Comparable) (x[perm[c]])) - .compareTo(v))) >= 0) { - if (comparison == 0) - IntArrays.swap(perm, c, d--); - c--; - } - if (b > c) - break; - IntArrays.swap(perm, b++, c--); - } - - // Swap partition elements back to middle - int s; - s = Math.min(a - from, b - a); - IntArrays.swap(perm, from, b - s, s); - s = Math.min(d - c, to - d - 1); - IntArrays.swap(perm, b, to - s, s); - - // Recursively sort non-partition-elements - if ((s = b - a) > 1) - quickSortIndirect(perm, x, from, from + s); - if ((s = d - c) > 1) - quickSortIndirect(perm, x, to - s, to); - } - - /** - * Sorts an array according to the natural ascending order using indirect - * quicksort. - * - *

- * The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley - * and M. Douglas McIlroy, “Engineering a Sort Function”, - * Software: Practice and Experience, 23(11), pages 1249−1265, - * 1993. - * - *

- * This method implement an indirect sort. The elements of - * perm (which must be exactly the numbers in the interval - * [0..perm.length)) will be permuted so that - * x[ perm[ i ] ] ≤ x[ perm[ i + 1 ] ]. - * - *

- * Note that this implementation does not allocate any object, contrarily to - * the implementation used to sort primitive types in - * {@link java.util.Arrays}, which switches to mergesort on large inputs. - * - * @param perm - * a permutation array indexing {@code x}. - * @param x - * the array to be sorted. - */ - public static void quickSortIndirect(final int perm[], final K[] x) { - quickSortIndirect(perm, x, 0, x.length); - } - - protected static class ForkJoinQuickSortIndirect extends RecursiveAction { - private static final long serialVersionUID = 1L; - private final int from; - private final int to; - private final int[] perm; - private final K[] x; - - public ForkJoinQuickSortIndirect(final int perm[], final K[] x, - final int from, final int to) { - this.from = from; - this.to = to; - this.x = x; - this.perm = perm; - } - - @Override - @SuppressWarnings("unchecked") - protected void compute() { - final K[] x = this.x; - final int len = to - from; - if (len < PARALLEL_QUICKSORT_NO_FORK) { - quickSortIndirect(perm, x, from, to); - return; - } - // Choose a partition element, v - int m = from + len / 2; - int l = from; - int n = to - 1; - int s = len / 8; - l = med3Indirect(perm, x, l, l + s, l + 2 * s); - m = med3Indirect(perm, x, m - s, m, m + s); - n = med3Indirect(perm, x, n - 2 * s, n - s, n); - m = med3Indirect(perm, x, l, m, n); - final K v = x[perm[m]]; - // Establish Invariant: v* (v)* v* - int a = from, b = a, c = to - 1, d = c; - while (true) { - int comparison; - while (b <= c - && (comparison = (((Comparable) (x[perm[b]])) - .compareTo(v))) <= 0) { - if (comparison == 0) - IntArrays.swap(perm, a++, b); - b++; - } - while (c >= b - && (comparison = (((Comparable) (x[perm[c]])) - .compareTo(v))) >= 0) { - if (comparison == 0) - IntArrays.swap(perm, c, d--); - c--; - } - if (b > c) - break; - IntArrays.swap(perm, b++, c--); - } - // Swap partition elements back to middle - int t; - s = Math.min(a - from, b - a); - IntArrays.swap(perm, from, b - s, s); - s = Math.min(d - c, to - d - 1); - IntArrays.swap(perm, b, to - s, s); - // Recursively sort non-partition-elements - s = b - a; - t = d - c; - if (s > 1 && t > 1) - invokeAll(new ForkJoinQuickSortIndirect(perm, x, from, from - + s), new ForkJoinQuickSortIndirect(perm, x, to - t, - to)); - else if (s > 1) - invokeAll(new ForkJoinQuickSortIndirect(perm, x, from, from - + s)); - else - invokeAll(new ForkJoinQuickSortIndirect(perm, x, to - t, to)); - } - } - - /** - * Sorts the specified range of elements according to the natural ascending - * order using a parallel indirect quicksort. - * - *

- * The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley - * and M. Douglas McIlroy, “Engineering a Sort Function”, - * Software: Practice and Experience, 23(11), pages 1249−1265, - * 1993. - * - *

- * This method implement an indirect sort. The elements of - * perm (which must be exactly the numbers in the interval - * [0..perm.length)) will be permuted so that - * x[ perm[ i ] ] ≤ x[ perm[ i + 1 ] ]. - * - *

- * This implementation uses a {@link ForkJoinPool} executor service with - * {@link Runtime#availableProcessors()} parallel threads. - * - * @param perm - * a permutation array indexing {@code x}. - * @param x - * the array to be sorted. - * @param from - * the index of the first element (inclusive) to be sorted. - * @param to - * the index of the last element (exclusive) to be sorted. - */ - public static void parallelQuickSortIndirect(final int[] perm, - final K[] x, final int from, final int to) { - if (to - from < PARALLEL_QUICKSORT_NO_FORK) - quickSortIndirect(perm, x, from, to); - else { - final ForkJoinPool pool = new ForkJoinPool(Runtime.getRuntime() - .availableProcessors()); - pool.invoke(new ForkJoinQuickSortIndirect(perm, x, from, to)); - pool.shutdown(); - } - } - - /** - * Sorts an array according to the natural ascending order using a parallel - * indirect quicksort. - * - *

- * The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley - * and M. Douglas McIlroy, “Engineering a Sort Function”, - * Software: Practice and Experience, 23(11), pages 1249−1265, - * 1993. - * - *

- * This method implement an indirect sort. The elements of - * perm (which must be exactly the numbers in the interval - * [0..perm.length)) will be permuted so that - * x[ perm[ i ] ] ≤ x[ perm[ i + 1 ] ]. - * - *

- * This implementation uses a {@link ForkJoinPool} executor service with - * {@link Runtime#availableProcessors()} parallel threads. - * - * @param perm - * a permutation array indexing {@code x}. - * @param x - * the array to be sorted. - * - */ - public static void parallelQuickSortIndirect(final int perm[], - final K[] x) { - parallelQuickSortIndirect(perm, x, 0, x.length); - } - - /** - * Stabilizes a permutation. - * - *

- * This method can be used to stabilize the permutation generated by an - * indirect sorting, assuming that initially the permutation array was in - * ascending order (e.g., the identity, as usually happens). This method - * scans the permutation, and for each non-singleton block of elements with - * the same associated values in {@code x}, permutes them in ascending order. - * The resulting permutation corresponds to a stable sort. - * - *

- * Usually combining an unstable indirect sort and this method is more - * efficient than using a stable sort, as most stable sort algorithms - * require a support array. - * - *

- * More precisely, assuming that - * x[ perm[ i ] ] ≤ x[ perm[ i + 1 ] ], after stabilization - * we will also have that x[ perm[ i ] ] = x[ perm[ i + 1 ] ] - * implies perm[ i ] ≤ perm[ i + 1 ]. - * - * @param perm - * a permutation array indexing {@code x} so that it is sorted. - * @param x - * the sorted array to be stabilized. - * @param from - * the index of the first element (inclusive) to be stabilized. - * @param to - * the index of the last element (exclusive) to be stabilized. - */ - public static void stabilize(final int perm[], final K[] x, - final int from, final int to) { - int curr = from; - for (int i = from + 1; i < to; i++) { - if (x[perm[i]] != x[perm[curr]]) { - if (i - curr > 1) - IntArrays.parallelQuickSort(perm, curr, i); - curr = i; - } - } - if (to - curr > 1) - IntArrays.parallelQuickSort(perm, curr, to); - } - - /** - * Stabilizes a permutation. - * - *

- * This method can be used to stabilize the permutation generated by an - * indirect sorting, assuming that initially the permutation array was in - * ascending order (e.g., the identity, as usually happens). This method - * scans the permutation, and for each non-singleton block of elements with - * the same associated values in {@code x}, permutes them in ascending order. - * The resulting permutation corresponds to a stable sort. - * - *

- * Usually combining an unstable indirect sort and this method is more - * efficient than using a stable sort, as most stable sort algorithms - * require a support array. - * - *

- * More precisely, assuming that - * x[ perm[ i ] ] ≤ x[ perm[ i + 1 ] ], after stabilization - * we will also have that x[ perm[ i ] ] = x[ perm[ i + 1 ] ] - * implies perm[ i ] ≤ perm[ i + 1 ]. - * - * @param perm - * a permutation array indexing {@code x} so that it is sorted. - * @param x - * the sorted array to be stabilized. - */ - public static void stabilize(final int perm[], final K[] x) { - stabilize(perm, x, 0, perm.length); - } - - @SuppressWarnings("unchecked") - private static int med3(final K x[], final K[] y, final int a, - final int b, final int c) { - int t; - final int ab = (t = (((Comparable) (x[a])).compareTo(x[b]))) == 0 - ? (((Comparable) (y[a])).compareTo(y[b])) - : t; - final int ac = (t = (((Comparable) (x[a])).compareTo(x[c]))) == 0 - ? (((Comparable) (y[a])).compareTo(y[c])) - : t; - final int bc = (t = (((Comparable) (x[b])).compareTo(x[c]))) == 0 - ? (((Comparable) (y[b])).compareTo(y[c])) - : t; - return (ab < 0 ? (bc < 0 ? b : ac < 0 ? c : a) : (bc > 0 ? b : ac > 0 - ? c - : a)); - } - - private static void swap(final K x[], final K[] y, final int a, - final int b) { - final K t = x[a]; - final K u = y[a]; - x[a] = x[b]; - y[a] = y[b]; - x[b] = t; - y[b] = u; - } - - private static void swap(final K[] x, final K[] y, int a, int b, - final int n) { - for (int i = 0; i < n; i++, a++, b++) - swap(x, y, a, b); - } - - @SuppressWarnings("unchecked") - private static void selectionSort(final K[] a, final K[] b, - final int from, final int to) { - for (int i = from; i < to - 1; i++) { - int m = i, u; - for (int j = i + 1; j < to; j++) - if ((u = (((Comparable) (a[j])).compareTo(a[m]))) < 0 - || u == 0 - && (((Comparable) (b[j])).compareTo(b[m]) < 0)) - m = j; - - if (m != i) { - K t = a[i]; - a[i] = a[m]; - a[m] = t; - t = b[i]; - b[i] = b[m]; - b[m] = t; - } - } - } - - /** - * Sorts the specified range of elements of two arrays according to the - * natural lexicographical ascending order using quicksort. - * - *

- * The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley - * and M. Douglas McIlroy, “Engineering a Sort Function”, - * Software: Practice and Experience, 23(11), pages 1249−1265, - * 1993. - * - *

- * This method implements a lexicographical sorting of the - * arguments. Pairs of elements in the same position in the two provided - * arrays will be considered a single key, and permuted accordingly. In the - * end, either x[ i ] < x[ i + 1 ] or x[ i ] - * == x[ i + 1 ] and y[ i ] ≤ y[ i + 1 ]. - * - * @param x - * the first array to be sorted. - * @param y - * the second array to be sorted. - * @param from - * the index of the first element (inclusive) to be sorted. - * @param to - * the index of the last element (exclusive) to be sorted. - */ - - @SuppressWarnings("unchecked") - public static void quickSort(final K[] x, final K[] y, final int from, - final int to) { - final int len = to - from; - if (len < QUICKSORT_NO_REC) { - selectionSort(x, y, from, to); - return; - } - // Choose a partition element, v - int m = from + len / 2; - int l = from; - int n = to - 1; - if (len > QUICKSORT_MEDIAN_OF_9) { // Big arrays, pseudomedian of 9 - int s = len / 8; - l = med3(x, y, l, l + s, l + 2 * s); - m = med3(x, y, m - s, m, m + s); - n = med3(x, y, n - 2 * s, n - s, n); - } - m = med3(x, y, l, m, n); // Mid-size, med of 3 - final K v = x[m], w = y[m]; - // Establish Invariant: v* (v)* v* - int a = from, b = a, c = to - 1, d = c; - while (true) { - int comparison, t; - while (b <= c - && (comparison = (t = (((Comparable) (x[b])) - .compareTo(v))) == 0 ? (((Comparable) (y[b])) - .compareTo(w)) : t) <= 0) { - if (comparison == 0) - swap(x, y, a++, b); - b++; - } - while (c >= b - && (comparison = (t = (((Comparable) (x[c])) - .compareTo(v))) == 0 ? (((Comparable) (y[c])) - .compareTo(w)) : t) >= 0) { - if (comparison == 0) - swap(x, y, c, d--); - c--; - } - if (b > c) - break; - swap(x, y, b++, c--); - } - // Swap partition elements back to middle - int s; - s = Math.min(a - from, b - a); - swap(x, y, from, b - s, s); - s = Math.min(d - c, to - d - 1); - swap(x, y, b, to - s, s); - // Recursively sort non-partition-elements - if ((s = b - a) > 1) - quickSort(x, y, from, from + s); - if ((s = d - c) > 1) - quickSort(x, y, to - s, to); - } - - /** - * Sorts two arrays according to the natural lexicographical ascending order - * using quicksort. - * - *

- * The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley - * and M. Douglas McIlroy, “Engineering a Sort Function”, - * Software: Practice and Experience, 23(11), pages 1249−1265, - * 1993. - * - *

- * This method implements a lexicographical sorting of the - * arguments. Pairs of elements in the same position in the two provided - * arrays will be considered a single key, and permuted accordingly. In the - * end, either x[ i ] < x[ i + 1 ] or x[ i ] - * == x[ i + 1 ] and y[ i ] ≤ y[ i + 1 ]. - * - * @param x - * the first array to be sorted. - * @param y - * the second array to be sorted. - */ - public static void quickSort(final K[] x, final K[] y) { - ensureSameLength(x, y); - quickSort(x, y, 0, x.length); - } - - protected static class ForkJoinQuickSort2 extends RecursiveAction { - private static final long serialVersionUID = 1L; - private final int from; - private final int to; - private final K[] x, y; - - public ForkJoinQuickSort2(final K[] x, final K[] y, final int from, - final int to) { - this.from = from; - this.to = to; - this.x = x; - this.y = y; - } - - @Override - @SuppressWarnings("unchecked") - protected void compute() { - final K[] x = this.x; - final K[] y = this.y; - final int len = to - from; - if (len < PARALLEL_QUICKSORT_NO_FORK) { - quickSort(x, y, from, to); - return; - } - // Choose a partition element, v - int m = from + len / 2; - int l = from; - int n = to - 1; - int s = len / 8; - l = med3(x, y, l, l + s, l + 2 * s); - m = med3(x, y, m - s, m, m + s); - n = med3(x, y, n - 2 * s, n - s, n); - m = med3(x, y, l, m, n); - final K v = x[m], w = y[m]; - // Establish Invariant: v* (v)* v* - int a = from, b = a, c = to - 1, d = c; - while (true) { - int comparison, t; - while (b <= c - && (comparison = (t = (((Comparable) (x[b])) - .compareTo(v))) == 0 - ? (((Comparable) (y[b])).compareTo(w)) - : t) <= 0) { - if (comparison == 0) - swap(x, y, a++, b); - b++; - } - while (c >= b - && (comparison = (t = (((Comparable) (x[c])) - .compareTo(v))) == 0 - ? (((Comparable) (y[c])).compareTo(w)) - : t) >= 0) { - if (comparison == 0) - swap(x, y, c, d--); - c--; - } - if (b > c) - break; - swap(x, y, b++, c--); - } - // Swap partition elements back to middle - int t; - s = Math.min(a - from, b - a); - swap(x, y, from, b - s, s); - s = Math.min(d - c, to - d - 1); - swap(x, y, b, to - s, s); - s = b - a; - t = d - c; - // Recursively sort non-partition-elements - if (s > 1 && t > 1) - invokeAll(new ForkJoinQuickSort2(x, y, from, from + s), - new ForkJoinQuickSort2(x, y, to - t, to)); - else if (s > 1) - invokeAll(new ForkJoinQuickSort2(x, y, from, from + s)); - else - invokeAll(new ForkJoinQuickSort2(x, y, to - t, to)); - } - } - - /** - * Sorts the specified range of elements of two arrays according to the - * natural lexicographical ascending order using a parallel quicksort. - * - *

- * The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley - * and M. Douglas McIlroy, “Engineering a Sort Function”, - * Software: Practice and Experience, 23(11), pages 1249−1265, - * 1993. - * - *

- * This method implements a lexicographical sorting of the - * arguments. Pairs of elements in the same position in the two provided - * arrays will be considered a single key, and permuted accordingly. In the - * end, either x[ i ] < x[ i + 1 ] or x[ i ] - * == x[ i + 1 ] and y[ i ] ≤ y[ i + 1 ]. - * - *

- * This implementation uses a {@link ForkJoinPool} executor service with - * {@link Runtime#availableProcessors()} parallel threads. - * - * @param x - * the first array to be sorted. - * @param y - * the second array to be sorted. - * @param from - * the index of the first element (inclusive) to be sorted. - * @param to - * the index of the last element (exclusive) to be sorted. - */ - public static void parallelQuickSort(final K[] x, final K[] y, - final int from, final int to) { - if (to - from < PARALLEL_QUICKSORT_NO_FORK) - quickSort(x, y, from, to); - final ForkJoinPool pool = new ForkJoinPool(Runtime.getRuntime() - .availableProcessors()); - pool.invoke(new ForkJoinQuickSort2(x, y, from, to)); - pool.shutdown(); - } - - /** - * Sorts two arrays according to the natural lexicographical ascending order - * using a parallel quicksort. - * - *

- * The sorting algorithm is a tuned quicksort adapted from Jon L. Bentley - * and M. Douglas McIlroy, “Engineering a Sort Function”, - * Software: Practice and Experience, 23(11), pages 1249−1265, - * 1993. - * - *

- * This method implements a lexicographical sorting of the - * arguments. Pairs of elements in the same position in the two provided - * arrays will be considered a single key, and permuted accordingly. In the - * end, either x[ i ] < x[ i + 1 ] or x[ i ] - * == x[ i + 1 ] and y[ i ] ≤ y[ i + 1 ]. - * - *

- * This implementation uses a {@link ForkJoinPool} executor service with - * {@link Runtime#availableProcessors()} parallel threads. - * - * @param x - * the first array to be sorted. - * @param y - * the second array to be sorted. - */ - public static void parallelQuickSort(final K[] x, final K[] y) { - ensureSameLength(x, y); - parallelQuickSort(x, y, 0, x.length); - } - - /** - * Sorts the specified range of elements according to the natural ascending - * order using mergesort, using a given pre-filled support array. - * - *

- * This sort is guaranteed to be stable: equal elements will not be - * reordered as a result of the sort. Moreover, no support arrays will be - * allocated. - * - * @param a - * the array to be sorted. - * @param from - * the index of the first element (inclusive) to be sorted. - * @param to - * the index of the last element (exclusive) to be sorted. - * @param supp - * a support array containing at least to elements, - * and whose entries are identical to those of {@code a} in the - * specified range. - */ - - @SuppressWarnings("unchecked") - public static void mergeSort(final K a[], final int from, final int to, - final K supp[]) { - int len = to - from; - - // Insertion sort on smallest arrays - if (len < MERGESORT_NO_REC) { - insertionSort(a, from, to); - return; - } - - // Recursively sort halves of a into supp - final int mid = (from + to) >>> 1; - mergeSort(supp, from, mid, a); - mergeSort(supp, mid, to, a); - - // If list is already sorted, just copy from supp to a. This is an - // optimization that results in faster sorts for nearly ordered lists. - if ((((Comparable) (supp[mid - 1])).compareTo(supp[mid]) <= 0)) { - System.arraycopy(supp, from, a, from, len); - return; - } - - // Merge sorted halves (now in supp) into a - for (int i = from, p = from, q = mid; i < to; i++) { - if (q >= to || p < mid - && (((Comparable) (supp[p])).compareTo(supp[q]) <= 0)) - a[i] = supp[p++]; - else - a[i] = supp[q++]; - } - } - - /** - * Sorts the specified range of elements according to the natural ascending - * order using mergesort. - * - *

- * This sort is guaranteed to be stable: equal elements will not be - * reordered as a result of the sort. An array as large as a - * will be allocated by this method. - * - * @param a - * the array to be sorted. - * @param from - * the index of the first element (inclusive) to be sorted. - * @param to - * the index of the last element (exclusive) to be sorted. - */ - public static void mergeSort(final K a[], final int from, final int to) { - mergeSort(a, from, to, a.clone()); - } - - /** - * Sorts an array according to the natural ascending order using mergesort. - * - *

- * This sort is guaranteed to be stable: equal elements will not be - * reordered as a result of the sort. An array as large as a - * will be allocated by this method. - * - * @param a - * the array to be sorted. - */ - public static void mergeSort(final K a[]) { - mergeSort(a, 0, a.length); - } - - /** - * Sorts the specified range of elements according to the order induced by - * the specified comparator using mergesort, using a given pre-filled - * support array. - * - *

- * This sort is guaranteed to be stable: equal elements will not be - * reordered as a result of the sort. Moreover, no support arrays will be - * allocated. - * - * @param a - * the array to be sorted. - * @param from - * the index of the first element (inclusive) to be sorted. - * @param to - * the index of the last element (exclusive) to be sorted. - * @param comp - * the comparator to determine the sorting order. - * @param supp - * a support array containing at least to elements, - * and whose entries are identical to those of {@code a} in the - * specified range. - */ - public static void mergeSort(final K a[], final int from, final int to, - Comparator comp, final K supp[]) { - int len = to - from; - - // Insertion sort on smallest arrays - if (len < MERGESORT_NO_REC) { - insertionSort(a, from, to, comp); - return; - } - - // Recursively sort halves of a into supp - final int mid = (from + to) >>> 1; - mergeSort(supp, from, mid, comp, a); - mergeSort(supp, mid, to, comp, a); - - // If list is already sorted, just copy from supp to a. This is an - // optimization that results in faster sorts for nearly ordered lists. - if (comp.compare(supp[mid - 1], supp[mid]) <= 0) { - System.arraycopy(supp, from, a, from, len); - return; - } - - // Merge sorted halves (now in supp) into a - for (int i = from, p = from, q = mid; i < to; i++) { - if (q >= to || p < mid && comp.compare(supp[p], supp[q]) <= 0) - a[i] = supp[p++]; - else - a[i] = supp[q++]; - } - } - - /** - * Sorts the specified range of elements according to the order induced by - * the specified comparator using mergesort. - * - *

- * This sort is guaranteed to be stable: equal elements will not be - * reordered as a result of the sort. An array as large as a - * will be allocated by this method. - * - * @param a - * the array to be sorted. - * @param from - * the index of the first element (inclusive) to be sorted. - * @param to - * the index of the last element (exclusive) to be sorted. - * @param comp - * the comparator to determine the sorting order. - */ - public static void mergeSort(final K a[], final int from, final int to, - Comparator comp) { - mergeSort(a, from, to, comp, a.clone()); - } - - /** - * Sorts an array according to the order induced by the specified comparator - * using mergesort. - * - *

- * This sort is guaranteed to be stable: equal elements will not be - * reordered as a result of the sort. An array as large as a - * will be allocated by this method. - * - * @param a - * the array to be sorted. - * @param comp - * the comparator to determine the sorting order. - */ - public static void mergeSort(final K a[], Comparator comp) { - mergeSort(a, 0, a.length, comp); - } - - /** - * Searches a range of the specified array for the specified value using the - * binary search algorithm. The range must be sorted prior to making this - * call. If it is not sorted, the results are undefined. If the range - * contains multiple elements with the specified value, there is no - * guarantee which one will be found. - * - * @param a - * the array to be searched. - * @param from - * the index of the first element (inclusive) to be searched. - * @param to - * the index of the last element (exclusive) to be searched. - * @param key - * the value to be searched for. - * @return index of the search key, if it is contained in the array; - * otherwise, (-(insertion point) - 1). The - * insertion point is defined as the the point at which the - * value would be inserted into the array: the index of the first - * element greater than the key, or the length of the array, if all - * elements in the array are less than the specified key. Note that - * this guarantees that the return value will be ≥ 0 if and only - * if the key is found. - * @see java.util.Arrays - */ - @SuppressWarnings("unchecked") - public static int binarySearch(final K[] a, int from, int to, - final K key) { - K midVal; - to--; - while (from <= to) { - final int mid = (from + to) >>> 1; - midVal = a[mid]; - - final int cmp = ((Comparable) midVal).compareTo(key); - if (cmp < 0) - from = mid + 1; - else if (cmp > 0) - to = mid - 1; - else - return mid; - - } - return -(from + 1); - } - - /** - * Searches an array for the specified value using the binary search - * algorithm. The range must be sorted prior to making this call. If it is - * not sorted, the results are undefined. If the range contains multiple - * elements with the specified value, there is no guarantee which one will - * be found. - * - * @param a - * the array to be searched. - * @param key - * the value to be searched for. - * @return index of the search key, if it is contained in the array; - * otherwise, (-(insertion point) - 1). The - * insertion point is defined as the the point at which the - * value would be inserted into the array: the index of the first - * element greater than the key, or the length of the array, if all - * elements in the array are less than the specified key. Note that - * this guarantees that the return value will be ≥ 0 if and only - * if the key is found. - * @see java.util.Arrays - */ - public static int binarySearch(final K[] a, final K key) { - return binarySearch(a, 0, a.length, key); - } - - /** - * Searches a range of the specified array for the specified value using the - * binary search algorithm and a specified comparator. The range must be - * sorted following the comparator prior to making this call. If it is not - * sorted, the results are undefined. If the range contains multiple - * elements with the specified value, there is no guarantee which one will - * be found. - * - * @param a - * the array to be searched. - * @param from - * the index of the first element (inclusive) to be searched. - * @param to - * the index of the last element (exclusive) to be searched. - * @param key - * the value to be searched for. - * @param c - * a comparator. - * @return index of the search key, if it is contained in the array; - * otherwise, (-(insertion point) - 1). The - * insertion point is defined as the the point at which the - * value would be inserted into the array: the index of the first - * element greater than the key, or the length of the array, if all - * elements in the array are less than the specified key. Note that - * this guarantees that the return value will be ≥ 0 if and only - * if the key is found. - * @see java.util.Arrays - */ - public static int binarySearch(final K[] a, int from, int to, - final K key, final Comparator c) { - K midVal; - to--; - while (from <= to) { - final int mid = (from + to) >>> 1; - midVal = a[mid]; - final int cmp = c.compare(midVal, key); - if (cmp < 0) - from = mid + 1; - else if (cmp > 0) - to = mid - 1; - else - return mid; // key found - } - return -(from + 1); - } - - /** - * Searches an array for the specified value using the binary search - * algorithm and a specified comparator. The range must be sorted following - * the comparator prior to making this call. If it is not sorted, the - * results are undefined. If the range contains multiple elements with the - * specified value, there is no guarantee which one will be found. - * - * @param a - * the array to be searched. - * @param key - * the value to be searched for. - * @param c - * a comparator. - * @return index of the search key, if it is contained in the array; - * otherwise, (-(insertion point) - 1). The - * insertion point is defined as the the point at which the - * value would be inserted into the array: the index of the first - * element greater than the key, or the length of the array, if all - * elements in the array are less than the specified key. Note that - * this guarantees that the return value will be ≥ 0 if and only - * if the key is found. - * @see java.util.Arrays - */ - public static int binarySearch(final K[] a, final K key, - final Comparator c) { - return binarySearch(a, 0, a.length, key, c); - } - /** - * Shuffles the specified array fragment using the specified pseudorandom - * number generator. - * - * @param a - * the array to be shuffled. - * @param from - * the index of the first element (inclusive) to be shuffled. - * @param to - * the index of the last element (exclusive) to be shuffled. - * @param random - * a pseudorandom number generator (please use a XorShift* generator). - * @return a. - */ - public static K[] shuffle(final K[] a, final int from, final int to, - final Random random) { - for (int i = to - from; i-- != 0;) { - final int p = random.nextInt(i + 1); - final K t = a[from + i]; - a[from + i] = a[from + p]; - a[from + p] = t; - } - return a; - } - - /** - * Shuffles the specified array using the specified pseudorandom number - * generator. - * - * @param a - * the array to be shuffled. - * @param random - * a pseudorandom number generator (please use a XorShift* generator). - * @return a. - */ - public static K[] shuffle(final K[] a, final Random random) { - for (int i = a.length; i-- != 0;) { - final int p = random.nextInt(i + 1); - final K t = a[i]; - a[i] = a[p]; - a[p] = t; - } - return a; - } - - /** - * Reverses the order of the elements in the specified array. - * - * @param a - * the array to be reversed. - * @return a. - */ - public static K[] reverse(final K[] a) { - final int length = a.length; - for (int i = length / 2; i-- != 0;) { - final K t = a[length - i - 1]; - a[length - i - 1] = a[i]; - a[i] = t; - } - return a; - } - - /** - * Reverses the order of the elements in the specified array fragment. - * - * @param a - * the array to be reversed. - * @param from - * the index of the first element (inclusive) to be reversed. - * @param to - * the index of the last element (exclusive) to be reversed. - * @return a. - */ - public static K[] reverse(final K[] a, final int from, final int to) { - final int length = to - from; - for (int i = length / 2; i-- != 0;) { - final K t = a[from + length - i - 1]; - a[from + length - i - 1] = a[from + i]; - a[from + i] = t; - } - return a; - } - - /** A type-specific content-based hash strategy for arrays. */ - - private static final class ArrayHashStrategy - implements - Hash.Strategy, - java.io.Serializable { - private static final long serialVersionUID = -7046029254386353129L; - - public int hashCode(final K[] o) { - return java.util.Arrays.hashCode(o); - } - - public boolean equals(final K[] a, final K[] b) { - return java.util.Arrays.equals(a, b); - } - } - - /** - * A type-specific content-based hash strategy for arrays. - * - *

- * This hash strategy may be used in custom hash collections whenever keys - * are arrays, and they must be considered equal by content. This strategy - * will handle null correctly, and it is serializable. - */ - - @SuppressWarnings({"rawtypes"}) - public final static Hash.Strategy HASH_STRATEGY = new ArrayHashStrategy(); - -} diff --git a/src/main/java/it/unimi/dsi/fastutil/objects/ObjectBidirectionalIterator.java b/src/main/java/it/unimi/dsi/fastutil/objects/ObjectBidirectionalIterator.java deleted file mode 100644 index f9ad1bc..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/objects/ObjectBidirectionalIterator.java +++ /dev/null @@ -1,77 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.objects; - -import it.unimi.dsi.fastutil.BidirectionalIterator; -import it.unimi.dsi.fastutil.objects.ObjectIterator; - -/** - * A type-specific bidirectional iterator; provides an additional method to - * avoid (un)boxing, and the possibility to skip elements backwards. - * - * @see BidirectionalIterator - */ - -public interface ObjectBidirectionalIterator - extends - ObjectIterator, - BidirectionalIterator { - /** - * Moves back for the given number of elements. - * - *

- * The effect of this call is exactly the same as that of calling - * {@link #previous()} for n times (possibly stopping if - * {@link #hasPrevious()} becomes false). - * - * @param n - * the number of elements to skip back. - * @return the number of elements actually skipped. - * @see java.util.Iterator#next() - */ - - int back(int n); -} diff --git a/src/main/java/it/unimi/dsi/fastutil/objects/ObjectCollection.java b/src/main/java/it/unimi/dsi/fastutil/objects/ObjectCollection.java deleted file mode 100644 index 2cf8cfe..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/objects/ObjectCollection.java +++ /dev/null @@ -1,106 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.objects; - -import it.unimi.dsi.fastutil.objects.ObjectIterable; -import it.unimi.dsi.fastutil.objects.ObjectIterator; - -import java.util.Collection; - -/** - * A type-specific {@link Collection}; provides some additional methods that use - * polymorphism to avoid (un)boxing. - * - *

- * Additionally, this class defines strengthens (again) {@link #iterator()} and - * defines a slightly different semantics for {@link #toArray(Object[])}. - * - * @see Collection - */ - -public interface ObjectCollection extends Collection, ObjectIterable { - - /** - * Returns a type-specific iterator on the elements of this collection. - * - *

- * Note that this specification strengthens the one given in - * {@link Iterable#iterator()}, which was already strengthened in - * the corresponding type-specific class, but was weakened by the fact that - * this interface extends {@link Collection}. - * - * @return a type-specific iterator on the elements of this collection. - */ - ObjectIterator iterator(); - - /** - * Returns a type-specific iterator on this elements of this collection. - * - * @see #iterator() - * @deprecated As of fastutil 5, replaced by - * {@link #iterator()}. - */ - @Deprecated - ObjectIterator objectIterator(); - - /** - * Returns an containing the items of this collection; the runtime type of - * the returned array is that of the specified array. - * - *

- * Warning: Note that, contrarily to - * {@link Collection#toArray(Object[])}, this methods just writes all - * elements of this collection: no special value will be added after the - * last one. - * - * @param a - * if this array is big enough, it will be used to store this - * collection. - * @return a primitive type array containing the items of this collection. - * @see Collection#toArray(Object[]) - */ - T[] toArray(T[] a); -} diff --git a/src/main/java/it/unimi/dsi/fastutil/objects/ObjectIterable.java b/src/main/java/it/unimi/dsi/fastutil/objects/ObjectIterable.java deleted file mode 100644 index e943bab..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/objects/ObjectIterable.java +++ /dev/null @@ -1,75 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.objects; - -import it.unimi.dsi.fastutil.objects.ObjectIterator; - -/** - * A type-specific {@link Iterable} that strengthens that specification of - * {@link Iterable#iterator()}. - * - *

- * Warning: Java will let you write “colon” - * for statements with primitive-type loop variables; however, what - * is (unfortunately) really happening is that at each iteration an unboxing - * (and, in the case of fastutil type-specific data structures, a - * boxing) will be performed. Watch out. - * - * @see Iterable - */ - -public interface ObjectIterable extends Iterable { - - /** - * Returns a type-specific iterator. - * - * Note that this specification strengthens the one given in - * {@link Iterable#iterator()}. - * - * @return a type-specific iterator. - */ - ObjectIterator iterator(); -} diff --git a/src/main/java/it/unimi/dsi/fastutil/objects/ObjectIterator.java b/src/main/java/it/unimi/dsi/fastutil/objects/ObjectIterator.java deleted file mode 100644 index bb12e1f..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/objects/ObjectIterator.java +++ /dev/null @@ -1,73 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.objects; - -import java.util.Iterator; - -/** - * A type-specific {@link Iterator}; provides an additional method to avoid - * (un)boxing, and the possibility to skip elements. - * - * @see Iterator - */ - -public interface ObjectIterator extends Iterator { - /** - * Skips the given number of elements. - * - *

- * The effect of this call is exactly the same as that of calling - * {@link #next()} for n times (possibly stopping if - * {@link #hasNext()} becomes false). - * - * @param n - * the number of elements to skip. - * @return the number of elements actually skipped. - * @see Iterator#next() - */ - - int skip(int n); -} diff --git a/src/main/java/it/unimi/dsi/fastutil/objects/ObjectIterators.java b/src/main/java/it/unimi/dsi/fastutil/objects/ObjectIterators.java deleted file mode 100644 index c974e3c..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/objects/ObjectIterators.java +++ /dev/null @@ -1,881 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.objects; - -import it.unimi.dsi.fastutil.objects.AbstractObjectBidirectionalIterator; -import it.unimi.dsi.fastutil.objects.AbstractObjectIterator; -import it.unimi.dsi.fastutil.objects.AbstractObjectListIterator; -import it.unimi.dsi.fastutil.objects.ObjectArrayList; -import it.unimi.dsi.fastutil.objects.ObjectArrays; -import it.unimi.dsi.fastutil.objects.ObjectBidirectionalIterator; -import it.unimi.dsi.fastutil.objects.ObjectCollection; -import it.unimi.dsi.fastutil.objects.ObjectIterator; -import it.unimi.dsi.fastutil.objects.ObjectList; -import it.unimi.dsi.fastutil.objects.ObjectListIterator; - -import java.util.Iterator; -import java.util.ListIterator; -import java.util.NoSuchElementException; - -/** - * A class providing static methods and objects that do useful things with - * type-specific iterators. - * - * @see Iterator - */ - -public class ObjectIterators { - - private ObjectIterators() { - } - - /** - * A class returning no elements and a type-specific iterator interface. - * - *

- * This class may be useful to implement your own in case you subclass a - * type-specific iterator. - */ - - public static class EmptyIterator extends AbstractObjectListIterator - implements - java.io.Serializable, - Cloneable { - - private static final long serialVersionUID = -7046029254386353129L; - - protected EmptyIterator() { - } - - public boolean hasNext() { - return false; - } - public boolean hasPrevious() { - return false; - } - public K next() { - throw new NoSuchElementException(); - } - public K previous() { - throw new NoSuchElementException(); - } - public int nextIndex() { - return 0; - } - public int previousIndex() { - return -1; - } - public int skip(int n) { - return 0; - }; - public int back(int n) { - return 0; - }; - public Object clone() { - return EMPTY_ITERATOR; - } - private Object readResolve() { - return EMPTY_ITERATOR; - } - } - - /** - * An empty iterator (immutable). It is serializable and cloneable. - * - *

- * The class of this objects represent an abstract empty iterator that can - * iterate as a type-specific (list) iterator. - */ - - @SuppressWarnings("rawtypes") - public final static EmptyIterator EMPTY_ITERATOR = new EmptyIterator(); - - /** An iterator returning a single element. */ - - private static class SingletonIterator - extends - AbstractObjectListIterator { - private final K element; - private int curr; - - public SingletonIterator(final K element) { - this.element = element; - } - - public boolean hasNext() { - return curr == 0; - } - public boolean hasPrevious() { - return curr == 1; - } - - public K next() { - if (!hasNext()) - throw new NoSuchElementException(); - curr = 1; - return element; - } - - public K previous() { - if (!hasPrevious()) - throw new NoSuchElementException(); - curr = 0; - return element; - } - - public int nextIndex() { - return curr; - } - - public int previousIndex() { - return curr - 1; - } - } - - /** - * Returns an iterator that iterates just over the given element. - * - * @param element - * the only element to be returned by a type-specific list - * iterator. - * @return an iterator that iterates just over element. - */ - public static ObjectListIterator singleton(final K element) { - return new SingletonIterator(element); - } - - /** A class to wrap arrays in iterators. */ - - private static class ArrayIterator extends AbstractObjectListIterator { - private final K[] array; - private final int offset, length; - private int curr; - - public ArrayIterator(final K[] array, final int offset, final int length) { - this.array = array; - this.offset = offset; - this.length = length; - } - - public boolean hasNext() { - return curr < length; - } - public boolean hasPrevious() { - return curr > 0; - } - - public K next() { - if (!hasNext()) - throw new NoSuchElementException(); - return array[offset + curr++]; - } - - public K previous() { - if (!hasPrevious()) - throw new NoSuchElementException(); - return array[offset + --curr]; - } - - public int skip(int n) { - if (n <= length - curr) { - curr += n; - return n; - } - n = length - curr; - curr = length; - return n; - } - - public int back(int n) { - if (n <= curr) { - curr -= n; - return n; - } - n = curr; - curr = 0; - return n; - } - - public int nextIndex() { - return curr; - } - - public int previousIndex() { - return curr - 1; - } - } - - /** - * Wraps the given part of an array into a type-specific list iterator. - * - *

- * The type-specific list iterator returned by this method will iterate - * length times, returning consecutive elements of the given - * array starting from the one with index offset. - * - * @param array - * an array to wrap into a type-specific list iterator. - * @param offset - * the first element of the array to be returned. - * @param length - * the number of elements to return. - * @return an iterator that will return length elements of - * array starting at position offset. - */ - public static ObjectListIterator wrap(final K[] array, - final int offset, final int length) { - ObjectArrays.ensureOffsetLength(array, offset, length); - return new ArrayIterator(array, offset, length); - } - - /** - * Wraps the given array into a type-specific list iterator. - * - *

- * The type-specific list iterator returned by this method will return all - * elements of the given array. - * - * @param array - * an array to wrap into a type-specific list iterator. - * @return an iterator that will the elements of array. - */ - public static ObjectListIterator wrap(final K[] array) { - return new ArrayIterator(array, 0, array.length); - } - - /** - * Unwraps an iterator into an array starting at a given offset for a given - * number of elements. - * - *

- * This method iterates over the given type-specific iterator and stores the - * elements returned, up to a maximum of length, in the given - * array starting at offset. The number of actually unwrapped - * elements is returned (it may be less than max if the - * iterator emits less than max elements). - * - * @param i - * a type-specific iterator. - * @param array - * an array to contain the output of the iterator. - * @param offset - * the first element of the array to be returned. - * @param max - * the maximum number of elements to unwrap. - * @return the number of elements unwrapped. - */ - public static int unwrap(final Iterator i, - final K array[], int offset, final int max) { - if (max < 0) - throw new IllegalArgumentException( - "The maximum number of elements (" + max + ") is negative"); - if (offset < 0 || offset + max > array.length) - throw new IllegalArgumentException(); - int j = max; - while (j-- != 0 && i.hasNext()) - array[offset++] = i.next(); - return max - j - 1; - } - - /** - * Unwraps an iterator into an array. - * - *

- * This method iterates over the given type-specific iterator and stores the - * elements returned in the given array. The iteration will stop when the - * iterator has no more elements or when the end of the array has been - * reached. - * - * @param i - * a type-specific iterator. - * @param array - * an array to contain the output of the iterator. - * @return the number of elements unwrapped. - */ - public static int unwrap(final Iterator i, final K array[]) { - return unwrap(i, array, 0, array.length); - } - - /** - * Unwraps an iterator, returning an array, with a limit on the number of - * elements. - * - *

- * This method iterates over the given type-specific iterator and returns an - * array containing the elements returned by the iterator. At most - * max elements will be returned. - * - * @param i - * a type-specific iterator. - * @param max - * the maximum number of elements to be unwrapped. - * @return an array containing the elements returned by the iterator (at - * most max). - */ - @SuppressWarnings("unchecked") - public static K[] unwrap(final Iterator i, int max) { - if (max < 0) - throw new IllegalArgumentException( - "The maximum number of elements (" + max + ") is negative"); - K array[] = (K[]) new Object[16]; - int j = 0; - - while (max-- != 0 && i.hasNext()) { - if (j == array.length) - array = ObjectArrays.grow(array, j + 1); - array[j++] = i.next(); - } - - return ObjectArrays.trim(array, j); - } - - /** - * Unwraps an iterator, returning an array. - * - *

- * This method iterates over the given type-specific iterator and returns an - * array containing the elements returned by the iterator. - * - * @param i - * a type-specific iterator. - * @return an array containing the elements returned by the iterator. - */ - - public static K[] unwrap(final Iterator i) { - return unwrap(i, Integer.MAX_VALUE); - } - - /** - * Unwraps an iterator into a type-specific collection, with a limit on the - * number of elements. - * - *

- * This method iterates over the given type-specific iterator and stores the - * elements returned, up to a maximum of max, in the given - * type-specific collection. The number of actually unwrapped elements is - * returned (it may be less than max if the iterator emits less - * than max elements). - * - * @param i - * a type-specific iterator. - * @param c - * a type-specific collection array to contain the output of the - * iterator. - * @param max - * the maximum number of elements to unwrap. - * @return the number of elements unwrapped. Note that this is the number of - * elements returned by the iterator, which is not necessarily the - * number of elements that have been added to the collection - * (because of duplicates). - */ - public static int unwrap(final Iterator i, - final ObjectCollection c, final int max) { - if (max < 0) - throw new IllegalArgumentException( - "The maximum number of elements (" + max + ") is negative"); - int j = max; - while (j-- != 0 && i.hasNext()) - c.add(i.next()); - return max - j - 1; - } - - /** - * Unwraps an iterator into a type-specific collection. - * - *

- * This method iterates over the given type-specific iterator and stores the - * elements returned in the given type-specific collection. The returned - * count on the number unwrapped elements is a long, so that it will work - * also with very large collections. - * - * @param i - * a type-specific iterator. - * @param c - * a type-specific collection to contain the output of the - * iterator. - * @return the number of elements unwrapped. Note that this is the number of - * elements returned by the iterator, which is not necessarily the - * number of elements that have been added to the collection - * (because of duplicates). - */ - public static long unwrap(final Iterator i, - final ObjectCollection c) { - long n = 0; - while (i.hasNext()) { - c.add(i.next()); - n++; - } - return n; - } - - /** - * Pours an iterator into a type-specific collection, with a limit on the - * number of elements. - * - *

- * This method iterates over the given type-specific iterator and adds the - * returned elements to the given collection (up to max). - * - * @param i - * a type-specific iterator. - * @param s - * a type-specific collection. - * @param max - * the maximum number of elements to be poured. - * @return the number of elements poured. Note that this is the number of - * elements returned by the iterator, which is not necessarily the - * number of elements that have been added to the collection - * (because of duplicates). - */ - - public static int pour(final Iterator i, - final ObjectCollection s, final int max) { - if (max < 0) - throw new IllegalArgumentException( - "The maximum number of elements (" + max + ") is negative"); - int j = max; - while (j-- != 0 && i.hasNext()) - s.add(i.next()); - return max - j - 1; - } - - /** - * Pours an iterator into a type-specific collection. - * - *

- * This method iterates over the given type-specific iterator and adds the - * returned elements to the given collection. - * - * @param i - * a type-specific iterator. - * @param s - * a type-specific collection. - * @return the number of elements poured. Note that this is the number of - * elements returned by the iterator, which is not necessarily the - * number of elements that have been added to the collection - * (because of duplicates). - */ - - public static int pour(final Iterator i, - final ObjectCollection s) { - return pour(i, s, Integer.MAX_VALUE); - } - - /** - * Pours an iterator, returning a type-specific list, with a limit on the - * number of elements. - * - *

- * This method iterates over the given type-specific iterator and returns a - * type-specific list containing the returned elements (up to - * max). Iteration on the returned list is guaranteed to - * produce the elements in the same order in which they appeared in the - * iterator. - * - * - * @param i - * a type-specific iterator. - * @param max - * the maximum number of elements to be poured. - * @return a type-specific list containing the returned elements, up to - * max. - */ - - public static ObjectList pour(final Iterator i, int max) { - final ObjectArrayList l = new ObjectArrayList(); - pour(i, l, max); - l.trim(); - return l; - } - - /** - * Pours an iterator, returning a type-specific list. - * - *

- * This method iterates over the given type-specific iterator and returns a - * list containing the returned elements. Iteration on the returned list is - * guaranteed to produce the elements in the same order in which they - * appeared in the iterator. - * - * @param i - * a type-specific iterator. - * @return a type-specific list containing the returned elements. - */ - - public static ObjectList pour(final Iterator i) { - return pour(i, Integer.MAX_VALUE); - } - - private static class IteratorWrapper extends AbstractObjectIterator { - final Iterator i; - - public IteratorWrapper(final Iterator i) { - this.i = i; - } - - public boolean hasNext() { - return i.hasNext(); - } - public void remove() { - i.remove(); - } - - public K next() { - return (i.next()); - } - } - - /** - * Wraps a standard iterator into a type-specific iterator. - * - *

- * This method wraps a standard iterator into a type-specific one which will - * handle the type conversions for you. Of course, any attempt to wrap an - * iterator returning the instances of the wrong class will generate a - * {@link ClassCastException}. The returned iterator is backed by - * i: changes to one of the iterators will affect the other, - * too. - * - *

- * If i is already type-specific, it will returned and no new - * object will be generated. - * - * @param i - * an iterator. - * @return a type-specific iterator backed by i. - */ - - public static ObjectIterator asObjectIterator(final Iterator i) { - if (i instanceof ObjectIterator) - return (ObjectIterator) i; - return new IteratorWrapper(i); - } - - private static class ListIteratorWrapper - extends - AbstractObjectListIterator { - final ListIterator i; - - public ListIteratorWrapper(final ListIterator i) { - this.i = i; - } - - public boolean hasNext() { - return i.hasNext(); - } - public boolean hasPrevious() { - return i.hasPrevious(); - } - public int nextIndex() { - return i.nextIndex(); - } - public int previousIndex() { - return i.previousIndex(); - } - public void set(K k) { - i.set((k)); - } - public void add(K k) { - i.add((k)); - } - public void remove() { - i.remove(); - } - - public K next() { - return (i.next()); - } - public K previous() { - return (i.previous()); - } - } - - /** - * Wraps a standard list iterator into a type-specific list iterator. - * - *

- * This method wraps a standard list iterator into a type-specific one which - * will handle the type conversions for you. Of course, any attempt to wrap - * an iterator returning the instances of the wrong class will generate a - * {@link ClassCastException}. The returned iterator is backed by - * i: changes to one of the iterators will affect the other, - * too. - * - *

- * If i is already type-specific, it will returned and no new - * object will be generated. - * - * @param i - * a list iterator. - * @return a type-specific list iterator backed by i. - */ - - public static ObjectListIterator asObjectIterator( - final ListIterator i) { - if (i instanceof ObjectListIterator) - return (ObjectListIterator) i; - return new ListIteratorWrapper(i); - } - private static class IteratorConcatenator - extends - AbstractObjectIterator { - final ObjectIterator a[]; - int offset, length, lastOffset = -1; - - public IteratorConcatenator(final ObjectIterator a[], - int offset, int length) { - this.a = a; - this.offset = offset; - this.length = length; - advance(); - } - - private void advance() { - while (length != 0) { - if (a[offset].hasNext()) - break; - length--; - offset++; - } - - return; - } - - public boolean hasNext() { - return length > 0; - } - - public K next() { - if (!hasNext()) - throw new NoSuchElementException(); - K next = a[lastOffset = offset].next(); - advance(); - return next; - } - - public void remove() { - if (lastOffset == -1) - throw new IllegalStateException(); - a[lastOffset].remove(); - } - - public int skip(int n) { - lastOffset = -1; - - int skipped = 0; - - while (skipped < n && length != 0) { - skipped += a[offset].skip(n - skipped); - if (a[offset].hasNext()) - break; - length--; - offset++; - } - - return skipped; - } - - } - - /** - * Concatenates all iterators contained in an array. - * - *

- * This method returns an iterator that will enumerate in order the elements - * returned by all iterators contained in the given array. - * - * @param a - * an array of iterators. - * @return an iterator obtained by concatenation. - */ - - public static ObjectIterator concat( - final ObjectIterator a[]) { - return concat(a, 0, a.length); - } - - /** - * Concatenates a sequence of iterators contained in an array. - * - *

- * This method returns an iterator that will enumerate in order the elements - * returned by a[ offset ], then those returned by - * a[ offset + 1 ], and so on up to - * a[ offset + length - 1 ]. - * - * @param a - * an array of iterators. - * @param offset - * the index of the first iterator to concatenate. - * @param length - * the number of iterators to concatenate. - * @return an iterator obtained by concatenation of length - * elements of a starting at offset. - */ - - public static ObjectIterator concat( - final ObjectIterator a[], final int offset, - final int length) { - return new IteratorConcatenator(a, offset, length); - } - - /** An unmodifiable wrapper class for iterators. */ - - public static class UnmodifiableIterator - extends - AbstractObjectIterator { - final protected ObjectIterator i; - - public UnmodifiableIterator(final ObjectIterator i) { - this.i = i; - } - - public boolean hasNext() { - return i.hasNext(); - } - - public K next() { - return i.next(); - } - - } - - /** - * Returns an unmodifiable iterator backed by the specified iterator. - * - * @param i - * the iterator to be wrapped in an unmodifiable iterator. - * @return an unmodifiable view of the specified iterator. - */ - public static ObjectIterator unmodifiable(final ObjectIterator i) { - return new UnmodifiableIterator(i); - } - - /** An unmodifiable wrapper class for bidirectional iterators. */ - - public static class UnmodifiableBidirectionalIterator - extends - AbstractObjectBidirectionalIterator { - final protected ObjectBidirectionalIterator i; - - public UnmodifiableBidirectionalIterator( - final ObjectBidirectionalIterator i) { - this.i = i; - } - - public boolean hasNext() { - return i.hasNext(); - } - public boolean hasPrevious() { - return i.hasPrevious(); - } - public K next() { - return i.next(); - } - public K previous() { - return i.previous(); - } - } - - /** - * Returns an unmodifiable bidirectional iterator backed by the specified - * bidirectional iterator. - * - * @param i - * the bidirectional iterator to be wrapped in an unmodifiable - * bidirectional iterator. - * @return an unmodifiable view of the specified bidirectional iterator. - */ - public static ObjectBidirectionalIterator unmodifiable( - final ObjectBidirectionalIterator i) { - return new UnmodifiableBidirectionalIterator(i); - } - - /** An unmodifiable wrapper class for list iterators. */ - - public static class UnmodifiableListIterator - extends - AbstractObjectListIterator { - final protected ObjectListIterator i; - - public UnmodifiableListIterator(final ObjectListIterator i) { - this.i = i; - } - - public boolean hasNext() { - return i.hasNext(); - } - public boolean hasPrevious() { - return i.hasPrevious(); - } - public K next() { - return i.next(); - } - public K previous() { - return i.previous(); - } - public int nextIndex() { - return i.nextIndex(); - } - public int previousIndex() { - return i.previousIndex(); - } - } - - /** - * Returns an unmodifiable list iterator backed by the specified list - * iterator. - * - * @param i - * the list iterator to be wrapped in an unmodifiable list - * iterator. - * @return an unmodifiable view of the specified list iterator. - */ - public static ObjectListIterator unmodifiable( - final ObjectListIterator i) { - return new UnmodifiableListIterator(i); - } -} diff --git a/src/main/java/it/unimi/dsi/fastutil/objects/ObjectList.java b/src/main/java/it/unimi/dsi/fastutil/objects/ObjectList.java deleted file mode 100644 index 96a5d7c..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/objects/ObjectList.java +++ /dev/null @@ -1,217 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.objects; - -import it.unimi.dsi.fastutil.objects.ObjectCollection; -import it.unimi.dsi.fastutil.objects.ObjectListIterator; - -import java.util.List; - -/** - * A type-specific {@link List}; provides some additional methods that use - * polymorphism to avoid (un)boxing. - * - *

- * Note that this type-specific interface extends {@link Comparable}: it is - * expected that implementing classes perform a lexicographical comparison using - * the standard operator "less then" for primitive types, and the usual - * {@link Comparable#compareTo(Object) compareTo()} method for objects. - * - *

- * Additionally, this interface strengthens {@link #listIterator()}, - * {@link #listIterator(int)} and {@link #subList(int,int)}. - * - *

- * Besides polymorphic methods, this interfaces specifies methods to copy into - * an array or remove contiguous sublists. Although the abstract implementation - * of this interface provides simple, one-by-one implementations of these - * methods, it is expected that concrete implementation override them with - * optimized versions. - * - * @see List - */ - -public interface ObjectList - extends - List, - Comparable>, - ObjectCollection { - /** - * Returns a type-specific iterator on the elements of this list (in proper - * sequence). - * - * Note that this specification strengthens the one given in - * {@link List#iterator()}. It would not be normally necessary, but - * {@link Iterable#iterator()} is bizarrily re-specified in - * {@link List}. - * - * @return an iterator on the elements of this list (in proper sequence). - */ - ObjectListIterator iterator(); - - /** - * Returns a type-specific list iterator on the list. - * - * @see #listIterator() - * @deprecated As of fastutil 5, replaced by - * {@link #listIterator()}. - */ - @Deprecated - ObjectListIterator objectListIterator(); - - /** - * Returns a type-specific list iterator on the list starting at a given - * index. - * - * @see #listIterator(int) - * @deprecated As of fastutil 5, replaced by - * {@link #listIterator(int)}. - */ - @Deprecated - ObjectListIterator objectListIterator(int index); - - /** - * Returns a type-specific list iterator on the list. - * - * @see List#listIterator() - */ - ObjectListIterator listIterator(); - - /** - * Returns a type-specific list iterator on the list starting at a given - * index. - * - * @see List#listIterator(int) - */ - ObjectListIterator listIterator(int index); - - /** - * Returns a type-specific view of the portion of this list from the index - * from, inclusive, to the index to, exclusive. - * - * @see List#subList(int,int) - * @deprecated As of fastutil 5, replaced by - * {@link #subList(int,int)}. - */ - @Deprecated - it.unimi.dsi.fastutil.objects.ObjectList objectSubList(int from, int to); - - /** - * Returns a type-specific view of the portion of this list from the index - * from, inclusive, to the index to, exclusive. - * - *

- * Note that this specification strengthens the one given in - * {@link List#subList(int,int)}. - * - * @see List#subList(int,int) - */ - it.unimi.dsi.fastutil.objects.ObjectList subList(int from, int to); - - /** - * Sets the size of this list. - * - *

- * If the specified size is smaller than the current size, the last elements - * are discarded. Otherwise, they are filled with 0/null/ - * false. - * - * @param size - * the new size. - */ - - void size(int size); - - /** - * Copies (hopefully quickly) elements of this type-specific list into the - * given array. - * - * @param from - * the start index (inclusive). - * @param a - * the destination array. - * @param offset - * the offset into the destination array where to store the first - * element copied. - * @param length - * the number of elements to be copied. - */ - void getElements(int from, Object a[], int offset, int length); - - /** - * Removes (hopefully quickly) elements of this type-specific list. - * - * @param from - * the start index (inclusive). - * @param to - * the end index (exclusive). - */ - void removeElements(int from, int to); - - /** - * Add (hopefully quickly) elements to this type-specific list. - * - * @param index - * the index at which to add elements. - * @param a - * the array containing the elements. - */ - void addElements(int index, K a[]); - - /** - * Add (hopefully quickly) elements to this type-specific list. - * - * @param index - * the index at which to add elements. - * @param a - * the array containing the elements. - * @param offset - * the offset of the first element to add. - * @param length - * the number of elements to add. - */ - void addElements(int index, K a[], int offset, int length); -} diff --git a/src/main/java/it/unimi/dsi/fastutil/objects/ObjectListIterator.java b/src/main/java/it/unimi/dsi/fastutil/objects/ObjectListIterator.java deleted file mode 100644 index 859d6a1..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/objects/ObjectListIterator.java +++ /dev/null @@ -1,71 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.objects; - -import it.unimi.dsi.fastutil.objects.ObjectBidirectionalIterator; - -import java.util.ListIterator; - -/** - * A type-specific bidirectional iterator that is also a {@link ListIterator}. - * - *

- * This interface merges the methods provided by a {@link ListIterator} and a - * type-specific {@link it.unimi.dsi.fastutil.BidirectionalIterator}. Moreover, - * it provides type-specific versions of - * {@link ListIterator#add(Object) add()} and - * {@link ListIterator#set(Object) set()}. - * - * @see ListIterator - * @see it.unimi.dsi.fastutil.BidirectionalIterator - */ - -public interface ObjectListIterator - extends - ListIterator, - ObjectBidirectionalIterator { - -} diff --git a/src/main/java/it/unimi/dsi/fastutil/objects/ObjectSet.java b/src/main/java/it/unimi/dsi/fastutil/objects/ObjectSet.java deleted file mode 100644 index 53050a6..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/objects/ObjectSet.java +++ /dev/null @@ -1,90 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.objects; - -import it.unimi.dsi.fastutil.objects.ObjectCollection; -import it.unimi.dsi.fastutil.objects.ObjectIterator; - -import java.util.Set; - -/** - * A type-specific {@link Set}; provides some additional methods that use - * polymorphism to avoid (un)boxing. - * - *

- * Additionally, this interface strengthens (again) {@link #iterator()}. - * - * @see Set - */ - -public interface ObjectSet extends ObjectCollection, Set { - - /** - * Returns a type-specific iterator on the elements of this set. - * - *

- * Note that this specification strengthens the one given in - * {@link Iterable#iterator()}, which was already strengthened in - * the corresponding type-specific class, but was weakened by the fact that - * this interface extends {@link Set}. - * - * @return a type-specific iterator on the elements of this set. - */ - ObjectIterator iterator(); - - /** - * Removes an element from this set. - * - *

- * Note that the corresponding method of the type-specific collection is - * rem(). This unfortunate situation is caused by the clash - * with the similarly named index-based method in the {@link java.util.List} - * interface. - * - * @see java.util.Collection#remove(Object) - */ - public boolean remove(Object k); -} diff --git a/src/main/java/it/unimi/dsi/fastutil/shorts/ShortIterator.java b/src/main/java/it/unimi/dsi/fastutil/shorts/ShortIterator.java deleted file mode 100644 index 330e73a..0000000 --- a/src/main/java/it/unimi/dsi/fastutil/shorts/ShortIterator.java +++ /dev/null @@ -1,85 +0,0 @@ -/* Generic definitions */ - -/* Assertions (useful to generate conditional code) */ - -/* Current type and class (and size, if applicable) */ -/* Value methods */ - -/* Interfaces (keys) */ -/* Interfaces (values) */ -/* Abstract implementations (keys) */ -/* Abstract implementations (values) */ - -/* Static containers (keys) */ -/* Static containers (values) */ - -/* Implementations */ -/* Synchronized wrappers */ -/* Unmodifiable wrappers */ -/* Other wrappers */ - -/* Methods (keys) */ -/* Methods (values) */ -/* Methods (keys/values) */ - -/* Methods that have special names depending on keys (but the special names depend on values) */ - -/* Equality */ -/* Object/Reference-only definitions (keys) */ -/* Primitive-type-only definitions (keys) */ -/* Object/Reference-only definitions (values) */ -/* - * Copyright (C) 2002-2016 Sebastiano Vigna - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package it.unimi.dsi.fastutil.shorts; - -import java.util.Iterator; - -/** - * A type-specific {@link Iterator}; provides an additional method to avoid - * (un)boxing, and the possibility to skip elements. - * - * @see Iterator - */ - -public interface ShortIterator - extends Iterator { - - /** - * Returns the next element as a primitive type. - * - * @return the next element in the iteration. - * @see Iterator#next() - */ - - short nextShort(); - - /** - * Skips the given number of elements. - * - *

- * The effect of this call is exactly the same as that of calling - * {@link #next()} for n times (possibly stopping if - * {@link #hasNext()} becomes false). - * - * @param n - * the number of elements to skip. - * @return the number of elements actually skipped. - * @see Iterator#next() - */ - - int skip(int n); -} diff --git a/src/test/java/com/github/akurilov/concurrent/test/RateThrottleTest.java b/src/test/java/com/github/akurilov/concurrent/test/RateThrottleTest.java index bcae49a..8038d71 100644 --- a/src/test/java/com/github/akurilov/concurrent/test/RateThrottleTest.java +++ b/src/test/java/com/github/akurilov/concurrent/test/RateThrottleTest.java @@ -1,6 +1,7 @@ package com.github.akurilov.concurrent.test; import com.github.akurilov.concurrent.RateThrottle; +import com.github.akurilov.concurrent.Throttle; import org.junit.Test; import static org.junit.Assert.assertEquals; @@ -20,13 +21,12 @@ public void testRate100mHzNonBatch() throws Exception { final double rateLimit = 0.1; final int timeLimitSec = 50; - final RateThrottle throttle = new RateThrottle(rateLimit); - final Object subj = new Object(); + final Throttle throttle = new RateThrottle(rateLimit); final LongAdder counter = new LongAdder(); final Thread submThread = new Thread( () -> { while(true) { - if(throttle.tryAcquire(subj)) { + if(throttle.tryAcquire()) { counter.increment(); } else { LockSupport.parkNanos(1); @@ -46,13 +46,12 @@ public void testRate10HzNonBatch() throws Exception { final int rateLimit = 10; final int timeLimitSec = 10; - final RateThrottle throttle = new RateThrottle(rateLimit); - final Object subj = new Object(); + final Throttle throttle = new RateThrottle(rateLimit); final LongAdder counter = new LongAdder(); final Thread submThread = new Thread( () -> { while(true) { - if(throttle.tryAcquire(subj)) { + if(throttle.tryAcquire()) { counter.increment(); } else { LockSupport.parkNanos(1); @@ -72,13 +71,12 @@ public void testRate100kHzNonBatch() throws Exception { final int rateLimit = 100_000; final int timeLimitSec = 20; - final RateThrottle throttle = new RateThrottle(rateLimit); - final Object subj = new Object(); + final Throttle throttle = new RateThrottle(rateLimit); final LongAdder counter = new LongAdder(); final Thread submThread = new Thread( () -> { while(true) { - if(throttle.tryAcquire(subj)) { + if(throttle.tryAcquire()) { counter.increment(); } else { LockSupport.parkNanos(1); @@ -98,14 +96,13 @@ public void testRate1HzBatch() throws Exception { final int rateLimit = 1; final int timeLimitSec = 50; - final RateThrottle throttle = new RateThrottle(rateLimit); - final Object subj = new Object(); + final Throttle throttle = new RateThrottle(rateLimit); final LongAdder counter = new LongAdder(); final Thread submThread = new Thread( () -> { int n; while(true) { - n = throttle.tryAcquire(subj, 10); + n = throttle.tryAcquire(10); if(n > 0) { counter.add(n); } else { @@ -126,14 +123,13 @@ public void testRate100HzBatch() throws Exception { final int rateLimit = 100; final int timeLimitSec = 50; - final RateThrottle throttle = new RateThrottle(rateLimit); - final Object subj = new Object(); + final Throttle throttle = new RateThrottle(rateLimit); final LongAdder counter = new LongAdder(); final Thread submThread = new Thread( () -> { int n; while(true) { - n = throttle.tryAcquire(subj, 100); + n = throttle.tryAcquire(100); if(n > 0) { counter.add(n); } else { @@ -154,14 +150,13 @@ public void testRate1MHzBatch() throws Exception { final int rateLimit = 1_000_000; final int timeLimitSec = 10; - final RateThrottle throttle = new RateThrottle(rateLimit); - final Object subj = new Object(); + final Throttle throttle = new RateThrottle(rateLimit); final LongAdder counter = new LongAdder(); final Thread submThread = new Thread( () -> { int n; while(true) { - n = throttle.tryAcquire(subj, 100); + n = throttle.tryAcquire(100); if(n > 0) { counter.add(n); } else { @@ -181,8 +176,7 @@ public void testRate1MHzBatch() public void testRate1kHzBatchConcurrent() { final int rateLimit = 1_000; final int timeLimitSec = 20; - final Object subj = new Object(); - final RateThrottle throttle = new RateThrottle(rateLimit); + final Throttle throttle = new RateThrottle(rateLimit); final LongAdder counter = new LongAdder(); final ExecutorService execSvc = Executors.newFixedThreadPool(4); for(int i = 0; i < 4; i ++) { @@ -192,13 +186,13 @@ public void testRate1kHzBatchConcurrent() { int n; while(true) { if(j == 0) { - if(throttle.tryAcquire(subj)) { + if(throttle.tryAcquire()) { counter.increment(); } else { LockSupport.parkNanos(1); } } else { - n = throttle.tryAcquire(subj, 1 + j); + n = throttle.tryAcquire(1 + j); if(n > 0) { counter.add(n); } else { diff --git a/src/test/java/com/github/akurilov/concurrent/test/SequentialWeightsThrottleTest.java b/src/test/java/com/github/akurilov/concurrent/test/SequentialWeightsThrottleTest.java index a3f8cd8..63211ce 100644 --- a/src/test/java/com/github/akurilov/concurrent/test/SequentialWeightsThrottleTest.java +++ b/src/test/java/com/github/akurilov/concurrent/test/SequentialWeightsThrottleTest.java @@ -1,11 +1,6 @@ package com.github.akurilov.concurrent.test; import com.github.akurilov.concurrent.SequentialWeightsThrottle; -import it.unimi.dsi.fastutil.ints.Int2IntMap; -import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap; -import it.unimi.dsi.fastutil.ints.Int2ObjectMap; -import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; - import org.junit.Test; import java.util.concurrent.ExecutorService; @@ -22,37 +17,31 @@ public class SequentialWeightsThrottleTest { - private enum IoType { - CREATE, READ - } + private static final int WRITE = 0; + private static final int READ = 1; - private final Int2IntMap weightMap = new Int2IntOpenHashMap() { - { - put(IoType.CREATE.ordinal(), 80); - put(IoType.READ.ordinal(), 20); - } + private final int[] weights = new int[] { + 80, + 20 }; - - private final Int2ObjectMap resultsMap = new Int2ObjectOpenHashMap() { - { - put(IoType.CREATE.ordinal(), new LongAdder()); - put(IoType.READ.ordinal(), new LongAdder()); - } + private final LongAdder[] resultCounters = new LongAdder[] { + new LongAdder(), + new LongAdder() }; - private final SequentialWeightsThrottle wt = new SequentialWeightsThrottle(weightMap); + private final SequentialWeightsThrottle wt = new SequentialWeightsThrottle(weights); private final class SubmTask implements Runnable { - private final IoType ioType; - public SubmTask(final IoType ioType) { - this.ioType = ioType; + private final int origin; + public SubmTask(final int origin) { + this.origin = origin; } @Override public final void run() { while(true) { - if(wt.tryAcquire(ioType.ordinal())) { - resultsMap.get(ioType.ordinal()).increment(); + if(wt.tryAcquire(origin)) { + resultCounters[origin].increment(); } else { LockSupport.parkNanos(1); } @@ -64,29 +53,29 @@ public final void run() { public void testRequestApprovalFor() throws Exception { final ExecutorService es = Executors.newFixedThreadPool(2); - es.submit(new SubmTask(IoType.CREATE)); - es.submit(new SubmTask(IoType.READ)); + es.submit(new SubmTask(WRITE)); + es.submit(new SubmTask(READ)); es.awaitTermination(10, TimeUnit.SECONDS); es.shutdownNow(); - final double writes = resultsMap.get(IoType.CREATE.ordinal()).sum(); - final long reads = resultsMap.get(IoType.READ.ordinal()).sum(); + final double writes = resultCounters[WRITE].sum(); + final long reads = resultCounters[READ].sum(); assertEquals(80/20, writes / reads, 0.01); System.out.println("Write rate: " + writes / 10 + " Hz, read rate: " + reads / 10 + " Hz"); } private final class BatchSubmTask implements Runnable { - private final IoType ioType; - public BatchSubmTask(final IoType ioType) { - this.ioType = ioType; + private final int origin; + public BatchSubmTask(final int origin) { + this.origin = origin; } @Override public final void run() { int n; while(true) { - n = wt.tryAcquire(ioType.ordinal(), 128); + n = wt.tryAcquire(origin, 128); if(n > 0) { - resultsMap.get(ioType.ordinal()).add(n); + resultCounters[origin].add(n); } else { LockSupport.parkNanos(1); } @@ -98,12 +87,12 @@ public final void run() { public void testRequestBatchApprovalFor() throws Exception { final ExecutorService es = Executors.newFixedThreadPool(2); - es.submit(new BatchSubmTask(IoType.CREATE)); - es.submit(new BatchSubmTask(IoType.READ)); + es.submit(new BatchSubmTask(WRITE)); + es.submit(new BatchSubmTask(READ)); es.awaitTermination(10, TimeUnit.SECONDS); es.shutdownNow(); - final double writes = resultsMap.get(IoType.CREATE.ordinal()).sum(); - final long reads = resultsMap.get(IoType.READ.ordinal()).sum(); + final double writes = resultCounters[WRITE].sum(); + final long reads = resultCounters[READ].sum(); assertEquals(80/20, writes / reads, 0.01); System.out.println("Write rate: " + writes / 10 + " Hz, read rate: " + reads / 10 + " Hz"); }