trove-3.0.3/0000755000175000017500000000000011763017636011634 5ustar ericherichtrove-3.0.3/CHANGES.txt0000644000175000017500000004706511763017636013461 0ustar ericherich--- 3.0.3 --- Bugs Fixed: - [3445639] ArrayIndexOutOfBoundsException from TIntHashSet.retainAll - [3460395] no_entry_value is set always to 0 in map default constructor --- 3.0.2 --- Bug Fixed: - [3429703] TIntObjectHashMap losing entry - [3431135] ArrayIndexOutOfBoundsException at TIntIntHashMap.keys - [3432212] entrySet() does not unwrap in cased of no_entry_value or no_entrykey - [3432175] Decorator entrySet() -keySet() impl - Minor problem with the way null keys are unwarped --- 3.0.1 --- Bugs Fixed: - fix for ClassCastException in equals(T,T) when comparing with REMOVED - [3408129] Benchmarks don't run correctly - [3394094] Args to gnu.trove.generator.Generator not basedir-relative - Re-introduce TLinkableAdapter class New Features: - [3412967] Need TMap interface - .zip and .tgz files now expand into a sub-directory - Documentation for generator patterns and replicated blocks - Maven artifact generation now a bit more automatic --- 3.0.0 --- - !!! Major restructuring of classes and packages !!! Interfaces have been broken out to allow for alternate implementations. The package changes will require code migration, although it should mainly consist of simply updating import statements. However, because everything is in new packages, both Trove 2.x and Trove 3.x can co-exist in a classpath (to hopefully ease the migration burden). - Broke out classes that allow custom hashing for performance reasons. New collections are: - TCustomHashMap - TCustomHashSet - TObject*CustomHashMap (ex: TObjectIntCustomHashMap) IdentityHashingStrategy is available for identity-based hash maps. - [ 3152276 ] Add sum() method to T*List - [ 3159432 ] THashMap.entrySet().remove() throws on non-Entries - [ 3153005 ] fix for null keys in Object maps - Benchmarks for comparing different libraries. Currently java.util, Colt, Trove 2 and Trove 3. - Fixes to serialVersionUID's and where Serializable is marked. For example, Serializable has been removed from the interfaces for various collections (to better match how it's done in java.util). - Many bug fixes, particularly to TLinkedList. --- 2.1.0 --- No substantial changes. --- 2.1.0 a3 --- Bugs fixed: - [ 2685774 ] THashMap serialization bug in 2.0.4 --- 2.1.0 a2 --- Bugs fixed: - [ 2166456 ] clone() for TObjectHashMap is inefficient - [ 2166768 ] add toString() method to maps. Thanks to Ozgur Aydinli. - [ 2688770 ] TxxxArrayList serializes full capacity instead of full size - [ 2687519 ] Primitive Lists hashCode is calculated w/o regard for order - Fixed issues related to removing items multiple times from TLinkedList and using removeFirst/Last when no items are in the list. New Features - [ 2126522 ] add putAll() to the HashMaps. Thanks to Ozgur Aydinli. --- 2.1.0 a1 --- Bugs fixed: - [ 2143564 ] THashSet serialization - [ 1960418 ] Decorators serialization - [ 2127841 ] Use .valueOf on wrap/unwrap in T#K##V#HashMapDecorator New Features: - Added "Dectorators" class for easier creation of decorator classes. - [ 2152149 ] Improve performance by avoiding Math/StrictMath (thanks to Mark Beevers) --- 2.0.5 a1 --- Bugs fixed: - [ 2037709 ] bug in .keys([]) method New Features: - added keys(e[]) method to P2O maps (TIntObjectHashMap, etc.) --- 2.0.4 --- Bugs fixed: - [ 1959853 ] @return for put and putIfAbsent is incorrect --- 2.0.4 rc1 --- Bugs Fixed: - [ 1952509 ] Replace StringBuffer with StringBuilder - [ 1952508 ] pufIfAbsent for maps - [ 1955103 ] Hashing Strategy Not Retained After Serialization --- 2.0.4 a2 --- Bugs fixed: - Correct an error in TLinkedList that caused nodes to not be properly linked when using addAfter(T,T). --- 2.0.4 a1 --- Bugs fixed: - [ 1946240 ] THash.ensureCapacity(...) bug --- 2.0.3 --- Bugs Fixed: - [ 1932929 ] add toString() methods to THashSet and THashMap - Switched to Arrays.fill (which seems to be slightly faster) for clearing --- 2.0.2 --- Bugs Fixed: - [ 1821911 ] get(0) doesn't throw exception when TLinkedList is empty - [ 1800288 ] Trivial typo fixes --- 2.0.1 --- Bugs Fixed: - Fixed implementation of PArrayList.min() and .max(). --- 2.0.1 rc1 --- New Features: [ 1778999 ] Publish a source-JAR with future releases Misc: - Switched version from 2.1 to 2.0.1. --- 2.0.1 ALPHA 3 (previously: 2.1 ALPHA 3) --- Bugs Fixed: [ 1764177 ] bug in binary search --- 2.0.1 ALPHA 2 (previously: 2.1 ALPHA 2) --- New Features: [ 1748566 ] add T[] getValues(T[] a) Bugs Fixed: - Corrected hashcode computation for longs. Should result in better lookup performance. --- 2.0.1 ALPHA 1 (previously: 2.1 ALPHA 1) --- New Features: [ 1741864 ] add TLinkedList addAfter method Bugs Fixed: [ 1738760 ] T*HashMap.retainEntries should suspend automatic compaction. - Corrected hashcode computation for longs. Should result in better lookup performance. Misc: - Added an assertion in HashFunctions to throw an assertion if a value of NaN is used in a lookup/insert/delete from a map. - Added TLinkedList.getNext() and getPrevious() methods. --- 2.0 --- Unchanged from 2.0rc1 --- 2.0rc1 --- New Features: [ 1606090 ] adjustOrPutValue [ 1604073 ] Generate primitive stacks [ 1632250 ] Do maps implement Iterable [ 1670933 ] Provide access to stack native arrays [ 1690743 ] Add subList(begin, end) to ArrayLists Added forEach(TObjectProcedure) method to TLinkedList Bugs Fixed: [ 1640353 ] Generator fails on multiple file systems [ 1676866 ] Not handling REMOVED flag correctly in TObjectHash.index(T) [ 1642768 ] Exception removing from iterator when auto-compact occurs --- 2.0a2 --- New Features: [ 779039 ] expose decorator's set/map Bugs Fixed: [ 1428614 ] THashMap.values().remove() can remove multiple mappings [ 1506751 ] TxxxArrayList.toNativeArray(offset, len) is broken [ 1606095 ] Critical Iterator Error --- 2.0a1 --- This release adds support for generics, which were introduced in JSE 1.5. Starting with this release, JSE 1.5 or greater is required in order to run Trove. Special thanks to JetBrains for their initial work providing generics support. Also added in this release is automatic compaction, such that manually calling compact() is no longer necessary (although it may still provide performance benefits in certain situations). Compactions are by default performed automatically when a certain number of removes are performed based on the size of the set or map. The compaction factor can be specified via THash.setAutoCompactionFactor(float) (the default compaction factor is set to match the load factor). So, for example, if a map is created with an initial capacity of 10 and a load factory of 0.5, a compaction will be performed after 5 removes. If a size is later grown to 1000, then a compaction will occur after 500 removes. When a set/map is rehashed, the time to next compaction is reset. NOTE: auto-compaction can be disabled by setting the autoCompactionFactory (via THash.setAutoCompactionFactor) to zero. Manually compacting a collection will also reset the auto-compaction counter, so that manually compacting more often than auto-compaction wants to occur effectively also disables auto-compaction. NOTE: while manually calling compact() is no longer strictly necessary, results should always be verified in your application to ensure that the auto-compaction scheme and the compaction factors work well for your individual scenario. Support for more primitve types has been introduced. Object serialization has been changed to use Externalization. Unfortunately this means that objects serialized with earlier versions cannot be read by this release. The up-side is that this gives enough flexibility to ensure that we won't need to break serialization again. The other benefit is that the output is more efficient/compact and readable... especially when used with XML serialization mechanisms such as XStream. New Features: [ 918059 ] should rehash when below low water mark upon remove [ 1153656 ] generics? Bugs Fixed: [ 1518795 ] NullPointerException in TLinkedList's removeFirst()/Last() [ 1277703 ] make T**HashMap serializable [ 1417563 ] TLinkedList.add(int,Object) bug [ 1518823 ] another TLinkedList.add(int,Object) bug [ 1461458 ] THashMap.equals(..) method is not consistent [ 1571435 ] Error in cloning of TObjectXXXHashMap instances --- 1.1b5 --- Bugs fixed: [ 1391359 ] Duplicate iteration in THashSet.toArray(Object[]) removed the duplication [ 1382196 ] THashMap.entrySet().retainAll() implemented missing methods on elements of entrySet, refactored retainAll to use retainEntries, which saves a bunch of allocations [ 1378868 ] CVS has junit.jar checked in as ASCII flipped on '-kb' for this file [ 1193416 ] TByteArrayList throws ArrayIndexOutOfBoundsException wrongly fixed off by one error --- 1.1b4 --- Accepted patch for feature request 926921 - adds support for short, byte collections. Also adds support for null object keys. THIS WILL BREAK SERIALIZATION. A big thanks to Steven Lunt for putting this patch together. Added testSerializablePrimitives unit test to validate that behavior reported in 1113420 does work as it's supposed to. Fixed doc problem reported in 939016 Fixed 995597, missing serial version IDs. NOTE: THashMap, THashSet and TLinkedList have IDs generated by serialver and are believed to be b/w compatible. The generated collections, however, are NOT reverse compatible versions and so will break archived collections created with earlier versions of trove. Fixed 937977 -- primitive array lists were not doing a true deep clone of the underlying array. This is fixed --- 1.1b3 --- Fixed 918045 -- bug in *Decorator classes made it impossible to subclass the decorators and make those subclasses cloneable. Thanks to Steve Lunt for the bug report. --- 1.1b2 --- Fixed 901135 -- bug in T*Hash.insertionIndex() methods that prevented us from reclaiming the very first REMOVED slot if that's what the first hash landed upon. In applications that do lots of adds/removes, this would have led to unnecessary rehashing. With this fix, you can add(1), remove(1), and then re add(1) and the same slot will be used. Thanks to matlun for reporting the problem. --- 1.1b1 --- fixed a bug in decorator equals methods (845890) fixed a memory leak for certain usage patterns (843772) corrected some javadoc defects (846286) minor tuning of T*ArrayList toString() added clone() methods to decorator classes. Thanks to Steve Lunt for the bug report. implemented equals()/hashCode() on THashMap.KeyView and (by extension) subclasses. This allows the test in THashMapTests.testKeySetEqualsEquivalentSet to pass. fix 787515 -- bug in T*ArrayList.set(int, *[], int, int) --- 1.0.2 --- revamped versioning scheme added hashCode implementation to collections so that they can appear in collections too. added check+exception to detect violations of the equals() <-> hashCode() contract specified in java.lang.Object's api. --- 0.1.8 --- Added gnu.trove.decorator package, with Decorator classes that wrap trove's primitive maps and sets for conformance with the java.util.{Map,Set} APIs. --- 0.1.7 --- Added iterators to the primitive maps and sets. Note that semantics differ from those of java.util.Iterator, so RTFM. Added hashing strategy interfaces to allow users to implement custom hashing schemes for optimal distribution for specific data sets. Fixed bug 602376 -- ClassCastException n THashMap.putAll Made all collections implement Cloneable. primitive collections clone deeply; Object collections produce shallow clones. --- 0.1.6 --- Minor bug fix release. Two bugs in TIntArrayList have been fixed. Thanks to Jessica P. Hekman for reporting them. One of these prevented toNativeArray from working correctly in certain circumstances; the other problem was with the depth of cloning operations. One enhancement to TintArrayList has been made -- serialized instances are now compact -- previous versions relied on serialization behavior of the backing array, which included empty slots and so wasted space. Serialization of sets/maps has been modified as follows: previously all of the writeObject methods used a local implementation of the TXXXProcedure for writing out the data in a particular collection. These have been replaced by a single class (SerializationProcedure) which implements all of the appropriate interfaces. This reduces the number of .class files in the trove jar --- 0.1.5 --- added retainEntries methods to all Map classes. These methods accept procedure objects of the appropriate sort and use the return value of those procedures to determine whether or not a particular entry in the map should be retained. This is useful for applying a cutoff in a map without copying data: TIntIntHashMap map = new TIntIntHashMap(); // load up map map.retainEntries(new TIntIntProcedure() { public boolean execute(int key, int val) { return val > 3; // retain only those mappings with val > 3 } }); It can also be used if you want to reduce one map to the intersection between it and another map: THashMap map1 = new THashMap(); THashMap map2 = new THashMap(); // load up both maps map1.retainEntries(new TObjectObjectProcedure() { public boolean execute(Object key, Object val) { return map2.containsKey(key); // retain the intersection with map2 } }); --- 0.1.4 --- added increment() and adjustValue() methods to maps with primitive values. These are useful in the all-too-common case where you need a map for the purposes of counting the number of times a key is seen. These methods are handy because you don't have to do a "containsKey" test prior to every increment() call. Instead, you can check the return status (true if an existing mapping was modified) and if it is false, then insert the mapping with the initial value: TIntIntHashMap map = TIntIntHashMap(); int key, val; key = keyFromSomeWhere(); val = valFromSomeWhere(); if (! map.increment(key)) map.put(key, 0); increment is implemented in terms of adjustValue, which allows you to specify the amount by which the primitive value associated with a particular key should be adjusted. Thanks to Jason Baldridge for the idea. --- 0.1.3 --- bug fix in TLinkedList ListIterator implementation: fixed remove() behavior so that it correctly removes the last element returned by either next() or previous(). Added several tests to suite to verify that list iterator does what it's supposed to do in accordance with the collections API docs. --- 0.1.2 --- bug fix in primitive hash sets: toArray now produces a correct return value of size set.size(). Previously it generated an ArrayIndexOutOfBoundsException. Thanks to Tobias Henle for finding this. revised class hierarchy so that all primitive hashing collections are derived from TPrimitiveHash, which extends THash. Object hashing collections are derived from TObjectHash. As part of this change, the byte[] flags were pushed down to TPrimitiveHash, and TObjectHash was revised so that it no longer needs a byte[] array to track the state of the table. This has an appreciable impact on the total size of Object hashing collections: a set of 1,000 Integers used to take 69% of the memory needed for a JDK set; it now takes only 62%. removed slots can now be re-used in all hashing collections. If the search for an insertion index does not find that the key is already present in the map, insertionIndex implementations will now return the index of the first REMOVED or FREE slot. This means that tables which undergo a pattern of insertions/deletions without radical changes in size will not trigger as many rehashes as before. revised hashing algorithm so that the second hash function is only executed when necessary and so that FREE or FULL w/identical content slots can be found with a minimum of effort. --- 0.1.1 --- made the initial capacity of lists used for return values in grep/inverseGrep be the default capacity rather than the size of the list-being-grepped. This saves space when a small list is grepped from a larger list. added reset and resetQuick methods to *ArrayList implementations so that lists can be cleared while retaining their current capacity. changed *ArrayList toNativeArray() method behavior so that a List of 0 length can return a native array of 0 length (previously this would have thrown an exception) revamped *ArrayList insert/remove implementations so that edits are done in place instead of with a temporary array. minor performance tweak in THashIterator --- 0.1.0 --- Added primitive ArrayList implementations. --- 0.0.9 --- Made all collections implement java.io.Serializable Made all collections implement equals() so that they compare their contents instead of doing collection object identity. Made TLinkable extend java.io.Serializable Changed secondary hash function to reflect Knuth's observation about the desirability of using an odd value. Added trimToSize() and ensureCapacity() methods (finally) implemented loadFactor, with default of 0.5, per Knuth. Note that load/capacity/size are handled differently than in the Javasoft implementations. Specifically, if you ask for a collection of capacity X, Trove will give you one that can hold X elements without rehashing; Javasoft's implementation does not do this. --- 0.0.8 --- Fixes for several user-reported bugs. Unit tests have been added to demonstrate that each of these is actually fixed. 485440 Null in keys() from TObjectDoubleHashMap size/free were being updated even when a map.put() was really a replaement for an existing mapping. 485829 null values not handled correctly 485831 null values cause exceptions 485834 null values cause NullPointerException made Maps that hold Object values behave correctly (no NPE) when doing comparisons with null objects, since null values are legal. 485837 entrySet comparison semantics are wrong made entrySet check both key and value when doing comparisons. --- 0.0.7 --- new package: gnu.trove.benchmark replaced gnu.trove.Benchmark with benchmark package. This now produces formatted reports that include OS/JVM specs. Changed benchmarking approach so that timestamps are only taken at the beginning/end of the full repetition count for an operation. This reduces the variability caused by calling System.currentTimeMillis() more than once in the same second. Added memory profiler which produces a report with the memory requirements for trove/javasoft collections of the same objects. build.xml modified jar task so that the benchmark package is not included in the jar file or the javadoc set. Only the framework classes get jarred up; developers can run the benchmarks by using the output/classes directory instead. TObjectHash Based on profiling results, replaced calls to HashFunctions.hash(obj) with direct invocation of obj.hashCode() to save a method call. This is probably inlined by hotspot compilers, but my profiler doesn't work with those. TObjectHash.HashIterator Based on bytecode examination, replaced a putfield/getfield combo with a putfield/dup_x. This saves three opcodes in a method which gets called a lot (moveToNextIndex()). PrimeFinder/HashFunctions finalized both classes and all methods. trove-3.0.3/README-license.txt0000644000175000017500000000157111763017636014756 0ustar ericherichThe Trove library is licensed under the Lesser GNU Public License, which is included with the distribution in a file called LICENSE.txt. Other license arrangements are possible, for a fee: contact ericdf@users.sourceforge.net for terms/pricing. The PrimeFinder and HashFunctions classes in Trove are subject to the following license restrictions: 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. trove-3.0.3/test/0000755000175000017500000000000011763017634012611 5ustar ericherichtrove-3.0.3/test/gnu/0000755000175000017500000000000011763017634013402 5ustar ericherichtrove-3.0.3/test/gnu/trove/0000755000175000017500000000000012000515265014525 5ustar ericherichtrove-3.0.3/test/gnu/trove/set/0000755000175000017500000000000011763017634015334 5ustar ericherichtrove-3.0.3/test/gnu/trove/set/hash/0000755000175000017500000000000012000515265016243 5ustar ericherichtrove-3.0.3/test/gnu/trove/set/hash/TPrimitiveHashSetTest.java0000644000175000017500000004342111763017634023342 0ustar ericherichpackage gnu.trove.set.hash; import gnu.trove.iterator.TIntIterator; import gnu.trove.procedure.TIntProcedure; import gnu.trove.set.TIntSet; import junit.framework.TestCase; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.*; /** * Test the primitive HashSet classes. */ public class TPrimitiveHashSetTest extends TestCase { public TPrimitiveHashSetTest(String name) { super(name); } public void setUp() throws Exception { super.setUp(); } public void tearDown() throws Exception { super.tearDown(); } public void testConstructors() throws Exception { TIntSet set = new TIntHashSet(); assertNotNull(set); int[] ints = {1138, 42, 86, 99, 101}; set.addAll(ints); TIntSet copy = new TIntHashSet(set); assertTrue("set not a copy: " + set + ", " + copy, set.equals(copy)); TIntSet another = new TIntHashSet(20); another.addAll(ints); assertTrue("set not equal: " + set + ", " + copy, set.equals(another)); another = new TIntHashSet(2, 1.0f); another.addAll(ints); assertTrue("set not equal: " + set + ", " + copy, set.equals(another)); another = new TIntHashSet(ints); assertTrue("set not equal: " + set + ", " + copy, set.equals(another)); } public void testIsEmpty() throws Exception { TIntSet s = new TIntHashSet(); assertTrue("new set wasn't empty", s.isEmpty()); s.add(1); assertTrue("set with element reports empty", !s.isEmpty()); s.clear(); assertTrue("cleared set reports not-empty", s.isEmpty()); } public void testContains() throws Exception { TIntSet s = new TIntHashSet(); int i = 100; s.add(i); assertTrue("contains failed", s.contains(i)); assertFalse("contains failed", s.contains(1000)); } @SuppressWarnings({"ForLoopReplaceableByForEach"}) public void testContainsAll() throws Exception { int[] ints = {1138, 42, 13, 86, 99}; TIntSet set = new TIntHashSet(); set.addAll(ints); TIntSet other = new TIntHashSet(); other.addAll(ints); List ints_list = new ArrayList(); for (int element : ints) { ints_list.add(element); } for (int index = 0; index < ints.length; index++) { assertTrue(Integer.valueOf(ints[index]).toString(), set.contains(ints[index])); } assertTrue("containsAll(Collection) failed: " + set, set.containsAll(ints_list)); ints_list.remove(Integer.valueOf(42)); ints_list.add(Long.valueOf(42)); assertFalse("containsAll(Collection) failed: " + set, set.containsAll(ints_list)); assertTrue("containsAll(TIntSet) failed (same set): " + set, set.containsAll(set)); assertTrue("containsAll(TIntSet) failed (other set): " + set, set.containsAll(other)); assertTrue("containsAll(int[]) failed: " + set, set.containsAll(ints)); int[] failed = {42, 86, 99, 123456}; TIntSet failed_set = new TIntHashSet(); failed_set.addAll(failed); List failed_list = new ArrayList(); for (int element : failed) { failed_list.add(element); } assertFalse("containsAll(Collection) failed (false positive): " + set, set.containsAll(failed_list)); assertFalse("containsAll(TIntSet) failed (false positive): " + set, set.containsAll(failed_set)); assertFalse("containsAll(int[]) failed (false positive): " + set, set.containsAll(failed)); } public void testAddAll() throws Exception { int[] ints = {1138, 42, 13, 86, 99, 101}; TIntSet set; List list = new ArrayList(); for (int element : ints) { list.add(Integer.valueOf(element)); } set = new TIntHashSet(); assertTrue("addAll(Collection) failed: " + set, set.addAll(list)); for (int element : ints) { assertTrue("contains failed: ", set.contains(element)); } set = new TIntHashSet(); assertTrue("addAll(int[]) failed: " + set, set.addAll(ints)); for (int element : ints) { assertTrue("contains failed: ", set.contains(element)); } TIntSet test_set = new TIntHashSet(); assertTrue("addAll(TIntSet) failed: " + test_set, test_set.addAll(set)); for (int element : ints) { assertTrue("contains failed: ", set.contains(element)); } } public void testRetainAll() throws Exception { int[] ints = {1138, 42, 13, 86, 99, 101}; TIntSet set = new TIntHashSet(); set.addAll(ints); TIntSet other = new TIntHashSet(); other.addAll(ints); int[] to_retain = {13, 86, 99, 1138}; TIntSet retain_set = new TIntHashSet(); retain_set.addAll(to_retain); List retain_list = new ArrayList(); for (int element : to_retain) { retain_list.add(element); } assertFalse("retainAll(TIntSet) failed (same set): " + set, set.retainAll(set)); // Contains all the original elements assertTrue(set.toString(), set.containsAll(ints)); assertTrue(retain_set.toString(), retain_set.containsAll(to_retain)); assertTrue("retainAll(Collection) failed: " + set, set.retainAll(retain_list)); // Contains just the expected elements assertFalse(set.toString(), set.containsAll(ints)); assertTrue(set.toString(), set.containsAll(to_retain)); assertTrue(retain_set.toString(), retain_set.containsAll(to_retain)); // reset the set. set = new TIntHashSet(); set.addAll(ints); assertTrue("retainAll(TIntSet) failed: " + set, set.retainAll(retain_set)); // Contains just the expected elements assertFalse(set.toString(), set.containsAll(ints)); assertTrue(set.toString(), set.containsAll(to_retain)); assertTrue(retain_set.toString(), retain_set.containsAll(to_retain)); // reset the set. set = new TIntHashSet(); set.addAll(ints); assertTrue("retainAll(int[]) failed: " + set, set.retainAll(to_retain)); // Contains just the expected elements assertFalse(set.toString(), set.containsAll(ints)); assertTrue(set.toString(), set.containsAll(to_retain)); assertTrue(retain_set.toString(), retain_set.containsAll(to_retain)); } public void testRemoveAll() throws Exception { int[] ints = {1138, 42, 13, 86, 99, 101}; TIntSet set = new TIntHashSet(); set.addAll(ints); TIntSet other = new TIntHashSet(); other.addAll(ints); int[] to_remove = {13, 86, 99, 1138}; TIntSet remove_set = new TIntHashSet(); remove_set.addAll(to_remove); List remove_list = new ArrayList(); for (int element : to_remove) { remove_list.add(element); } int[] remainder = {42, 101}; try { assertFalse("removeAll(TIntSet) failed (same set): " + set, set.removeAll(set)); fail("should have thrown ConcurrentModificationException"); } catch (ConcurrentModificationException cme) { // expected exception thrown. } // reset the set. set = new TIntHashSet(); set.addAll(ints); assertTrue("removeAll(Collection) failed: " + set, set.removeAll(remove_list)); // Contains just the expected elements assertTrue(set.toString(), set.containsAll(remainder)); assertFalse(set.toString(), set.containsAll(to_remove)); assertTrue(remove_set.toString(), remove_set.containsAll(to_remove)); // reset the set. set = new TIntHashSet(); set.addAll(ints); assertTrue("removeAll(TIntSet) failed: " + set, set.removeAll(remove_set)); // Contains just the expected elements assertTrue(set.toString(), set.containsAll(remainder)); assertFalse(set.toString(), set.containsAll(to_remove)); assertTrue(remove_set.toString(), remove_set.containsAll(to_remove)); // reset the set. set = new TIntHashSet(); set.addAll(ints); assertTrue("removeAll(int[]) failed: " + set, set.removeAll(to_remove)); // Contains just the expected elements assertTrue(set.toString(), set.containsAll(remainder)); assertFalse(set.toString(), set.containsAll(to_remove)); assertTrue(remove_set.toString(), remove_set.containsAll(to_remove)); } public void testAdd() throws Exception { TIntSet set = new TIntHashSet(); assertTrue("add failed", set.add(1)); assertFalse("duplicated add modified set", set.add(1)); } public void testRemove() throws Exception { TIntSet set = new TIntHashSet(); set.add(1); set.add(2); assertTrue("One was not added", set.contains(1)); assertTrue("One was not removed", set.remove(1)); assertFalse("One was not removed", set.contains(1)); assertTrue("Two was also removed", set.contains(2)); } public void testRemoveNonExistant() throws Exception { TIntSet set = new TIntHashSet(); set.add(1); set.add(2); assertTrue("One was not added", set.contains(1)); assertTrue("One was not removed", set.remove(1)); assertFalse("One was not removed", set.contains(1)); assertTrue("Two was also removed", set.contains(2)); assertFalse("Three was removed (non-existant)", set.remove(3)); } public void testSize() throws Exception { TIntSet set = new TIntHashSet(); assertEquals("initial size was not 0", 0, set.size()); for (int i = 0; i < 99; i++) { set.add(i); assertEquals("size did not increase after add", i + 1, set.size()); } } public void testClear() throws Exception { TIntSet set = new TIntHashSet(); set.addAll(new int[]{1, 2, 3}); assertEquals("size was not 3", 3, set.size()); set.clear(); assertEquals("initial size was not 0", 0, set.size()); } public void testSerialize() throws Exception { int[] ints = {1138, 42, 86, 99, 101}; TIntSet set = new TIntHashSet(); set.addAll(ints); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(set); ByteArrayInputStream bias = new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bias); TIntSet deserialized = (TIntSet) ois.readObject(); assertEquals(set, deserialized); } public void testToArray() { TIntSet set = new TIntHashSet(); int[] ints = {42, 1138, 13, 86, 99}; set.addAll(ints); int[] res = set.toArray(); Arrays.sort(ints); Arrays.sort(res); assertTrue(Arrays.equals(ints, res)); } public void testToArrayMatchesIteratorOrder() { TIntSet set = new TIntHashSet(); int[] ints = {42, 1138, 13, 86, 99}; set.addAll(ints); int[] toarray_ints = set.toArray(); int[] iter_ints = new int[5]; TIntIterator iter = set.iterator(); int index = 0; while (iter.hasNext()) { iter_ints[index++] = iter.next(); } assertTrue(Arrays.equals(iter_ints, toarray_ints)); } public void testToArrayWithParams() { int no_entry_value = Integer.MIN_VALUE; TIntSet set = new TIntHashSet(10, 0.5f, no_entry_value); assertEquals(no_entry_value, set.getNoEntryValue()); int[] ints = {42, 1138, 13, 86, 99}; set.addAll(ints); int[] sink = new int[ints.length + 2]; sink[sink.length - 1] = -1; sink[sink.length - 2] = -2; int[] res = set.toArray(sink); assertEquals(set.getNoEntryValue(), res[set.size()]); Set copy = new HashSet(); for (int element : sink) { copy.add(Integer.valueOf(element)); } Set bogey = new HashSet(); for (int element : ints) { bogey.add(Integer.valueOf(element)); } bogey.add(-1); bogey.add(no_entry_value); assertEquals(bogey, copy); } public void testRehashing() throws Exception { int size = 10000; TIntSet set = new TIntHashSet(10); for (int i = 0; i < size; i++) { set.add(i); } assertEquals(set.size(), size); } public void testIterator() { TIntSet set = new TIntHashSet(); set.add(1); set.add(2); set.add(3); set.add(4); TIntIterator iter = set.iterator(); assertTrue("iterator should have a next item", iter.hasNext()); int last = -1; while (iter.hasNext()) { int next = iter.next(); assertTrue(Integer.valueOf(next).toString(), next >= 1 && next <= 4); assertTrue(Integer.valueOf(next).toString(), next != last); last = next; } assertFalse("iterator should not have a next item", iter.hasNext()); assertTrue("set should contain 1", set.contains(1)); assertTrue("set should contain 2", set.contains(2)); assertTrue("set should contain 3", set.contains(3)); assertTrue("set should contain 4", set.contains(4)); assertEquals(4, set.size()); } public void testIteratorRemove() { TIntSet set = new TIntHashSet(); set.add(1); set.add(2); set.add(3); set.add(4); TIntIterator iter = set.iterator(); assertTrue("iterator should have a next item", iter.hasNext()); int last = -1; while (iter.hasNext()) { int next = iter.next(); assertTrue(next >= 1 && next <= 4); assertTrue(next != last); last = next; if (next == 3) { iter.remove(); } } assertFalse("iterator should not have a next item", iter.hasNext()); assertFalse("set should not contain 3", set.contains(3)); assertTrue("set should contain 1", set.contains(1)); assertTrue("set should contain 2", set.contains(2)); assertTrue("set should contain 4", set.contains(4)); assertEquals(3, set.size()); } public void testForEach() { TIntSet set = new TIntHashSet(10, 0.5f); int[] ints = {1138, 42, 86, 99, 101}; set.addAll(ints); class ForEach implements TIntProcedure { TIntSet built = new TIntHashSet(); public boolean execute(int value) { built.add(value); return true; } TIntSet getBuilt() { return built; } } ForEach procedure = new ForEach(); set.forEach(procedure); TIntSet built = procedure.getBuilt(); assertEquals("inequal sizes: " + set + ", " + built, set.size(), built.size()); assertTrue("inequal sets: " + set + ", " + built, set.equals(built)); } public void testEquals() { int[] ints = {1138, 42, 86, 99, 101}; TIntSet set = new TIntHashSet(); set.addAll(ints); TIntSet other = new TIntHashSet(); other.addAll(ints); assertTrue("sets incorrectly not equal: " + set + ", " + other, set.equals(other)); int[] mismatched = {72, 49, 53, 1024, 999}; TIntSet unequal = new TIntHashSet(); unequal.addAll(mismatched); assertFalse("sets incorrectly equal: " + set + ", " + unequal, set.equals(unequal)); // Change length, different code branch unequal.add(1); assertFalse("sets incorrectly equal: " + set + ", " + unequal, set.equals(unequal)); } public void testHashcode() { int[] ints = {1138, 42, 86, 99, 101}; TIntSet set = new TIntHashSet(); set.addAll(ints); TIntSet other = new TIntHashSet(); other.addAll(ints); assertTrue("hashcodes incorrectly not equal: " + set + ", " + other, set.hashCode() == other.hashCode()); int[] mismatched = {72, 49, 53, 1024, 999}; TIntSet unequal = new TIntHashSet(); unequal.addAll(mismatched); assertFalse("hashcodes unlikely equal: " + set + ", " + unequal, set.hashCode() == unequal.hashCode()); } public void test3445639() throws Exception { // Retain all bug AIOBE TIntHashSet hs = new TIntHashSet(23, 1f); hs.addAll(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22}); hs.retainAll(new int[]{11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22}); hs.retainAll(new int[]{18}); } } trove-3.0.3/test/gnu/trove/set/hash/TLinkedHashSetTest.java0000644000175000017500000004441311763017634022602 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001-2006, Eric D. Friedman All Rights Reserved. // Copyright (c) 2009, Rob Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.set.hash; import junit.framework.TestCase; import org.omg.CORBA.portable.Streamable; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.*; /** * Created: Sat Nov 3 10:33:15 2001 * * @author Eric D. Friedman * @author Rob Eden * @author Jeff Randall * @version $Id: THashSetTest.java,v 1.1.2.3 2010/03/02 04:09:50 robeden Exp $ */ public class TLinkedHashSetTest extends TestCase { public TLinkedHashSetTest(String name) { super( name ); } public void setUp() throws Exception { super.setUp(); } public void tearDown() throws Exception { super.tearDown(); } public void testConstructors() throws Exception { Set set = new TLinkedHashSet(); assertNotNull( set ); String[] strings = {"a", "b", "c", "d"}; set.addAll( Arrays.asList( strings ) ); Set copy = new TLinkedHashSet( set ); assertTrue( "set not a copy: " + set + ", " + copy, set.equals( copy ) ); Set another = new TLinkedHashSet( 20 ); another.addAll( Arrays.asList( strings ) ); assertTrue( "set not equal: " + set + ", " + copy, set.equals( another ) ); another = new TLinkedHashSet( 2, 1.0f ); another.addAll( Arrays.asList( strings ) ); assertTrue( "set not equal: " + set + ", " + copy, set.equals( another ) ); } public void testIsEmpty() throws Exception { Set s = new TLinkedHashSet(); assertTrue( "new set wasn't empty", s.isEmpty() ); s.add( "One" ); assertTrue( "set with element reports empty", !s.isEmpty() ); s.clear(); assertTrue( "cleared set reports not-empty", s.isEmpty() ); } public void testContains() throws Exception { Set s = new TLinkedHashSet(); String o = "testContains"; s.add( o ); assertTrue( "contains failed", s.contains( o ) ); } @SuppressWarnings({"ForLoopReplaceableByForEach"}) public void testContainsAll() throws Exception { Set s = new TLinkedHashSet(); String[] o = {"Hello World", "Goodbye World", "Hello Goodbye"}; s.addAll( Arrays.asList( o ) ); for ( int i = 0; i < o.length; i++ ) { assertTrue( o[i], s.contains( o[i] ) ); } assertTrue( "containsAll failed: " + s, s.containsAll( Arrays.asList( o ) ) ); String[] more = {"Hello World", "Goodbye World", "Hello Goodbye", "Not There"}; assertFalse( "containsAll failed: " + s, s.containsAll( Arrays.asList( more ) ) ); } public void testRetainAll() throws Exception { Set set = new TLinkedHashSet(); String[] strings = {"Hello World", "Goodbye World", "Hello Goodbye", "Remove Me"}; set.addAll( Arrays.asList( strings ) ); for ( String string : strings ) { assertTrue( string, set.contains( string ) ); } String[] retain = {"Hello World", "Goodbye World", "Hello Goodbye"}; assertTrue( "retainAll failed: " + set, set.retainAll( Arrays.asList( retain ) ) ); assertTrue( "containsAll failed: " + set, set.containsAll( Arrays.asList( retain ) ) ); } public void testRemoveAll() throws Exception { Set set = new TLinkedHashSet(); String[] strings = {"Hello World", "Goodbye World", "Hello Goodbye", "Keep Me"}; set.addAll( Arrays.asList( strings ) ); for ( String string : strings ) { assertTrue( string, set.contains( string ) ); } String[] remove = {"Hello World", "Goodbye World", "Hello Goodbye"}; assertTrue( "removeAll failed: " + set, set.removeAll( Arrays.asList( remove ) ) ); assertTrue( "removeAll failed: " + set, set.containsAll( Arrays.asList( "Keep Me" ) ) ); for ( String element : remove ) { assertFalse( element + " still in set: " + set, set.contains( element ) ); } assertEquals( 1, set.size() ); } public void testAdd() throws Exception { Set s = new TLinkedHashSet(); assertTrue( "add failed", s.add( "One" ) ); assertTrue( "duplicated add succeded", !s.add( "One" ) ); } public void testRemove() throws Exception { Set s = new TLinkedHashSet(); s.add( "One" ); s.add( "Two" ); assertTrue( "One was not added", s.contains( "One" ) ); assertTrue( "One was not removed", s.remove( "One" ) ); assertTrue( "One was not removed", !s.contains( "One" ) ); assertTrue( "Two was removed", s.contains( "Two" ) ); assertEquals( 1, s.size() ); } public void testRemoveObjectNotInSet() throws Exception { Set set = new TLinkedHashSet(); set.add( "One" ); set.add( "Two" ); assertTrue( "One was not added", set.contains( "One" ) ); assertTrue( "One was not removed", set.remove( "One" ) ); assertTrue( "One was not removed", !set.contains( "One" ) ); assertTrue( "Two was removed", set.contains( "Two" ) ); assertFalse( "Three was removed (non-existant)", set.remove( "Three" ) ); assertEquals( 1, set.size() ); } public void testSize() throws Exception { Set o = new TLinkedHashSet(); assertEquals( "initial size was not 0", 0, o.size() ); for ( int i = 0; i < 99; i++ ) { o.add( new Object() ); assertEquals( "size did not increase after add", i + 1, o.size() ); } } public void testClear() throws Exception { Set s = new TLinkedHashSet(); s.addAll( Arrays.asList( "one", "two", "three" ) ); assertEquals( "size was not 3", 3, s.size() ); s.clear(); assertEquals( "initial size was not 0", 0, s.size() ); } public void testIterationOrder() throws Exception { TLinkedHashSet lhs = new TLinkedHashSet(); Set s = lhs; s.add("a"); s.add("b"); s.add("c"); // Iterator it = s.iterator(); // assertEquals("a", it.next()); assertEquals("b", it.next()); assertEquals("c", it.next()); // s.add("a"); it = s.iterator(); // assertEquals("a", it.next()); assertEquals("b", it.next()); assertEquals("c", it.next()); // s.remove("a"); s.add("a"); // it = s.iterator(); assertEquals("b", it.next()); assertEquals("c", it.next()); assertEquals("a", it.next()); // lhs.compact(); it = s.iterator(); assertEquals("b", it.next()); assertEquals("c", it.next()); assertEquals("a", it.next()); } public void testIteratorRemove() throws Exception { Set s = new TLinkedHashSet(); s.add("a"); s.add("b"); s.add("c"); // Iterator it = s.iterator(); // assertEquals("a", it.next()); assertEquals("b", it.next()); assertEquals("c", it.next()); it = s.iterator(); // assertEquals("a", it.next()); it.remove(); assertEquals("b", it.next()); assertEquals("c", it.next()); it = s.iterator(); // assertEquals("b", it.next()); it.remove(); assertEquals("c", it.next()); it = s.iterator(); // assertEquals("c", it.next()); it.remove(); assertTrue(s.isEmpty()); } public void testSerialize() throws Exception { Set s = new TLinkedHashSet(); s.addAll( Arrays.asList( "one", "two", "three" ) ); assertEquals(s, s); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream( baos ); oos.writeObject( s ); ByteArrayInputStream bais = new ByteArrayInputStream( baos.toByteArray() ); ObjectInputStream ois = new ObjectInputStream( bais ); TLinkedHashSet s2 = (TLinkedHashSet) ois.readObject(); assertEquals( s, s2 ); } public void testToArray() { Set s = new TLinkedHashSet(); String[] str = {"hi", "bye", "hello", "goodbye"}; s.addAll( Arrays.asList( str ) ); Object[] res = s.toArray(); Arrays.sort( str ); Arrays.sort( res ); assertTrue( Arrays.equals( str, res ) ); } public void testToArrayWithParams() { Set s = new TLinkedHashSet(); String[] str = {"hi", "bye", "hello", "goodbye"}; s.addAll( Arrays.asList( str ) ); String[] sink = new String[str.length + 2]; sink[sink.length - 1] = "residue"; sink[sink.length - 2] = "will be cleared"; String[] res = s.toArray( sink ); Set copy = new HashSet(); copy.addAll( Arrays.asList( res ) ); Set bogey = new HashSet(); bogey.addAll( Arrays.asList( str ) ); bogey.add( "residue" ); bogey.add( null ); assertEquals( bogey, copy ); } @SuppressWarnings({"ToArrayCallWithZeroLengthArrayArgument", "SuspiciousToArrayCall"}) public void testToArrayAnotherType() throws Exception { Set set = new TLinkedHashSet(); Number[] nums = {1138, 42, 86, 99, 101}; set.addAll( Arrays.asList( nums ) ); Integer[] to_int_array_zero = set.toArray( new Integer[0] ); assertTrue( "set and array mismatch: " + set + ", " + Arrays.asList( to_int_array_zero ), set.containsAll( Arrays.asList( to_int_array_zero ) ) ); Integer[] to_int_array_size = set.toArray( new Integer[set.size()] ); assertTrue( "set and array mismatch: " + set + ", " + Arrays.asList( to_int_array_size ), set.containsAll( Arrays.asList( to_int_array_size ) ) ); Number[] to_num_array_zero = set.toArray( new Number[0] ); assertTrue( "set and array mismatch: " + set + ", " + Arrays.asList( to_num_array_zero ), set.containsAll( Arrays.asList( to_num_array_zero ) ) ); Number[] to_num_array_size = set.toArray( new Number[set.size()] ); assertTrue( "set and array mismatch: " + set + ", " + Arrays.asList( to_num_array_size ), set.containsAll( Arrays.asList( to_num_array_size ) ) ); } @SuppressWarnings({"MismatchedQueryAndUpdateOfCollection"}) public void testRehashing() throws Exception { Set s = new TLinkedHashSet(); for ( int i = 0; i < 10000; i++ ) { s.add( new Integer( i ) ); } } /** * this tests that we throw when people violate the * general contract for hashcode on java.lang.Object */ @SuppressWarnings({"MismatchedQueryAndUpdateOfCollection"}) public void testSomeBadlyWrittenObject() { Set s = new TLinkedHashSet(); boolean didThrow = false; int i = 0; try { for (; i < 101; i++ ) { s.add( new Crap() ); } } catch ( IllegalArgumentException e ) { didThrow = true; } assertTrue( "expected TLinkedHashSet to throw an IllegalArgumentException", didThrow ); } public void testIterable() { Set set = new TLinkedHashSet(); set.add( "One" ); set.add( "Two" ); for ( String s : set ) { assertTrue( s.equals( "One" ) || s.equals( "Two" ) ); } } public void testToString() { Set set = new TLinkedHashSet(); set.add( "One" ); set.add( "Two" ); String to_string = set.toString(); assertTrue( to_string, to_string.equals( "{One, Two}" ) || to_string.equals( "{Two, One}" ) ); } public void testEquals() { String[] strings = {"hi", "bye", "hello", "goodbye"}; Set set = new TLinkedHashSet(); set.addAll( Arrays.asList( strings ) ); Set other = new TLinkedHashSet(); other.addAll( Arrays.asList( strings ) ); assertTrue( "sets incorrectly not equal: " + set + ", " + other, set.equals( other ) ); String[] mismatched = {"heyya", "whassup", "seeya", "blargh"}; Set unequal = new TLinkedHashSet(); unequal.addAll( Arrays.asList( mismatched ) ); assertFalse( "sets incorrectly equal: " + set + ", " + unequal, set.equals( unequal ) ); // Change length, different code branch unequal.add( "whee!" ); assertFalse( "sets incorrectly equal: " + set + ", " + unequal, set.equals( unequal ) ); } public void testEqualsNonSet() { String[] strings = {"hi", "bye", "hello", "goodbye"}; Set set = new TLinkedHashSet(); set.addAll( Arrays.asList( strings ) ); List other = new ArrayList(); other.addAll( Arrays.asList( strings ) ); assertFalse( "sets incorrectly equals list: " + set + ", " + other, set.equals( other ) ); Map map = new HashMap(); for ( String string : strings ) { map.put( string, string ); } assertFalse( "sets incorrectly equals map: " + set + ", " + map, set.equals( map ) ); } public void testHashcode() { String[] strings = {"hi", "bye", "hello", "goodbye"}; Set set = new TLinkedHashSet(); set.addAll( Arrays.asList( strings ) ); Set other = new TLinkedHashSet(); other.addAll( Arrays.asList( strings ) ); assertTrue( "hashcodes incorrectly not equal: " + set + ", " + other, set.hashCode() == other.hashCode() ); String[] mismatched = {"heyya", "whassup", "seeya", "blargh"}; Set unequal = new TLinkedHashSet(); unequal.addAll( Arrays.asList( mismatched ) ); assertFalse( "hashcodes unlikely equal: " + set + ", " + unequal, set.hashCode() == unequal.hashCode() ); } public void testCompact() { int max_size = 10000; int reduced_size = 100; TLinkedHashSet set = new TLinkedHashSet( max_size, 1.0f ); for ( int index = 1; index <= max_size; index++ ) { set.add( Integer.valueOf( index ) ); } assertEquals( max_size, set.size() ); int max_length = set._set.length; for ( int index = max_size; index > reduced_size; index-- ) { set.remove( Integer.valueOf( index ) ); } assertEquals( reduced_size, set.size() ); set.compact(); int compacted_length = set._set.length; assertFalse( max_length + " should != " + compacted_length, max_length == compacted_length ); } public void testDisabledAutoCompact() { int max_size = 10000; int reduced_size = 100; TLinkedHashSet set = new TLinkedHashSet( max_size, 1.0f ); set.setAutoCompactionFactor( 0.0f ); // Disable for ( int index = 1; index <= max_size; index++ ) { set.add( Integer.valueOf( index ) ); } assertEquals( max_size, set.size() ); int max_length = set._set.length; for ( int index = max_size; index > reduced_size; index-- ) { set.remove( Integer.valueOf( index ) ); } assertEquals( reduced_size, set.size() ); int uncompacted_length = set._set.length; assertEquals( max_length, uncompacted_length ); set.compact(); int compacted_length = set._set.length; assertFalse( uncompacted_length + " should != " + compacted_length, uncompacted_length == compacted_length ); } // in this junk class, all instances hash to the same // address, but some objects claim to be equal where // others do not. public static class Crap { public boolean equals( Object other ) { return other instanceof Crap; } public int hashCode() { return System.identityHashCode( this ); } } public static void main( String[] args ) throws Exception { junit.textui.TestRunner.run( new TLinkedHashSetTest( "testBadlyWrittenObject" ) ); } } // TLinkedHashSetTests trove-3.0.3/test/gnu/trove/set/hash/THashSetTest.java0000644000175000017500000004026511763017634021454 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001-2006, Eric D. Friedman All Rights Reserved. // Copyright (c) 2009, Rob Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.set.hash; import junit.framework.TestCase; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.*; /** * Created: Sat Nov 3 10:33:15 2001 * * @author Eric D. Friedman * @author Rob Eden * @author Jeff Randall * @version $Id: THashSetTest.java,v 1.1.2.3 2010/03/02 04:09:50 robeden Exp $ */ public class THashSetTest extends TestCase { public THashSetTest( String name ) { super( name ); } public void setUp() throws Exception { super.setUp(); } public void tearDown() throws Exception { super.tearDown(); } public void testConstructors() throws Exception { Set set = new THashSet(); assertNotNull( set ); String[] strings = {"a", "b", "c", "d"}; set.addAll( Arrays.asList( strings ) ); Set copy = new THashSet( set ); assertTrue( "set not a copy: " + set + ", " + copy, set.equals( copy ) ); Set another = new THashSet( 20 ); another.addAll( Arrays.asList( strings ) ); assertTrue( "set not equal: " + set + ", " + copy, set.equals( another ) ); another = new THashSet( 2, 1.0f ); another.addAll( Arrays.asList( strings ) ); assertTrue( "set not equal: " + set + ", " + copy, set.equals( another ) ); } public void testIsEmpty() throws Exception { Set s = new THashSet(); assertTrue( "new set wasn't empty", s.isEmpty() ); s.add( "One" ); assertTrue( "set with element reports empty", !s.isEmpty() ); s.clear(); assertTrue( "cleared set reports not-empty", s.isEmpty() ); } public void testContains() throws Exception { Set s = new THashSet(); String o = "testContains"; s.add( o ); assertTrue( "contains failed", s.contains( o ) ); } @SuppressWarnings({"ForLoopReplaceableByForEach"}) public void testContainsAll() throws Exception { Set s = new THashSet(); String[] o = {"Hello World", "Goodbye World", "Hello Goodbye"}; s.addAll( Arrays.asList( o ) ); for ( int i = 0; i < o.length; i++ ) { assertTrue( o[i], s.contains( o[i] ) ); } assertTrue( "containsAll failed: " + s, s.containsAll( Arrays.asList( o ) ) ); String[] more = {"Hello World", "Goodbye World", "Hello Goodbye", "Not There"}; assertFalse( "containsAll failed: " + s, s.containsAll( Arrays.asList( more ) ) ); } public void testRetainAll() throws Exception { Set set = new THashSet(); String[] strings = {"Hello World", "Goodbye World", "Hello Goodbye", "Remove Me"}; set.addAll( Arrays.asList( strings ) ); for ( String string : strings ) { assertTrue( string, set.contains( string ) ); } String[] retain = {"Hello World", "Goodbye World", "Hello Goodbye"}; assertTrue( "retainAll failed: " + set, set.retainAll( Arrays.asList( retain ) ) ); assertTrue( "containsAll failed: " + set, set.containsAll( Arrays.asList( retain ) ) ); } public void testRemoveAll() throws Exception { Set set = new THashSet(); String[] strings = {"Hello World", "Goodbye World", "Hello Goodbye", "Keep Me"}; set.addAll( Arrays.asList( strings ) ); for ( String string : strings ) { assertTrue( string, set.contains( string ) ); } String[] remove = {"Hello World", "Goodbye World", "Hello Goodbye"}; assertTrue( "removeAll failed: " + set, set.removeAll( Arrays.asList( remove ) ) ); assertTrue( "removeAll failed: " + set, set.containsAll( Arrays.asList( "Keep Me" ) ) ); for ( String element : remove ) { assertFalse( element + " still in set: " + set, set.contains( element ) ); } assertEquals( 1, set.size() ); } public void testAdd() throws Exception { Set s = new THashSet(); assertTrue( "add failed", s.add( "One" ) ); assertTrue( "duplicated add succeded", !s.add( "One" ) ); } public void testRemove() throws Exception { Set s = new THashSet(); s.add( "One" ); s.add( "Two" ); assertTrue( "One was not added", s.contains( "One" ) ); assertTrue( "One was not removed", s.remove( "One" ) ); assertTrue( "One was not removed", !s.contains( "One" ) ); assertTrue( "Two was removed", s.contains( "Two" ) ); assertEquals( 1, s.size() ); } public void testRemoveObjectNotInSet() throws Exception { Set set = new THashSet(); set.add( "One" ); set.add( "Two" ); assertTrue( "One was not added", set.contains( "One" ) ); assertTrue( "One was not removed", set.remove( "One" ) ); assertTrue( "One was not removed", !set.contains( "One" ) ); assertTrue( "Two was removed", set.contains( "Two" ) ); assertFalse( "Three was removed (non-existant)", set.remove( "Three" ) ); assertEquals( 1, set.size() ); } public void testSize() throws Exception { Set o = new THashSet(); assertEquals( "initial size was not 0", 0, o.size() ); for ( int i = 0; i < 99; i++ ) { o.add( new Object() ); assertEquals( "size did not increase after add", i + 1, o.size() ); } } public void testClear() throws Exception { Set s = new THashSet(); s.addAll( Arrays.asList( "one", "two", "three" ) ); assertEquals( "size was not 3", 3, s.size() ); s.clear(); assertEquals( "initial size was not 0", 0, s.size() ); } public void testSerialize() throws Exception { Set s = new THashSet(); s.addAll( Arrays.asList( "one", "two", "three" ) ); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream( baos ); oos.writeObject( s ); ByteArrayInputStream bais = new ByteArrayInputStream( baos.toByteArray() ); ObjectInputStream ois = new ObjectInputStream( bais ); THashSet s2 = (THashSet) ois.readObject(); assertEquals( s, s2 ); } public void testToArray() { Set s = new THashSet(); String[] str = {"hi", "bye", "hello", "goodbye"}; s.addAll( Arrays.asList( str ) ); Object[] res = s.toArray(); Arrays.sort( str ); Arrays.sort( res ); assertTrue( Arrays.equals( str, res ) ); } public void testToArrayWithParams() { Set s = new THashSet(); String[] str = {"hi", "bye", "hello", "goodbye"}; s.addAll( Arrays.asList( str ) ); String[] sink = new String[str.length + 2]; sink[sink.length - 1] = "residue"; sink[sink.length - 2] = "will be cleared"; String[] res = s.toArray( sink ); Set copy = new HashSet(); copy.addAll( Arrays.asList( res ) ); Set bogey = new HashSet(); bogey.addAll( Arrays.asList( str ) ); bogey.add( "residue" ); bogey.add( null ); assertEquals( bogey, copy ); } @SuppressWarnings({"ToArrayCallWithZeroLengthArrayArgument", "SuspiciousToArrayCall"}) public void testToArrayAnotherType() throws Exception { Set set = new THashSet(); Number[] nums = {1138, 42, 86, 99, 101}; set.addAll( Arrays.asList( nums ) ); Integer[] to_int_array_zero = set.toArray( new Integer[0] ); assertTrue( "set and array mismatch: " + set + ", " + Arrays.asList( to_int_array_zero ), set.containsAll( Arrays.asList( to_int_array_zero ) ) ); Integer[] to_int_array_size = set.toArray( new Integer[set.size()] ); assertTrue( "set and array mismatch: " + set + ", " + Arrays.asList( to_int_array_size ), set.containsAll( Arrays.asList( to_int_array_size ) ) ); Number[] to_num_array_zero = set.toArray( new Number[0] ); assertTrue( "set and array mismatch: " + set + ", " + Arrays.asList( to_num_array_zero ), set.containsAll( Arrays.asList( to_num_array_zero ) ) ); Number[] to_num_array_size = set.toArray( new Number[set.size()] ); assertTrue( "set and array mismatch: " + set + ", " + Arrays.asList( to_num_array_size ), set.containsAll( Arrays.asList( to_num_array_size ) ) ); } @SuppressWarnings({"MismatchedQueryAndUpdateOfCollection"}) public void testRehashing() throws Exception { Set s = new THashSet(); for ( int i = 0; i < 10000; i++ ) { s.add( new Integer( i ) ); } } /** * this tests that we throw when people violate the * general contract for hashcode on java.lang.Object */ @SuppressWarnings({"MismatchedQueryAndUpdateOfCollection"}) public void testSomeBadlyWrittenObject() { Set s = new THashSet(); boolean didThrow = false; int i = 0; try { for (; i < 101; i++ ) { s.add( new Crap() ); } } catch ( IllegalArgumentException e ) { didThrow = true; } assertTrue( "expected THashSet to throw an IllegalArgumentException", didThrow ); } public void testIterable() { Set set = new THashSet(); set.add( "One" ); set.add( "Two" ); for ( String s : set ) { assertTrue( s.equals( "One" ) || s.equals( "Two" ) ); } } public void testToString() { Set set = new THashSet(); set.add( "One" ); set.add( "Two" ); String to_string = set.toString(); assertTrue( to_string, to_string.equals( "{One, Two}" ) || to_string.equals( "{Two, One}" ) ); } public void testEquals() { String[] strings = {"hi", "bye", "hello", "goodbye"}; Set set = new THashSet(); set.addAll( Arrays.asList( strings ) ); Set other = new THashSet(); other.addAll( Arrays.asList( strings ) ); assertTrue( "sets incorrectly not equal: " + set + ", " + other, set.equals( other ) ); String[] mismatched = {"heyya", "whassup", "seeya", "blargh"}; Set unequal = new THashSet(); unequal.addAll( Arrays.asList( mismatched ) ); assertFalse( "sets incorrectly equal: " + set + ", " + unequal, set.equals( unequal ) ); // Change length, different code branch unequal.add( "whee!" ); assertFalse( "sets incorrectly equal: " + set + ", " + unequal, set.equals( unequal ) ); } public void testEqualsNonSet() { String[] strings = {"hi", "bye", "hello", "goodbye"}; Set set = new THashSet(); set.addAll( Arrays.asList( strings ) ); List other = new ArrayList(); other.addAll( Arrays.asList( strings ) ); assertFalse( "sets incorrectly equals list: " + set + ", " + other, set.equals( other ) ); Map map = new HashMap(); for ( String string : strings ) { map.put( string, string ); } assertFalse( "sets incorrectly equals map: " + set + ", " + map, set.equals( map ) ); } public void testHashcode() { String[] strings = {"hi", "bye", "hello", "goodbye"}; Set set = new THashSet(); set.addAll( Arrays.asList( strings ) ); Set other = new THashSet(); other.addAll( Arrays.asList( strings ) ); assertTrue( "hashcodes incorrectly not equal: " + set + ", " + other, set.hashCode() == other.hashCode() ); String[] mismatched = {"heyya", "whassup", "seeya", "blargh"}; Set unequal = new THashSet(); unequal.addAll( Arrays.asList( mismatched ) ); assertFalse( "hashcodes unlikely equal: " + set + ", " + unequal, set.hashCode() == unequal.hashCode() ); } public void testCompact() { int max_size = 10000; int reduced_size = 100; THashSet set = new THashSet( max_size, 1.0f ); for ( int index = 1; index <= max_size; index++ ) { set.add( Integer.valueOf( index ) ); } assertEquals( max_size, set.size() ); int max_length = set._set.length; for ( int index = max_size; index > reduced_size; index-- ) { set.remove( Integer.valueOf( index ) ); } assertEquals( reduced_size, set.size() ); set.compact(); int compacted_length = set._set.length; assertFalse( max_length + " should != " + compacted_length, max_length == compacted_length ); } public void testDisabledAutoCompact() { int max_size = 10000; int reduced_size = 100; THashSet set = new THashSet( max_size, 1.0f ); set.setAutoCompactionFactor( 0.0f ); // Disable for ( int index = 1; index <= max_size; index++ ) { set.add( Integer.valueOf( index ) ); } assertEquals( max_size, set.size() ); int max_length = set._set.length; for ( int index = max_size; index > reduced_size; index-- ) { set.remove( Integer.valueOf( index ) ); } assertEquals( reduced_size, set.size() ); int uncompacted_length = set._set.length; assertEquals( max_length, uncompacted_length ); set.compact(); int compacted_length = set._set.length; assertFalse( uncompacted_length + " should != " + compacted_length, uncompacted_length == compacted_length ); } // in this junk class, all instances hash to the same // address, but some objects claim to be equal where // others do not. public static class Crap { public boolean equals( Object other ) { return other instanceof Crap; } public int hashCode() { return System.identityHashCode( this ); } } public static void main( String[] args ) throws Exception { junit.textui.TestRunner.run( new THashSetTest( "testBadlyWrittenObject" ) ); } } // THashSetTests trove-3.0.3/test/gnu/trove/set/hash/TCustomHashSetTest.java0000644000175000017500000000414111763017634022640 0ustar ericherichpackage gnu.trove.set.hash; import gnu.trove.strategy.HashingStrategy; import gnu.trove.map.hash.ArrayHashingStrategy; import junit.framework.TestCase; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Set; /** * */ public class TCustomHashSetTest extends TestCase { public void testArray() { char[] foo = new char[] { 'a', 'b', 'c' }; char[] bar = new char[] { 'a', 'b', 'c' }; assertFalse( foo.hashCode() == bar.hashCode() ); //noinspection ArrayEquals assertFalse( foo.equals( bar ) ); HashingStrategy strategy = new ArrayHashingStrategy(); assertTrue( strategy.computeHashCode( foo ) == strategy.computeHashCode( bar ) ); assertTrue( strategy.equals( foo, bar ) ); Set set = new TCustomHashSet( strategy ); set.add( foo ); assertTrue( set.contains( foo ) ); assertTrue( set.contains( bar ) ); set.remove( bar ); assertTrue( set.isEmpty() ); } public void testSerialization() throws Exception { char[] foo = new char[] { 'a', 'b', 'c' }; char[] bar = new char[] { 'a', 'b', 'c' }; HashingStrategy strategy = new ArrayHashingStrategy(); Set set = new TCustomHashSet( strategy ); set.add( foo ); // Make sure it still works after being serialized ObjectOutputStream oout = null; ByteArrayOutputStream bout = null; ObjectInputStream oin = null; ByteArrayInputStream bin = null; try { bout = new ByteArrayOutputStream(); oout = new ObjectOutputStream( bout ); oout.writeObject( set ); bin = new ByteArrayInputStream( bout.toByteArray() ); oin = new ObjectInputStream( bin ); set = ( Set ) oin.readObject(); } finally { if ( oin != null ) oin.close(); if ( bin != null ) bin.close(); if ( oout != null ) oout.close(); if ( bout != null ) bout.close(); } assertTrue( set.contains( foo ) ); assertTrue( set.contains( bar ) ); set.remove( bar ); assertTrue( set.isEmpty() ); } } trove-3.0.3/test/gnu/trove/stack/0000755000175000017500000000000011763017634015646 5ustar ericherichtrove-3.0.3/test/gnu/trove/stack/array/0000755000175000017500000000000012000515265016750 5ustar ericherichtrove-3.0.3/test/gnu/trove/stack/array/TStackTest.java0000644000175000017500000001624311763017634021666 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001, Eric D. Friedman All Rights Reserved. // Copyright (c) 2009, Rob Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.stack.array; import gnu.trove.list.array.TIntArrayList; import gnu.trove.stack.TIntStack; import junit.framework.TestCase; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; /** * */ public class TStackTest extends TestCase { public TStackTest() { super(); } public TStackTest( String string ) { super( string ); } public void testConstructors() { TIntStack stack = new TIntArrayStack(); assertEquals( 0, stack.size() ); stack.push( 10 ); stack.push( 20 ); assertEquals( 2, stack.size() ); TIntStack other = new TIntArrayStack( 20 ); other.push( 10 ); other.push( 20 ); assertEquals( 2, other.size() ); assertTrue( "stacks should be equal: " + stack + ", " + other, stack.equals( other ) ); TIntStack copy = new TIntArrayStack( stack ); assertTrue( "stacks should be equal: " + stack + ", " + copy, stack.equals( copy ) ); } public void testBasic() { TIntStack stack = new TIntArrayStack(); assertEquals( 0, stack.size() ); stack.push( 10 ); assertEquals( 1, stack.size() ); assertEquals( 10, stack.peek() ); assertEquals( 1, stack.size() ); assertEquals( 10, stack.peek() ); assertEquals( 1, stack.size() ); assertEquals( 10, stack.pop() ); assertEquals( 0, stack.size() ); stack.push( 10 ); stack.push( 20 ); stack.push( 30 ); assertEquals( 3, stack.size() ); assertEquals( 30, stack.pop() ); assertEquals( 20, stack.pop() ); assertEquals( 10, stack.pop() ); } public void testArrays() { int no_entry_value = Integer.MIN_VALUE; TIntStack stack = new TIntArrayStack(10, no_entry_value); assertEquals( no_entry_value, stack.getNoEntryValue() ); int[] array; array = stack.toArray(); assertNotNull( array ); assertEquals( 0, array.length ); stack.push( 10 ); stack.push( 20 ); stack.push( 30 ); stack.push( 40 ); array = stack.toArray(); assertNotNull( array ); assertEquals( 4, array.length ); // NOTE: Top element in stack should be first element in array assertEquals( 40, array[0] ); assertEquals( 30, array[1] ); assertEquals( 20, array[2] ); assertEquals( 10, array[3] ); assertEquals( 4, stack.size() ); int[] array_correct_size = new int[4]; stack.toArray( array_correct_size ); assertEquals( 40, array_correct_size[0] ); assertEquals( 30, array_correct_size[1] ); assertEquals( 20, array_correct_size[2] ); assertEquals( 10, array_correct_size[3] ); int[] array_too_long = new int[6]; stack.toArray( array_too_long ); assertEquals( 40, array_too_long[0] ); assertEquals( 30, array_too_long[1] ); assertEquals( 20, array_too_long[2] ); assertEquals( 10, array_too_long[3] ); assertEquals( stack.getNoEntryValue(), array_too_long[4] ); int[] array_too_short = new int[2]; stack.toArray( array_too_short ); assertEquals( 40, array_too_short[0] ); assertEquals( 30, array_too_short[1] ); } public void testClear() { TIntStack stack = new TIntArrayStack(); assertEquals( 0, stack.size() ); stack.push( 10 ); assertEquals( 1, stack.size() ); assertEquals( 10, stack.pop() ); assertEquals( 0, stack.size() ); stack.push( 10 ); stack.push( 20 ); stack.push( 30 ); assertEquals( 3, stack.size() ); stack.clear(); assertEquals( 0, stack.size() ); } public void testEquals() { TIntStack stack = new TIntArrayStack(); assertEquals( 0, stack.size() ); stack.push( 10 ); stack.push( 20 ); assertEquals( 2, stack.size() ); TIntStack other = new TIntArrayStack( 20 ); other.push( 10 ); other.push( 20 ); assertEquals( 2, other.size() ); assertTrue( "stacks should equal itself: " + stack, stack.equals( stack ) ); assertTrue( "stacks should be equal: " + stack + ", " + other, stack.equals( other ) ); TIntArrayList list = new TIntArrayList( stack.toArray() ); assertFalse( "stack should not equal list: " + stack + ", " + list, stack.equals( list ) ); } public void testHashCode() { TIntStack stack = new TIntArrayStack(); assertEquals( 0, stack.size() ); stack.push( 10 ); stack.push( 20 ); assertEquals( 2, stack.size() ); TIntStack other = new TIntArrayStack( 20 ); other.push( 10 ); other.push( 20 ); assertEquals( 2, other.size() ); assertTrue( "stack hashcode should equal itself: " + stack, stack.hashCode() == stack.hashCode() ); assertTrue( "stacks should be equal: " + stack + ", " + other, stack.hashCode() == other.hashCode() ); other.push( 30 ); assertFalse( "stack should not equal list: " + stack + ", " + other, stack.hashCode() == other.hashCode() ); } public void testSerialize() throws Exception { TIntStack stack = new TIntArrayStack(); stack.push( 10 ); stack.push( 20 ); stack.push( 30 ); stack.push( 40 ); stack.push( 50 ); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream( baos ); oos.writeObject( stack ); ByteArrayInputStream bais = new ByteArrayInputStream( baos.toByteArray() ); ObjectInputStream ois = new ObjectInputStream( bais ); TIntStack serialized = (TIntStack) ois.readObject(); assertEquals( stack, serialized ); } } trove-3.0.3/test/gnu/trove/map/0000755000175000017500000000000011763017634015316 5ustar ericherichtrove-3.0.3/test/gnu/trove/map/hash/0000755000175000017500000000000012000515265016225 5ustar ericherichtrove-3.0.3/test/gnu/trove/map/hash/TPrimitiveObjectHashMapTest.java0000644000175000017500000021316211763017634024436 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001-2006, Eric D. Friedman All Rights Reserved. // Copyright (c) 2009, Rob Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.map.hash; import gnu.trove.TIntCollection; import gnu.trove.function.TObjectFunction; import gnu.trove.iterator.TIntIterator; import gnu.trove.iterator.TIntObjectIterator; import gnu.trove.list.TIntList; import gnu.trove.list.array.TIntArrayList; import gnu.trove.map.TIntObjectMap; import gnu.trove.procedure.TIntObjectProcedure; import gnu.trove.procedure.TIntProcedure; import gnu.trove.procedure.TObjectProcedure; import gnu.trove.set.TIntSet; import gnu.trove.set.hash.TIntHashSet; import junit.framework.TestCase; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.*; /** * */ public class TPrimitiveObjectHashMapTest extends TestCase { public TPrimitiveObjectHashMapTest( String name ) { super( name ); } public void testBug2975214() { TIntObjectHashMap map = new TIntObjectHashMap( 5 ); for ( int i = 0; i < 9; i++ ) { System.out.println( "Pass: " + i ); map.put( i, new Integer( i ) ); map.remove( i ); } } public void testConstructors() { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; TIntObjectMap map = new TIntObjectHashMap(); for ( int i = 0; i < element_count; i++ ) { keys[i] = i + 1; vals[i] = Integer.toString( i + 1 ); map.put( keys[i], vals[i] ); } TIntObjectMap capacity = new TIntObjectHashMap( 20 ); for ( int i = 0; i < element_count; i++ ) { capacity.put( keys[i], vals[i] ); } assertEquals( map, capacity ); TIntObjectMap cap_and_factor = new TIntObjectHashMap( 20, 0.75f ); for ( int i = 0; i < element_count; i++ ) { cap_and_factor.put( keys[i], vals[i] ); } assertEquals( map, cap_and_factor ); TIntObjectMap fully_specified = new TIntObjectHashMap( 20, 0.75f, Integer.MIN_VALUE ); for ( int i = 0; i < element_count; i++ ) { fully_specified.put( keys[i], vals[i] ); } assertEquals( map, fully_specified ); TIntObjectMap copy = new TIntObjectHashMap( map ); assertEquals( map, copy ); } public void testContainsKey() { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; TIntObjectMap map = new TIntObjectHashMap(); for ( int i = 0; i < element_count; i++ ) { keys[i] = i + 1; vals[i] = Integer.toString( i + 1 ); map.put( keys[i], vals[i] ); } for ( int i = 0; i < element_count; i++ ) { assertTrue( "Key should be present: " + keys[i] + ", map: " + map, map.containsKey( keys[i] ) ); } int key = 1138; assertFalse( "Key should not be present: " + key + ", map: " + map, map.containsKey( key ) ); } public void testContainsValue() { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; TIntObjectMap map = new TIntObjectHashMap(); for ( int i = 0; i < element_count; i++ ) { keys[i] = i + 1; vals[i] = Integer.toString( i + 1 ); map.put( keys[i], vals[i] ); } for ( int i = 0; i < element_count; i++ ) { assertTrue( "Value should be present: " + vals[i] + ", map: " + map, map.containsValue( vals[i] ) ); } String val = "1138"; assertFalse( "Key should not be present: " + val + ", map: " + map, map.containsValue( val ) ); assertFalse( "Random object should not be present in map: " + map, map.containsValue( new Object() ) ); // test with null value int key = 11010110; map.put( key, null ); assertTrue( map.containsKey( key ) ); assertTrue( map.containsValue( null ) ); assertNull( map.get( key ) ); } public void testPutIfAbsent() { TIntObjectMap map = new TIntObjectHashMap(); map.put( 1, "One" ); map.put( 2, "Two" ); map.put( 3, "Three" ); assertEquals( "One", map.putIfAbsent( 1, "Two" ) ); assertEquals( "One", map.get( 1 ) ); assertEquals( null, map.putIfAbsent( 9, "Nine") ); assertEquals( "Nine", map.get( 9 ) ); } public void testRemove() { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; TIntObjectMap map = new TIntObjectHashMap(); for ( int i = 0; i < element_count; i++ ) { keys[i] = i + 1; vals[i] = Integer.toString( i + 1 ); map.put( keys[i], vals[i] ); } for ( int i = 0; i < element_count; i++ ) { if ( i % 2 == 1 ) { assertEquals( "Remove should have modified map: " + keys[i] + ", map: " + map, vals[i], map.remove( keys[i] ) ); } } for ( int i = 0; i < element_count; i++ ) { if ( i % 2 == 1 ) { assertTrue( "Removed key still in map: " + keys[i] + ", map: " + map, map.get( keys[i] ) == null ); } else { assertTrue( "Key should still be in map: " + keys[i] + ", map: " + map, map.get( keys[i] ).equals( vals[i] ) ); } } } public void testPutAllMap() { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; TIntObjectMap control = new TIntObjectHashMap(); for ( int i = 0; i < element_count; i++ ) { keys[i] = i + 1; vals[i] = Integer.toString( i + 1 ); control.put( keys[i], vals[i] ); } TIntObjectMap map = new TIntObjectHashMap(); Map source = new HashMap(); for ( int i = 0; i < element_count; i++ ) { source.put( keys[i], vals[i] ); } map.putAll( source ); assertEquals( control, map ); } public void testPutAll() throws Exception { TIntObjectMap t = new TIntObjectHashMap(); TIntObjectMap m = new TIntObjectHashMap(); m.put( 2, "one" ); m.put( 4, "two" ); m.put( 6, "three" ); t.put( 5, "four" ); assertEquals( 1, t.size() ); t.putAll( m ); assertEquals( 4, t.size() ); assertEquals( "two", t.get( 4 ) ); } public void testClear() { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; TIntObjectMap map = new TIntObjectHashMap(); for ( int i = 0; i < element_count; i++ ) { keys[i] = i + 1; vals[i] = Integer.toString( i + 1 ); map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); map.clear(); assertTrue( map.isEmpty() ); assertEquals( 0, map.size() ); assertNull( map.get( keys[5] ) ); } public void testKeySet() { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; TIntObjectMap map = new TIntObjectHashMap(); for ( int i = 0; i < element_count; i++ ) { keys[i] = i + 1; vals[i] = Integer.toString( i + 1 ); map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); TIntSet keyset = map.keySet(); for ( int i = 0; i < keyset.size(); i++ ) { assertTrue( keyset.contains( keys[i] ) ); } assertFalse( keyset.isEmpty() ); int[] keys_array = keyset.toArray(); int count = 0; TIntIterator iter = keyset.iterator(); while ( iter.hasNext() ) { int key = iter.next(); assertTrue( keyset.contains( key ) ); assertEquals( keys_array[count], key ); count++; } //noinspection ToArrayCallWithZeroLengthArrayArgument keys_array = keyset.toArray( new int[0] ); count = 0; iter = keyset.iterator(); while ( iter.hasNext() ) { int key = iter.next(); assertTrue( keyset.contains( key ) ); assertEquals( keys_array[count], key ); count++; } keys_array = keyset.toArray( new int[keyset.size()] ); count = 0; iter = keyset.iterator(); while ( iter.hasNext() ) { int key = iter.next(); assertTrue( keyset.contains( key ) ); assertEquals( keys_array[count], key ); count++; } keys_array = keyset.toArray( new int[keyset.size() * 2] ); count = 0; iter = keyset.iterator(); while ( iter.hasNext() ) { int key = iter.next(); assertTrue( keyset.contains( key ) ); assertEquals( keys_array[count], key ); count++; } assertEquals( keyset.getNoEntryValue(), keys_array[keyset.size()] ); TIntSet other = new TIntHashSet( keyset ); assertFalse( keyset.retainAll( other ) ); other.remove( keys[5] ); assertTrue( keyset.retainAll( other ) ); assertFalse( keyset.contains( keys[5] ) ); assertFalse( map.containsKey( keys[5] ) ); keyset.clear(); assertTrue( keyset.isEmpty() ); } public void testKeySetAdds() { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; TIntObjectMap map = new TIntObjectHashMap(); for ( int i = 0; i < element_count; i++ ) { keys[i] = i + 1; vals[i] = Integer.toString( i + 1 ); map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); TIntSet keyset = map.keySet(); for ( int i = 0; i < keyset.size(); i++ ) { assertTrue( keyset.contains( keys[i] ) ); } assertFalse( keyset.isEmpty() ); try { keyset.add( 1138 ); fail( "Expected UnsupportedOperationException" ); } catch ( UnsupportedOperationException ex ) { // Expected } try { Set test = new HashSet(); test.add( Integer.valueOf( 1138 ) ); keyset.addAll( test ); fail( "Expected UnsupportedOperationException" ); } catch ( UnsupportedOperationException ex ) { // Expected } try { TIntSet test = new TIntHashSet(); test.add( 1138 ); keyset.addAll( test ); fail( "Expected UnsupportedOperationException" ); } catch ( UnsupportedOperationException ex ) { // Expected } try { int[] test = { 1138 }; keyset.addAll( test ); fail( "Expected UnsupportedOperationException" ); } catch ( UnsupportedOperationException ex ) { // Expected } } public void testKeySetContainsAllCollection() { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; TIntObjectMap map = new TIntObjectHashMap(); for ( int i = 0; i < element_count; i++ ) { keys[i] = i + 1; vals[i] = Integer.toString( i + 1 ); map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); TIntSet keyset = map.keySet(); for ( int i = 0; i < keyset.size(); i++ ) { assertTrue( keyset.contains( keys[i] ) ); } assertFalse( keyset.isEmpty() ); Collection test_collection = new HashSet(); for ( int i = 0; i < element_count; i++ ) { test_collection.add( keys[i] ); } assertTrue( keyset.containsAll( test_collection ) ) ; test_collection.remove( Integer.valueOf( keys[5] ) ); assertTrue( "should contain all. keyset: " + keyset + ", " + test_collection, keyset.containsAll( test_collection ) ); test_collection.add( Integer.valueOf( 1138 ) ); assertFalse( "should not contain all. keyset: " + keyset + ", " + test_collection, keyset.containsAll( test_collection ) ); } public void testKeySetContainsAllTCollection() { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; TIntObjectMap map = new TIntObjectHashMap(); for ( int i = 0; i < element_count; i++ ) { keys[i] = i + 1; vals[i] = Integer.toString( i + 1 ); map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); TIntSet keyset = map.keySet(); for ( int i = 0; i < keyset.size(); i++ ) { assertTrue( keyset.contains( keys[i] ) ); } assertFalse( keyset.isEmpty() ); TIntCollection test_collection = new TIntHashSet(); for ( int i = 0; i < element_count; i++ ) { test_collection.add( keys[i] ); } assertTrue( keyset.containsAll( test_collection ) ) ; assertTrue( keyset.equals( keyset ) ); test_collection.remove( Integer.valueOf( keys[5] ) ); assertTrue( "should contain all. keyset: " + keyset + ", " + test_collection, keyset.containsAll( test_collection ) ); test_collection.add( 1138 ); assertFalse( "should not contain all. keyset: " + keyset + ", " + test_collection, keyset.containsAll( test_collection ) ); } public void testKeySetContainsAllArray() { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; TIntObjectMap map = new TIntObjectHashMap(); for ( int i = 0; i < element_count; i++ ) { keys[i] = i + 1; vals[i] = Integer.toString( i + 1 ); map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); TIntSet keyset = map.keySet(); for ( int i = 0; i < keyset.size(); i++ ) { assertTrue( keyset.contains( keys[i] ) ); } assertFalse( keyset.isEmpty() ); assertTrue( "should contain all. keyset: " + keyset + ", " + Arrays.toString( keys ), keyset.containsAll( keys ) ); int[] other_array = new int[ keys.length + 1 ]; System.arraycopy( keys, 0, other_array, 0, keys.length ); other_array[other_array.length - 1] = 1138; assertFalse( "should not contain all. keyset: " + keyset + ", " + Arrays.toString( other_array ), keyset.containsAll( other_array ) ); } public void testKeySetRetainAllCollection() { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; TIntObjectMap map = new TIntObjectHashMap(); for ( int i = 0; i < element_count; i++ ) { keys[i] = i + 1; vals[i] = Integer.toString( i + 1 ); map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); TIntSet keyset = map.keySet(); for ( int i = 0; i < keyset.size(); i++ ) { assertTrue( keyset.contains( keys[i] ) ); } assertFalse( keyset.isEmpty() ); Collection test_collection = new HashSet(); for ( int i = 0; i < element_count; i++ ) { test_collection.add( keys[i] ); } keyset.retainAll( test_collection ); assertFalse( keyset.isEmpty() ); assertFalse( map.isEmpty() ); // Reset map for ( int i = 0; i < element_count; i++ ) { map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); test_collection.remove( Integer.valueOf( keys[5] ) ); keyset.retainAll( test_collection ); assertEquals( element_count - 1, keyset.size() ); assertEquals( element_count - 1, map.size() ); assertFalse( keyset.contains( keys[5] ) ); assertFalse( map.containsKey( keys[5] ) ); // Reset map for ( int i = 0; i < element_count; i++ ) { map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); test_collection.add( Integer.valueOf( 1138 ) ); keyset.retainAll( test_collection ); } public void testKeySetRetainAllTCollection() { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; TIntObjectMap map = new TIntObjectHashMap(); for ( int i = 0; i < element_count; i++ ) { keys[i] = i + 1; vals[i] = Integer.toString( i + 1 ); map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); TIntSet keyset = map.keySet(); for ( int i = 0; i < keyset.size(); i++ ) { assertTrue( keyset.contains( keys[i] ) ); } assertFalse( keyset.isEmpty() ); assertFalse( "keyset: " + keyset + ", should be unmodified.", keyset.retainAll( keyset ) ); TIntCollection other = new TIntArrayList( keyset ); assertFalse( "keyset: " + keyset + ", should be unmodified. other: " + other, keyset.retainAll( other ) ); other.remove( keys[5] ); assertTrue( "keyset: " + keyset + ", should be modified. other: " + other, keyset.retainAll( other ) ); assertFalse( keyset.contains( keys[5] ) ); assertFalse( map.containsKey( keys[5] ) ); assertFalse( map.containsValue( vals[5] ) ); assertTrue( "keyset: " + keyset + ", should contain all in other: " + other, keyset.containsAll( other ) ); } public void testKeySetRetainAllArray() { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; TIntObjectMap map = new TIntObjectHashMap(); for ( int i = 0; i < element_count; i++ ) { keys[i] = i + 1; vals[i] = Integer.toString( i + 1 ); map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); TIntSet keyset = map.keySet(); for ( int i = 0; i < keyset.size(); i++ ) { assertTrue( keyset.contains( keys[i] ) ); } assertFalse( keyset.isEmpty() ); assertFalse( "keyset: " + keyset + ", should be unmodified. array: " + Arrays.toString( keys ), keyset.retainAll( keys ) ); int[] other = new int[element_count - 1]; for ( int i = 0; i < element_count; i++ ) { if ( i < 5 ) { other[i] = i + 1; } if ( i > 5 ) { other[i - 1] = i + 1; } } assertTrue( "keyset: " + keyset + ", should be modified. array: " + Arrays.toString( other ), keyset.retainAll( other ) ); } public void testKeySetRemoveAllCollection() { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; TIntObjectMap map = new TIntObjectHashMap(); for ( int i = 0; i < element_count; i++ ) { keys[i] = i + 1; vals[i] = Integer.toString( i + 1 ); map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); TIntCollection keyset = map.keySet(); for ( int i = 0; i < keyset.size(); i++ ) { assertTrue( keyset.contains( keys[i] ) ); } assertFalse( keyset.isEmpty() ); List java_list = new ArrayList(); assertFalse( "collection: " + keyset + ", should contain all in list: " + java_list, keyset.removeAll( java_list ) ); java_list.add( keys[5] ); assertTrue( "collection: " + keyset + ", should contain all in list: " + java_list, keyset.removeAll( java_list ) ); assertFalse( keyset.contains( keys[5] ) ); assertFalse( map.containsKey( keys[5] ) ); assertFalse( map.containsValue( vals[5] ) ); java_list = new ArrayList(); for ( int key : keys ) { java_list.add( key ); } assertTrue( "collection: " + keyset + ", should contain all in list: " + java_list, keyset.removeAll( java_list ) ); assertTrue( keyset.isEmpty() ); } public void testKeySetRemoveAllTCollection() { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; TIntObjectMap map = new TIntObjectHashMap(); for ( int i = 0; i < element_count; i++ ) { keys[i] = i + 1; vals[i] = Integer.toString( i + 1 ); map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); TIntCollection keyset = map.keySet(); for ( int i = 0; i < keyset.size(); i++ ) { assertTrue( keyset.contains( keys[i] ) ); } assertFalse( keyset.isEmpty() ); TIntCollection other = new TIntArrayList(); assertFalse( "collection: " + keyset + ", should be unmodified.", keyset.removeAll( other ) ); other = new TIntArrayList( keyset ); other.remove( keys[5] ); assertTrue( "collection: " + keyset + ", should be modified. other: " + other, keyset.removeAll( other ) ); assertEquals( 1, keyset.size() ); for ( int i = 0; i < element_count; i++ ) { if ( i == 5 ) { assertTrue( keyset.contains( keys[i] ) ); assertTrue( map.containsKey( keys[i] ) ); assertTrue( map.containsValue( vals[i] ) ); } else { assertFalse( keyset.contains( keys[i] ) ); assertFalse( map.containsKey( keys[i] ) ); assertFalse( map.containsValue( vals[i] ) ); } } assertFalse( "collection: " + keyset + ", should be unmodified. other: " + other, keyset.removeAll( other ) ); assertTrue( "collection: " + keyset + ", should be modified. other: " + other, keyset.removeAll( keyset ) ); assertTrue( keyset.isEmpty() ); } public void testKeySetRemoveAllArray() { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; TIntObjectMap map = new TIntObjectHashMap(); for ( int i = 0; i < element_count; i++ ) { keys[i] = i + 1; vals[i] = Integer.toString( i + 1 ); map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); TIntCollection keyset = map.keySet(); for ( int i = 0; i < keyset.size(); i++ ) { assertTrue( keyset.contains( keys[i] ) ); } assertFalse( keyset.isEmpty() ); int[] other = {1138}; assertFalse( "collection: " + keyset + ", should be unmodified. array: " + Arrays.toString( vals ), keyset.removeAll( other ) ); other = new int[element_count - 1]; for ( int i = 0; i < element_count; i++ ) { if ( i < 5 ) { other[i] = i + 1; } if ( i > 5 ) { other[i - 1] = i + 1; } } assertTrue( "collection: " + keyset + ", should be modified. array: " + Arrays.toString( other ), keyset.removeAll( other ) ); assertEquals( 1, keyset.size() ); for ( int i = 0; i < element_count; i++ ) { if ( i == 5 ) { assertTrue( keyset.contains( keys[i] ) ); assertTrue( map.containsKey( keys[i] ) ); assertTrue( map.containsValue( vals[i] ) ); } else { assertFalse( keyset.contains( keys[i] ) ); assertFalse( map.containsKey( keys[i] ) ); assertFalse( map.containsValue( vals[i] ) ); } } } public void testKeySetEqual() { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; TIntObjectMap map = new TIntObjectHashMap(); for ( int i = 0; i < element_count; i++ ) { keys[i] = i + 1; vals[i] = Integer.toString( i + 1 ); map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); TIntSet keyset = map.keySet(); for ( int i = 0; i < keyset.size(); i++ ) { assertTrue( keyset.contains( keys[i] ) ); } assertFalse( keyset.isEmpty() ); TIntSet other = new TIntHashSet(); other.addAll( keys ); assertTrue( "sets incorrectly not equal: " + keyset + ", " + other, keyset.equals( other ) ); int[] mismatched = {72, 49, 53, 1024, 999}; TIntSet unequal = new TIntHashSet(); unequal.addAll( mismatched ); assertFalse( "sets incorrectly equal: " + keyset + ", " + unequal, keyset.equals( unequal ) ); // Change length, different code branch unequal.add( 1 ); assertFalse( "sets incorrectly equal: " + keyset + ", " + unequal, keyset.equals( unequal ) ); //noinspection ObjectEqualsNull assertFalse( keyset.equals( null ) ); } public void testKeySetHashCode() { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; TIntObjectMap map = new TIntObjectHashMap(); for ( int i = 0; i < element_count; i++ ) { keys[i] = i + 1; vals[i] = Integer.toString( i + 1 ); map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); TIntSet keyset = map.keySet(); for ( int i = 0; i < keyset.size(); i++ ) { assertTrue( keyset.contains( keys[i] ) ); } assertFalse( keyset.isEmpty() ); assertEquals( keyset.hashCode(), keyset.hashCode() ); TIntSet other = new TIntHashSet( keys ); other.add( 1138 ); assertTrue( keyset.hashCode() != other.hashCode() ); } public void testKeys() { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; TIntObjectMap map = new TIntObjectHashMap(); for ( int i = 0; i < element_count; i++ ) { keys[i] = i + 1; vals[i] = Integer.toString( i + 1 ); map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); // No argument int[] keys_array = map.keys(); assertEquals( element_count, keys_array.length ); TIntList keys_list = new TIntArrayList( keys_array ); for ( int i = 0; i < element_count; i++ ) { assertTrue( keys_list.contains( keys[i] ) ); } // Zero length array keys_array = map.keys( new int[0] ); assertEquals( element_count, keys_array.length ); keys_list = new TIntArrayList( keys_array ); for ( int i = 0; i < element_count; i++ ) { assertTrue( keys_list.contains( keys[i] ) ); } // appropriate length array keys_array = map.keys( new int[map.size()] ); assertEquals( element_count, keys_array.length ); keys_list = new TIntArrayList( keys_array ); for ( int i = 0; i < element_count; i++ ) { assertTrue( keys_list.contains( keys[i] ) ); } // longer array keys_array = map.keys( new int[element_count * 2] ); assertEquals( element_count * 2, keys_array.length ); keys_list = new TIntArrayList( keys_array ); for ( int i = 0; i < element_count; i++ ) { assertTrue( keys_list.contains( keys[i] ) ); } assertEquals( map.getNoEntryKey(), keys_array[element_count] ); } @SuppressWarnings({"ToArrayCallWithZeroLengthArrayArgument"}) public void testValueCollectionToArray() { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; TIntObjectMap map = new TIntObjectHashMap(); for ( int i = 0; i < element_count; i++ ) { keys[i] = i + 1; vals[i] = Integer.toString( i + 1 ); map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); Collection collection = map.valueCollection(); for ( int i = 0; i < collection.size(); i++ ) { assertTrue( collection.contains( vals[i] ) ); } assertFalse( collection.isEmpty() ); Object[] values_array = collection.toArray(); int count = 0; Iterator iter = collection.iterator(); while ( iter.hasNext() ) { String value = iter.next(); assertTrue( collection.contains( value ) ); assertEquals( values_array[count], value ); count++; } values_array = collection.toArray( new String[0] ); count = 0; iter = collection.iterator(); while ( iter.hasNext() ) { String value = iter.next(); assertTrue( collection.contains( value ) ); assertEquals( values_array[count], value ); count++; } values_array = collection.toArray( new String[collection.size()] ); count = 0; iter = collection.iterator(); while ( iter.hasNext() ) { String value = iter.next(); assertTrue( collection.contains( value ) ); assertEquals( values_array[count], value ); count++; } values_array = collection.toArray( new String[collection.size() * 2] ); count = 0; iter = collection.iterator(); while ( iter.hasNext() ) { String value = iter.next(); assertTrue( collection.contains( value ) ); assertEquals( values_array[count], value ); count++; } assertNull( values_array[collection.size()] ); assertNull( values_array[collection.size()] ); Collection other = new ArrayList( collection ); assertFalse( collection.retainAll( other ) ); other.remove( vals[5] ); assertTrue( collection.retainAll( other ) ); assertFalse( collection.contains( vals[5] ) ); assertFalse( map.containsKey( keys[5] ) ); collection.clear(); assertTrue( collection.isEmpty() ); } public void testValueCollectionAdds() { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; TIntObjectMap map = new TIntObjectHashMap(); for ( int i = 0; i < element_count; i++ ) { keys[i] = i + 1; vals[i] = Integer.toString( i + 1 ); map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); Collection collection = map.valueCollection(); for ( int i = 0; i < collection.size(); i++ ) { assertTrue( collection.contains( vals[i] ) ); } assertFalse( collection.isEmpty() ); try { collection.add( "1138" ); fail( "Expected UnsupportedOperationException" ); } catch ( UnsupportedOperationException ex ) { // Expected } try { Set test = new HashSet(); test.add( "1138" ); collection.addAll( test ); fail( "Expected UnsupportedOperationException" ); } catch ( UnsupportedOperationException ex ) { // Expected } try { Collection test = new ArrayList(); test.add( "1138" ); collection.addAll( test ); fail( "Expected UnsupportedOperationException" ); } catch ( UnsupportedOperationException ex ) { // Expected } try { collection.addAll( Arrays.asList( vals ) ); fail( "Expected UnsupportedOperationException" ); } catch ( UnsupportedOperationException ex ) { // Expected } } public void testValueCollectionContainsAll() { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; TIntObjectMap map = new TIntObjectHashMap(); for ( int i = 0; i < element_count; i++ ) { keys[i] = i + 1; vals[i] = Integer.toString( i + 1 ); map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); Collection collection = map.valueCollection(); for ( int i = 0; i < collection.size(); i++ ) { assertTrue( collection.contains( vals[i] ) ); } assertFalse( collection.isEmpty() ); List java_list = new ArrayList(); java_list.addAll( Arrays.asList( vals ) ); assertTrue( "collection: " + collection + ", should contain all in list: " + java_list, collection.containsAll( java_list ) ); java_list.add( String.valueOf( 1138 ) ); assertFalse( "collection: " + collection + ", should not contain all in list: " + java_list, collection.containsAll( java_list ) ); List number_list = new ArrayList(); for ( String value : vals ) { if ( value.equals( "5" ) ) { number_list.add( new StringBuilder().append( value ) ); } else { number_list.add( String.valueOf( value ) ); } } assertFalse( "collection: " + collection + ", should not contain all in list: " + java_list, collection.containsAll( number_list ) ); Collection other = new ArrayList( collection ); assertTrue( "collection: " + collection + ", should contain all in other: " + other, collection.containsAll( other ) ); other.add( "1138" ); assertFalse( "collection: " + collection + ", should not contain all in other: " + other, collection.containsAll( other ) ); } public void testValueCollectionRetainAllCollection() { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; TIntObjectMap map = new TIntObjectHashMap(); for ( int i = 0; i < element_count; i++ ) { keys[i] = i + 1; vals[i] = Integer.toString( i + 1 ); map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); Collection collection = map.valueCollection(); for ( int i = 0; i < collection.size(); i++ ) { assertTrue( collection.contains( vals[i] ) ); } assertFalse( collection.isEmpty() ); List java_list = new ArrayList(); java_list.addAll( Arrays.asList( vals ) ); assertFalse( "collection: " + collection + ", should contain all in list: " + java_list, collection.retainAll( java_list ) ); java_list.remove( 5 ); assertTrue( "collection: " + collection + ", should contain all in list: " + java_list, collection.retainAll( java_list ) ); assertFalse( collection.contains( vals[5] ) ); assertFalse( map.containsKey( keys[5] ) ); assertFalse( map.containsValue( vals[5] ) ); assertTrue( "collection: " + collection + ", should contain all in list: " + java_list, collection.containsAll( java_list ) ); } public void testValueCollectionRetainAllTCollection() { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; TIntObjectMap map = new TIntObjectHashMap(); for ( int i = 0; i < element_count; i++ ) { keys[i] = i + 1; vals[i] = Integer.toString( i + 1 ); map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); Collection collection = map.valueCollection(); for ( int i = 0; i < collection.size(); i++ ) { assertTrue( collection.contains( vals[i] ) ); } assertFalse( collection.isEmpty() ); assertFalse( "collection: " + collection + ", should be unmodified.", collection.retainAll( collection ) ); Collection other = new ArrayList( collection ); assertFalse( "collection: " + collection + ", should be unmodified. other: " + other, collection.retainAll( other ) ); other.remove( vals[5] ); assertTrue( "collection: " + collection + ", should be modified. other: " + other, collection.retainAll( other ) ); assertFalse( collection.contains( vals[5] ) ); assertFalse( map.containsKey( keys[5] ) ); assertFalse( map.containsValue( vals[5] ) ); assertTrue( "collection: " + collection + ", should contain all in other: " + other, collection.containsAll( other ) ); } public void testValueCollectionRemoveAllCollection() { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; TIntObjectMap map = new TIntObjectHashMap(); for ( int i = 0; i < element_count; i++ ) { keys[i] = i + 1; vals[i] = Integer.toString( i + 1 ); map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); Collection collection = map.valueCollection(); for ( int i = 0; i < collection.size(); i++ ) { assertTrue( collection.contains( vals[i] ) ); } assertFalse( collection.isEmpty() ); List java_list = new ArrayList(); assertFalse( "collection: " + collection + ", should contain all in list: " + java_list, collection.removeAll( java_list ) ); java_list.add( vals[5] ); assertTrue( "collection: " + collection + ", should contain all in list: " + java_list, collection.removeAll( java_list ) ); assertFalse( collection.contains( vals[5] ) ); assertFalse( map.containsKey( keys[5] ) ); assertFalse( map.containsValue( vals[5] ) ); java_list = new ArrayList(); java_list.addAll( Arrays.asList( vals ) ); assertTrue( "collection: " + collection + ", should contain all in list: " + java_list, collection.removeAll( java_list ) ); assertTrue( collection.isEmpty() ); } public void testValueCollectionRemoveAllTCollection() { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; TIntObjectMap map = new TIntObjectHashMap(); for ( int i = 0; i < element_count; i++ ) { keys[i] = i + 1; vals[i] = Integer.toString( i + 1 ); map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); Collection collection = map.valueCollection(); for ( int i = 0; i < collection.size(); i++ ) { assertTrue( collection.contains( vals[i] ) ); } assertFalse( collection.isEmpty() ); Collection other = new ArrayList(); assertFalse( "collection: " + collection + ", should be unmodified.", collection.removeAll( other ) ); other = new ArrayList( collection ); other.remove( vals[5] ); assertTrue( "collection: " + collection + ", should be modified. other: " + other, collection.removeAll( other ) ); assertEquals( 1, collection.size() ); for ( int i = 0; i < element_count; i++ ) { if ( i == 5 ) { assertTrue( collection.contains( vals[i] ) ); assertTrue( map.containsKey( keys[i] ) ); assertTrue( map.containsValue( vals[i] ) ); } else { assertFalse( collection.contains( vals[i] ) ); assertFalse( map.containsKey( keys[i] ) ); assertFalse( map.containsValue( vals[i] ) ); } } assertFalse( "collection: " + collection + ", should be unmodified. other: " + other, collection.removeAll( other ) ); assertTrue( "collection: " + collection + ", should be modified. other: " + other, collection.removeAll( collection ) ); assertTrue( collection.isEmpty() ); } public void testValues() { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; TIntObjectMap map = new TIntObjectHashMap(); for ( int i = 0; i < element_count; i++ ) { keys[i] = i + 1; vals[i] = Integer.toString( i + 1 ); map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); // No argument Object[] values_object_array = map.values(); assertEquals( element_count, values_object_array.length ); List values_object_list = Arrays.asList( values_object_array ); for ( int i = 0; i < element_count; i++ ) { assertTrue( values_object_list.contains( vals[i] ) ); } // Zero length array String[] values_array = map.values( new String[0] ); assertEquals( element_count, values_array.length ); List values_list = Arrays.asList( values_array ); for ( int i = 0; i < element_count; i++ ) { assertTrue( values_list.contains( vals[i] ) ); } // appropriate length array values_array = map.values( new String[map.size()] ); assertEquals( element_count, values_array.length ); values_list = Arrays.asList( values_array ); for ( int i = 0; i < element_count; i++ ) { assertTrue( values_list.contains( vals[i] ) ); } // longer array values_array = map.values( new String[element_count * 2] ); assertEquals( element_count * 2, values_array.length ); values_list = Arrays.asList( values_array ); for ( int i = 0; i < element_count; i++ ) { assertTrue( values_list.contains( vals[i] ) ); } assertEquals( null, values_array[element_count] ); } public void testIterator() { TIntObjectHashMap map = new TIntObjectHashMap(); TIntObjectIterator iterator = map.iterator(); assertFalse( iterator.hasNext() ); map.put( 1, "one" ); map.put( 2, "two" ); iterator = map.iterator(); assertTrue( iterator.hasNext() ); iterator.advance(); int first_key = iterator.key(); assertNotNull( "key was null", first_key ); assertTrue( "invalid key: " + first_key, first_key == 1 || first_key == 2 ); if ( first_key == 1 ) { assertEquals( "one", iterator.value() ); } else { assertEquals( "two", iterator.value() ); } assertTrue( iterator.hasNext() ); iterator.advance(); int second_key = iterator.key(); assertNotNull( "key was null", second_key ); assertTrue( "invalid key: " + second_key, second_key == 1 || second_key == 2 ); if ( second_key == 1 ) { assertEquals( "one", iterator.value() ); } else { assertEquals( "two", iterator.value() ); } assertFalse( first_key + ", " + second_key, first_key == second_key ); assertFalse( iterator.hasNext() ); // New Iterator iterator = map.iterator(); iterator.advance(); first_key = iterator.key(); iterator.setValue( "1138" ); assertEquals( "1138", iterator.value() ); assertEquals( "1138", map.get( first_key ) ); } public void testIteratorRemoval() { TIntObjectHashMap map = new TIntObjectHashMap(); map.put( 1, "one" ); map.put( 2, "two" ); map.put( 3, "three" ); map.put( 4, "four" ); map.put( 5, "five" ); map.put( 6, "six" ); map.put( 7, "seven" ); map.put( 8, "eight" ); map.put( 9, "nine" ); map.put( 10, "ten" ); TIntObjectIterator iterator = map.iterator(); while ( map.size() > 5 && iterator.hasNext() ) { iterator.advance(); int key = iterator.key(); iterator.remove(); assertFalse( "map still contains key: " + key, map.containsKey( key ) ); } assertEquals( 5, map.size() ); iterator = map.iterator(); assertTrue( iterator.hasNext() ); iterator.advance(); assertTrue( iterator.hasNext() ); iterator.advance(); assertTrue( iterator.hasNext() ); iterator.advance(); assertTrue( iterator.hasNext() ); iterator.advance(); assertTrue( iterator.hasNext() ); iterator.advance(); assertFalse( iterator.hasNext() ); iterator = map.iterator(); int elements = map.size(); while ( iterator.hasNext() ) { iterator.advance(); int key = iterator.key(); iterator.remove(); assertFalse( "map still contains key: " + key, map.containsKey( key ) ); elements--; } assertEquals( 0, elements ); assertEquals( 0, map.size() ); assertTrue( map.isEmpty() ); } public void testIteratorRemoval2() { int element_count = 10000; int remaining = element_count / 2; TIntObjectHashMap map = new TIntObjectHashMap( element_count, 0.5f, Integer.MIN_VALUE ); for ( int pass = 0; pass < 10; pass++ ) { Random r = new Random(); for ( int i = 0; i <= element_count; i++ ) { map.put( Integer.valueOf( r.nextInt() ), String.valueOf( i ) ); } TIntObjectIterator iterator = map.iterator(); while ( map.size() > remaining && iterator.hasNext() ) { iterator.advance(); iterator.remove(); } } } public void testForEachKey() { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; TIntObjectMap map = new TIntObjectHashMap( element_count, 0.5f, Integer.MIN_VALUE ); for ( int i = 0; i < element_count; i++ ) { keys[i] = i + 1; vals[i] = Integer.toString( i + 1 ); map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); class ForEach implements TIntProcedure { TIntList built = new TIntArrayList(); public boolean execute( int value ) { built.add( value ); return true; } TIntList getBuilt() { return built; } } ForEach foreach = new ForEach(); map.forEachKey( foreach ); TIntList built = foreach.getBuilt(); TIntList keys_list = new TIntArrayList( map.keys( new int[map.size()] ) ); assertEquals( keys_list, built ); built.sort(); keys_list.sort(); assertEquals( keys_list, built ); class ForEachFalse implements TIntProcedure { TIntList built = new TIntArrayList(); public boolean execute( int value ) { built.add( value ); return false; } TIntList getBuilt() { return built; } } ForEachFalse foreach_false = new ForEachFalse(); map.forEachKey( foreach_false ); built = foreach_false.getBuilt(); keys_list = new TIntArrayList( map.keys( new int[map.size()] ) ); assertEquals( 1, built.size() ); assertEquals( keys_list.get( 0 ), built.get( 0 ) ); } public void testForEachValue() { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; TIntObjectMap map = new TIntObjectHashMap( element_count, 0.5f, Integer.MIN_VALUE ); for ( int i = 0; i < element_count; i++ ) { keys[i] = i + 1; vals[i] = Integer.toString( i + 1 ); map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); class ForEach implements TObjectProcedure { List built = new ArrayList(); public boolean execute( String value ) { built.add( value ); return true; } List getBuilt() { return built; } } ForEach foreach = new ForEach(); map.forEachValue( foreach ); List built = foreach.getBuilt(); List values = Arrays.asList( map.values( new String[ 0 ] ) ); assertEquals( values, built ); Collections.sort( built ); Collections.sort( values ); assertEquals( values, built ); class ForEachFalse implements TObjectProcedure { List built = new ArrayList(); public boolean execute( String value ) { built.add( value ); return false; } List getBuilt() { return built; } } ForEachFalse foreach_false = new ForEachFalse(); map.forEachValue( foreach_false ); built = foreach_false.getBuilt(); values = Arrays.asList( map.values( new String[ 0 ] ) ); assertEquals( 1, built.size() ); assertEquals( values.get( 0 ), built.get( 0 ) ); } public void testForEachEntry() { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; TIntObjectMap map = new TIntObjectHashMap( element_count, 0.5f, Integer.MIN_VALUE ); for ( int i = 0; i < element_count; i++ ) { keys[i] = i + 1; vals[i] = Integer.toString( i + 1 ); map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); class ForEach implements TIntObjectProcedure { TIntObjectMap built = new TIntObjectHashMap(); public boolean execute( int key, String value ) { built.put( key, value ); return true; } TIntObjectMap getBuilt() { return built; } } ForEach foreach = new ForEach(); map.forEachEntry( foreach ); TIntObjectMap built = foreach.getBuilt(); assertEquals( map, built ); class ForEachFalse implements TIntObjectProcedure { TIntObjectMap built = new TIntObjectHashMap(); public boolean execute( int key, String value ) { built.put( key, value ); return false; } TIntObjectMap getBuilt() { return built; } } ForEachFalse foreach_false = new ForEachFalse(); map.forEachEntry( foreach_false ); built = foreach_false.getBuilt(); assertEquals( 1, built.size() ); assertTrue( map.containsKey( built.keys()[0] ) ); assertTrue( map.containsValue( built.values( new String[0] )[0] ) ); } public void testRetain() { TIntObjectHashMap map = new TIntObjectHashMap(); map.put( 1, "one" ); map.put( 2, "two" ); map.put( 3, "three" ); map.put( 4, "four" ); map.put( 5, "five" ); map.put( 6, "six" ); map.put( 7, "seven" ); map.put( 8, "eight" ); map.put( 9, "nine" ); map.put( 10, "ten" ); map.retainEntries( new TIntObjectProcedure() { public boolean execute( int a, String b ) { return a > 5 && a <= 8; } } ); assertEquals( 3, map.size() ); assertFalse( map.containsValue( "one" ) ); assertFalse( map.containsValue( "two" ) ); assertFalse( map.containsValue( "three" ) ); assertFalse( map.containsValue( "four" ) ); assertFalse( map.containsValue( "five" ) ); assertTrue( map.containsValue( "six" ) ); assertTrue( map.containsValue( "seven" ) ); assertTrue( map.containsValue( "eight" ) ); assertFalse( map.containsValue( "nine" ) ); assertFalse( map.containsValue( "ten" ) ); map.put( 11, "eleven" ); map.put( 12, "twelve" ); map.put( 13, "thirteen" ); map.put( 14, "fourteen" ); map.put( 15, "fifteen" ); map.put( 16, "sixteen" ); map.put( 17, "seventeen" ); map.put( 18, "eighteen" ); map.put( 19, "nineteen" ); map.put( 20, "twenty" ); map.retainEntries( new TIntObjectProcedure() { public boolean execute( int a, String b ) { return a > 15; } } ); assertEquals( 5, map.size() ); assertFalse( map.containsValue( "one" ) ); assertFalse( map.containsValue( "two" ) ); assertFalse( map.containsValue( "three" ) ); assertFalse( map.containsValue( "four" ) ); assertFalse( map.containsValue( "five" ) ); assertFalse( map.containsValue( "six" ) ); assertFalse( map.containsValue( "seven" ) ); assertFalse( map.containsValue( "eight" ) ); assertFalse( map.containsValue( "nine" ) ); assertFalse( map.containsValue( "ten" ) ); assertFalse( map.containsValue( "eleven" ) ); assertFalse( map.containsValue( "twelve" ) ); assertFalse( map.containsValue( "thirteen" ) ); assertFalse( map.containsValue( "fourteen" ) ); assertFalse( map.containsValue( "fifteen" ) ); assertTrue( map.containsValue( "sixteen" ) ); assertTrue( map.containsValue( "seventeen" ) ); assertTrue( map.containsValue( "eighteen" ) ); assertTrue( map.containsValue( "nineteen" ) ); assertTrue( map.containsValue( "twenty" ) ); map.retainEntries( new TIntObjectProcedure() { public boolean execute( int a, String b ) { return false; } } ); assertEquals( 0, map.size() ); } public void testTransformValues() { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; TIntObjectMap map = new TIntObjectHashMap( element_count, 0.5f, Integer.MIN_VALUE ); for ( int i = 0; i < element_count; i++ ) { keys[i] = i + 1; vals[i] = Integer.toString( i + 1 ); map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); map.transformValues( new TObjectFunction() { public String execute( String value ) { return value + "/" + value; } } ); for ( int i = 0; i < element_count; i++ ) { String expected = vals[i] + "/" + vals[i]; assertEquals( expected, map.get( keys[i] ) ); } } public void testEquals() { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; TIntObjectMap map = new TIntObjectHashMap( element_count, 0.5f, Integer.MIN_VALUE ); for ( int i = 0; i < element_count; i++ ) { keys[i] = i + 1; vals[i] = Integer.toString( i + 1 ); map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); TIntObjectHashMap fully_specified = new TIntObjectHashMap( 20, 0.75f, Integer.MIN_VALUE ); for ( int i = 0; i < element_count; i++ ) { fully_specified.put( keys[i], vals[i] ); } assertEquals( map, fully_specified ); assertFalse( "shouldn't equal random object", map.equals( new Object() ) ); int key = 11010110; // I thought I saw a two! assertNull( map.put( key, null ) ); assertNull( fully_specified.put( key, null ) ); assertTrue( "incorrectly not-equal map: " + map + "\nfully_specified: " + fully_specified, map.equals( fully_specified ) ); assertTrue( "incorrectly not-equal map: " + map + "\nfully_specified: " + fully_specified, fully_specified.equals( map ) ); assertNull( fully_specified.put( key, "non-null-value" ) ); assertFalse( "incorrectly equal map: " + map + "\nfully_specified: " + fully_specified, map.equals( fully_specified ) ); assertFalse( "incorrectly equal map: " + map + "\nfully_specified: " + fully_specified, fully_specified.equals( map ) ); assertNull( fully_specified.put( key + 1, "blargh" ) ); assertFalse( "incorrectly equal map: " + map + "\nfully_specified: " + fully_specified, map.equals( fully_specified ) ); } public void testHashCode() { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; int counter = 0; TIntObjectMap map = new TIntObjectHashMap( element_count, 0.5f, Integer.MIN_VALUE ); for ( int i = 0; i < element_count; i++, counter++ ) { keys[i] = counter + 1; vals[i] = Integer.toString( counter + 1 ); map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); assertEquals( map.hashCode(), map.hashCode() ); Map> string_tmap_map = new HashMap>(); string_tmap_map.put( "first", map ); string_tmap_map.put( "second", map ); assertSame( map, string_tmap_map.get( "first" ) ); assertSame( map, string_tmap_map.get( "second" ) ); TIntObjectMap map2 = new TIntObjectHashMap( element_count, 0.5f, Integer.MIN_VALUE ); for ( int i = 0; i < element_count; i++, counter++ ) { keys[i] = counter + 1; vals[i] = Integer.toString( counter + 1 ); map2.put( keys[i], vals[i] ); } assertEquals( element_count, map2.size() ); assertEquals( map2.hashCode(), map2.hashCode() ); TIntObjectMap map3 = new TIntObjectHashMap( element_count, 0.5f, Integer.MIN_VALUE ); for ( int i = 0; i < element_count; i++, counter++ ) { keys[i] = counter + 1; vals[i] = Integer.toString( counter + 1 ); map3.put( keys[i], vals[i] ); } assertEquals( element_count, map3.size() ); assertEquals( map3.hashCode(), map3.hashCode() ); assertFalse( "hashcodes are unlikely equal. map: " + map + " (" + map.hashCode() + ")\nmap2: " + map2 + " (" + map2.hashCode() + ")", map.hashCode() == map2.hashCode() ); assertFalse( "hashcodes are unlikely equal. map: " + map + " (" + map.hashCode() + ")\nmap3: " + map3 + " (" + map3.hashCode() + ")", map.hashCode() == map3.hashCode() ); assertFalse( "hashcodes are unlikely equal. map2: " + map2 + " (" + map2.hashCode() + ")\nmap3: " + map3 + " (" + map3.hashCode() + ")", map2.hashCode() == map3.hashCode() ); Map, String> tmap_string_map = new HashMap, String>(); tmap_string_map.put( map, "map1" ); tmap_string_map.put( map2, "map2" ); tmap_string_map.put( map3, "map3" ); assertEquals( "map1", tmap_string_map.get( map ) ); assertEquals( "map2", tmap_string_map.get( map2 ) ); assertEquals( "map3", tmap_string_map.get( map3 ) ); } @SuppressWarnings({"unchecked"}) public void testSerialize() throws Exception { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; TIntObjectMap map = new TIntObjectHashMap(); for ( int i = 0; i < element_count; i++ ) { keys[i] = i + 1; vals[i] = Integer.toString( i + 1 ); map.put( keys[i], vals[i] ); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream( baos ); oos.writeObject( map ); ByteArrayInputStream bias = new ByteArrayInputStream( baos.toByteArray() ); ObjectInputStream ois = new ObjectInputStream( bias ); TIntObjectMap deserialized = (TIntObjectMap) ois.readObject(); assertEquals( map, deserialized ); } public void testToString() { TIntObjectHashMap m = new TIntObjectHashMap(); m.put( 11, "One" ); m.put( 22, "Two" ); String to_string = m.toString(); assertTrue( to_string, to_string.equals( "{11=One,22=Two}" ) || to_string.equals( "{22=Two,11=One}" ) ); } /** * Test for tracking issue #1204014. +0.0 and -0.0 have different bit patterns, but * should be counted the same as keys in a map. Checks for doubles and floats. */ public void testFloatZeroHashing() { TDoubleObjectHashMap po_double_map = new TDoubleObjectHashMap(); TDoubleIntHashMap pp_double_map = new TDoubleIntHashMap(); TFloatObjectHashMap po_float_map = new TFloatObjectHashMap(); TFloatIntHashMap pp_float_map = new TFloatIntHashMap(); final double zero_double = 0.0; final double negative_zero_double = -zero_double; final float zero_float = 0.0f; final float negative_zero_float = -zero_float; // Sanity check... make sure I'm really creating two different values. final String zero_bits_double = Long.toBinaryString( Double.doubleToLongBits( zero_double ) ); final String negative_zero_bits_double = Long.toBinaryString( Double.doubleToLongBits( negative_zero_double ) ); assertFalse( zero_bits_double + " == " + negative_zero_bits_double, zero_bits_double.equals( negative_zero_bits_double ) ); final String zero_bits_float = Integer.toBinaryString( Float.floatToIntBits( zero_float ) ); final String negative_zero_bits_float = Integer.toBinaryString( Float.floatToIntBits( negative_zero_float ) ); assertFalse( zero_bits_float + " == " + negative_zero_bits_float, zero_bits_float.equals( negative_zero_bits_float ) ); po_double_map.put( zero_double, "Zero" ); po_double_map.put( negative_zero_double, "Negative Zero" ); pp_double_map.put( zero_double, 0 ); pp_double_map.put( negative_zero_double, -1 ); po_float_map.put( zero_float, "Zero" ); po_float_map.put( negative_zero_float, "Negative Zero" ); pp_float_map.put( zero_float, 0 ); pp_float_map.put( negative_zero_float, -1 ); assertEquals( 1, po_double_map.size() ); assertEquals( po_double_map.get( zero_double ), "Negative Zero" ); assertEquals( po_double_map.get( negative_zero_double ), "Negative Zero" ); assertEquals( 1, pp_double_map.size() ); assertEquals( pp_double_map.get( zero_double ), -1 ); assertEquals( pp_double_map.get( negative_zero_double ), -1 ); assertEquals( 1, po_float_map.size() ); assertEquals( po_float_map.get( zero_float ), "Negative Zero" ); assertEquals( po_float_map.get( negative_zero_float ), "Negative Zero" ); assertEquals( 1, pp_float_map.size() ); assertEquals( pp_float_map.get( zero_float ), -1 ); assertEquals( pp_float_map.get( negative_zero_float ), -1 ); po_double_map.put( zero_double, "Zero" ); pp_double_map.put( zero_double, 0 ); po_float_map.put( zero_float, "Zero" ); pp_float_map.put( zero_float, 0 ); assertEquals( 1, po_double_map.size() ); assertEquals( po_double_map.get( zero_double ), "Zero" ); assertEquals( po_double_map.get( negative_zero_double ), "Zero" ); assertEquals( 1, pp_double_map.size() ); assertEquals( pp_double_map.get( zero_double ), 0 ); assertEquals( pp_double_map.get( negative_zero_double ), 0 ); assertEquals( 1, po_float_map.size() ); assertEquals( po_float_map.get( zero_float ), "Zero" ); assertEquals( po_float_map.get( negative_zero_float ), "Zero" ); assertEquals( 1, pp_float_map.size() ); assertEquals( pp_float_map.get( zero_float ), 0 ); assertEquals( pp_float_map.get( negative_zero_float ), 0 ); } // Testing issue from: // https://sourceforge.net/projects/trove4j/forums/forum/121845/topic/4969032 public void testForumIssue_20120124() { TIntObjectHashMap string_map = new TIntObjectHashMap(); string_map.put( 1, "one" ); string_map.put( 2, "two" ); string_map.put( 3, "three" ); int count = 0; for ( final String string : string_map.values( new String[ 0 ] ) ) { count++; } assertEquals( 3, count ); } } trove-3.0.3/test/gnu/trove/map/hash/ArrayHashingStrategy.java0000644000175000017500000000063411763017634023212 0ustar ericherichpackage gnu.trove.map.hash; import gnu.trove.strategy.HashingStrategy; import java.io.Serializable; import java.util.Arrays; /** * */ public class ArrayHashingStrategy implements HashingStrategy, Serializable { public int computeHashCode( char[] o ) { return Arrays.hashCode( o ); } public boolean equals( char[] o1, char[] o2 ) { return Arrays.equals( o1, o2 ); } } trove-3.0.3/test/gnu/trove/map/hash/TObjectPrimitiveHashMapTest.java0000644000175000017500000016046311763017634024443 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001-2006, Eric D. Friedman All Rights Reserved. // Copyright (c) 2009, Rob Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.map.hash; import gnu.trove.TIntCollection; import gnu.trove.function.TIntFunction; import gnu.trove.iterator.TIntIterator; import gnu.trove.iterator.TObjectIntIterator; import gnu.trove.list.TIntList; import gnu.trove.list.array.TIntArrayList; import gnu.trove.map.TObjectIntMap; import gnu.trove.procedure.TIntProcedure; import gnu.trove.procedure.TObjectIntProcedure; import gnu.trove.procedure.TObjectProcedure; import junit.framework.TestCase; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.*; /** * */ public class TObjectPrimitiveHashMapTest extends TestCase { public TObjectPrimitiveHashMapTest( String name ) { super( name ); } public void testConstructors() { int element_count = 20; String[] keys = new String[element_count]; int[] vals = new int[element_count]; TObjectIntMap map = new TObjectIntHashMap(); for ( int i = 0; i < element_count; i++ ) { keys[i] = Integer.toString( i + 1 ); vals[i] = i + 1; map.put( keys[i], vals[i] ); } TObjectIntHashMap capacity = new TObjectIntHashMap( 20 ); for ( int i = 0; i < element_count; i++ ) { capacity.put( keys[i], vals[i] ); } assertEquals( map, capacity ); TObjectIntHashMap cap_and_factor = new TObjectIntHashMap( 20, 0.75f ); for ( int i = 0; i < element_count; i++ ) { cap_and_factor.put( keys[i], vals[i] ); } assertEquals( map, cap_and_factor ); TObjectIntHashMap fully_specified = new TObjectIntHashMap( 20, 0.75f, Integer.MIN_VALUE ); for ( int i = 0; i < element_count; i++ ) { fully_specified.put( keys[i], vals[i] ); } assertEquals( map, fully_specified ); TObjectIntHashMap copy = new TObjectIntHashMap( fully_specified ); assertEquals( map, copy ); } public void testContainsKey() { int element_count = 20; String[] keys = new String[element_count]; int[] vals = new int[element_count]; TObjectIntMap map = new TObjectIntHashMap(); for ( int i = 0; i < element_count; i++ ) { keys[i] = Integer.toString( i + 1 ); vals[i] = i + 1; map.put( keys[i], vals[i] ); } for ( int i = 0; i < element_count; i++ ) { assertTrue( "Key should be present: " + keys[i] + ", map: " + map, map.containsKey( keys[i] ) ); } String key = "1138"; assertFalse( "Key should not be present: " + key + ", map: " + map, map.containsKey( key ) ); assertFalse( "Random object should not be present in map: " + map, map.containsKey( new Object() ) ); } public void testContainsValue() { int element_count = 20; String[] keys = new String[element_count]; int[] vals = new int[element_count]; TObjectIntMap map = new TObjectIntHashMap(); for ( int i = 0; i < element_count; i++ ) { keys[i] = Integer.toString( i + 1 ); vals[i] = i + 1; map.put( keys[i], vals[i] ); } for ( int i = 0; i < element_count; i++ ) { assertTrue( "Value should be present: " + vals[i] + ", map: " + map, map.containsValue( vals[i] ) ); } int val = 1138; assertFalse( "Key should not be present: " + val + ", map: " + map, map.containsValue( val ) ); } public void testPutIfAbsent() { TObjectIntHashMap map = new TObjectIntHashMap(); map.put( "One", 1 ); map.put( "Two", 2 ); map.put( "Three", 3 ); assertEquals( 1, map.putIfAbsent( "One", 2 ) ); assertEquals( 1, map.get( "One" ) ); assertEquals( 0, map.putIfAbsent( "Nine", 9 ) ); assertEquals( 9, map.get( "Nine" ) ); } public void testRemove() { int element_count = 20; String[] keys = new String[element_count]; int[] vals = new int[element_count]; TObjectIntMap map = new TObjectIntHashMap(); for ( int i = 0; i < element_count; i++ ) { keys[i] = Integer.toString( i + 1 ); vals[i] = i + 1; map.put( keys[i], vals[i] ); } for ( int i = 0; i < element_count; i++ ) { if ( i % 2 == 1 ) { assertEquals( "Remove should have modified map: " + keys[i] + ", map: " + map, vals[i], map.remove( keys[i] ) ); } } for ( int i = 0; i < element_count; i++ ) { if ( i % 2 == 1 ) { assertTrue( "Removed key still in map: " + keys[i] + ", map: " + map, map.get( keys[i] ) == map.getNoEntryValue() ); } else { assertTrue( "Key should still be in map: " + keys[i] + ", map: " + map, map.get( keys[i] ) == vals[i] ); } } } public void testPutAllMap() { int element_count = 20; String[] keys = new String[element_count]; int[] vals = new int[element_count]; TObjectIntMap control = new TObjectIntHashMap(); for ( int i = 0; i < element_count; i++ ) { keys[i] = Integer.toString( i + 1 ); vals[i] = i + 1; control.put( keys[i], vals[i] ); } TObjectIntMap map = new TObjectIntHashMap(); Map source = new HashMap(); for ( int i = 0; i < element_count; i++ ) { source.put( keys[i], vals[i] ); } map.putAll( source ); assertEquals( control, map ); } public void testPutAll() throws Exception { TObjectIntHashMap t = new TObjectIntHashMap(); TObjectIntHashMap m = new TObjectIntHashMap(); m.put( "one", 2 ); m.put( "two", 4 ); m.put( "three", 6 ); t.put( "four", 5 ); assertEquals( 1, t.size() ); t.putAll( m ); assertEquals( 4, t.size() ); assertEquals( 4, t.get( "two" ) ); } public void testClear() { int element_count = 20; String[] keys = new String[element_count]; int[] vals = new int[element_count]; TObjectIntMap map = new TObjectIntHashMap(); for ( int i = 0; i < element_count; i++ ) { keys[i] = Integer.toString( i + 1 ); vals[i] = i + 1; map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); map.clear(); assertTrue( map.isEmpty() ); assertEquals( 0, map.size() ); assertEquals( map.getNoEntryValue(), map.get( keys[5] ) ); } @SuppressWarnings({"ToArrayCallWithZeroLengthArrayArgument"}) public void testKeySet() { int element_count = 20; String[] keys = new String[element_count]; int[] vals = new int[element_count]; TObjectIntMap map = new TObjectIntHashMap(); for ( int i = 0; i < element_count; i++ ) { keys[i] = Integer.toString( i + 1 ); vals[i] = i + 1; map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); Set keyset = map.keySet(); for ( int i = 0; i < keyset.size(); i++ ) { assertTrue( keyset.contains( keys[i] ) ); } assertFalse( keyset.isEmpty() ); Object[] keys_obj_array = keyset.toArray(); int count = 0; Iterator iter = keyset.iterator(); while ( iter.hasNext() ) { String key = iter.next(); assertTrue( keyset.contains( key ) ); assertEquals( keys_obj_array[count], key ); count++; } String[] keys_array = keyset.toArray( new String[0] ); count = 0; iter = keyset.iterator(); while ( iter.hasNext() ) { String key = iter.next(); assertTrue( keyset.contains( key ) ); assertEquals( keys_array[count], key ); count++; } keys_array = keyset.toArray( new String[keyset.size()] ); count = 0; iter = keyset.iterator(); while ( iter.hasNext() ) { String key = iter.next(); assertTrue( keyset.contains( key ) ); assertEquals( keys_array[count], key ); count++; } keys_array = keyset.toArray( new String[keyset.size() * 2] ); count = 0; iter = keyset.iterator(); while ( iter.hasNext() ) { String key = iter.next(); assertTrue( keyset.contains( key ) ); assertEquals( keys_array[count], key ); count++; } assertNull( keys_array[keyset.size()] ); Set other = new HashSet( keyset ); assertFalse( keyset.retainAll( other ) ); other.remove( keys[5] ); assertTrue( keyset.retainAll( other ) ); assertFalse( keyset.contains( keys[5] ) ); assertFalse( map.containsKey( keys[5] ) ); keyset.clear(); assertTrue( keyset.isEmpty() ); } public void testKeySetAdds() { int element_count = 20; String[] keys = new String[element_count]; int[] vals = new int[element_count]; TObjectIntMap map = new TObjectIntHashMap(); for ( int i = 0; i < element_count; i++ ) { keys[i] = Integer.toString( i + 1 ); vals[i] = i + 1; map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); Set keyset = map.keySet(); for ( int i = 0; i < keyset.size(); i++ ) { assertTrue( keyset.contains( keys[i] ) ); } assertFalse( keyset.isEmpty() ); try { keyset.add( "explosions!" ); fail( "Expected UnsupportedOperationException" ); } catch ( UnsupportedOperationException ex ) { // Expected } try { Set test = new HashSet(); test.add( "explosions!" ); keyset.addAll( test ); fail( "Expected UnsupportedOperationException" ); } catch ( UnsupportedOperationException ex ) { // Expected } } public void testKeys() { int element_count = 20; String[] keys = new String[element_count]; int[] vals = new int[element_count]; TObjectIntMap map = new TObjectIntHashMap(); for ( int i = 0; i < element_count; i++ ) { keys[i] = Integer.toString( i + 1 ); vals[i] = i + 1; map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); // No argument Object[] keys_object_array = map.keys(); assertEquals( element_count, keys_object_array.length ); List keys_object_list = Arrays.asList( keys_object_array ); for ( int i = 0; i < element_count; i++ ) { assertTrue( keys_object_list.contains( keys[i] ) ); } // Zero length array String[] keys_string_array = map.keys( new String[0] ); assertEquals( element_count, keys_string_array.length ); List keys_string_list = Arrays.asList( keys_string_array ); for ( int i = 0; i < element_count; i++ ) { assertTrue( keys_string_list.contains( keys[i] ) ); } // appropriate length array keys_string_array = map.keys( new String[map.size()] ); assertEquals( element_count, keys_string_array.length ); keys_string_list = Arrays.asList( keys_string_array ); for ( int i = 0; i < element_count; i++ ) { assertTrue( keys_string_list.contains( keys[i] ) ); } // longer array keys_string_array = map.keys( new String[element_count * 2] ); assertEquals( element_count * 2, keys_string_array.length ); keys_string_list = Arrays.asList( keys_string_array ); for ( int i = 0; i < element_count; i++ ) { assertTrue( keys_string_list.contains( keys[i] ) ); } assertNull( keys_string_array[element_count] ); } public void testValueCollectionToArray() { int element_count = 20; String[] keys = new String[element_count]; int[] vals = new int[element_count]; TObjectIntMap map = new TObjectIntHashMap( element_count, 0.5f, Integer.MIN_VALUE ); for ( int i = 0; i < element_count; i++ ) { keys[i] = Integer.toString( i + 1 ); vals[i] = i + 1; map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); TIntCollection collection = map.valueCollection(); for ( int i = 0; i < collection.size(); i++ ) { assertTrue( collection.contains( vals[i] ) ); } assertFalse( collection.isEmpty() ); int[] values_array = collection.toArray(); int count = 0; TIntIterator iter = collection.iterator(); while ( iter.hasNext() ) { int value = iter.next(); assertTrue( collection.contains( value ) ); assertEquals( values_array[count], value ); count++; } values_array = collection.toArray( new int[0] ); count = 0; iter = collection.iterator(); while ( iter.hasNext() ) { int value = iter.next(); assertTrue( collection.contains( value ) ); assertEquals( values_array[count], value ); count++; } values_array = collection.toArray( new int[collection.size()] ); count = 0; iter = collection.iterator(); while ( iter.hasNext() ) { int value = iter.next(); assertTrue( collection.contains( value ) ); assertEquals( values_array[count], value ); count++; } values_array = collection.toArray( new int[collection.size() * 2] ); count = 0; iter = collection.iterator(); while ( iter.hasNext() ) { int value = iter.next(); assertTrue( collection.contains( value ) ); assertEquals( values_array[count], value ); count++; } assertEquals( collection.getNoEntryValue(), values_array[collection.size()] ); assertEquals( map.getNoEntryValue(), values_array[collection.size()] ); TIntCollection other = new TIntArrayList( collection ); assertFalse( collection.retainAll( other ) ); other.remove( vals[5] ); assertTrue( collection.retainAll( other ) ); assertFalse( collection.contains( vals[5] ) ); assertFalse( map.containsKey( keys[5] ) ); collection.clear(); assertTrue( collection.isEmpty() ); } public void testValueCollectionAdds() { int element_count = 20; String[] keys = new String[element_count]; int[] vals = new int[element_count]; TObjectIntMap map = new TObjectIntHashMap(); for ( int i = 0; i < element_count; i++ ) { keys[i] = Integer.toString( i + 1 ); vals[i] = i + 1; map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); TIntCollection collection = map.valueCollection(); for ( int i = 0; i < collection.size(); i++ ) { assertTrue( collection.contains( vals[i] ) ); } assertFalse( collection.isEmpty() ); try { collection.add( 1138 ); fail( "Expected UnsupportedOperationException" ); } catch ( UnsupportedOperationException ex ) { // Expected } try { Set test = new HashSet(); test.add( Integer.valueOf( 1138 ) ); collection.addAll( test ); fail( "Expected UnsupportedOperationException" ); } catch ( UnsupportedOperationException ex ) { // Expected } try { TIntCollection test = new TIntArrayList(); test.add( 1138 ); collection.addAll( test ); fail( "Expected UnsupportedOperationException" ); } catch ( UnsupportedOperationException ex ) { // Expected } try { collection.addAll( vals ); fail( "Expected UnsupportedOperationException" ); } catch ( UnsupportedOperationException ex ) { // Expected } } public void testValueCollectionContainsAll() { int element_count = 20; String[] keys = new String[element_count]; int[] vals = new int[element_count]; TObjectIntMap map = new TObjectIntHashMap(); for ( int i = 0; i < element_count; i++ ) { keys[i] = Integer.toString( i + 1 ); vals[i] = i + 1; map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); TIntCollection collection = map.valueCollection(); for ( int i = 0; i < collection.size(); i++ ) { assertTrue( collection.contains( vals[i] ) ); } assertFalse( collection.isEmpty() ); List java_list = new ArrayList(); for ( int value : vals ) { java_list.add( value ); } assertTrue( "collection: " + collection + ", should contain all in list: " + java_list, collection.containsAll( java_list ) ); java_list.add( Integer.valueOf( 1138 ) ); assertFalse( "collection: " + collection + ", should not contain all in list: " + java_list, collection.containsAll( java_list ) ); List number_list = new ArrayList(); for ( int value : vals ) { if ( value == 5 ) { number_list.add( Long.valueOf( value ) ); } else { number_list.add( Integer.valueOf( value ) ); } } assertFalse( "collection: " + collection + ", should not contain all in list: " + java_list, collection.containsAll( number_list ) ); TIntCollection other = new TIntArrayList( collection ); assertTrue( "collection: " + collection + ", should contain all in other: " + other, collection.containsAll( other ) ); other.add( 1138 ); assertFalse( "collection: " + collection + ", should not contain all in other: " + other, collection.containsAll( other ) ); assertTrue( "collection: " + collection + ", should contain all in array: " + Arrays.toString( vals ), collection.containsAll( vals ) ); int[] other_array = new int[vals.length + 1]; other_array[other_array.length - 1] = 1138; assertFalse( "collection: " + collection + ", should not contain all in array: " + Arrays.toString( vals ), collection.containsAll( other_array ) ); } public void testValueCollectionRetainAllCollection() { int element_count = 20; String[] keys = new String[element_count]; int[] vals = new int[element_count]; TObjectIntMap map = new TObjectIntHashMap(); for ( int i = 0; i < element_count; i++ ) { keys[i] = Integer.toString( i + 1 ); vals[i] = i + 1; map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); TIntCollection collection = map.valueCollection(); for ( int i = 0; i < collection.size(); i++ ) { assertTrue( collection.contains( vals[i] ) ); } assertFalse( collection.isEmpty() ); List java_list = new ArrayList(); for ( int value : vals ) { java_list.add( value ); } assertFalse( "collection: " + collection + ", should contain all in list: " + java_list, collection.retainAll( java_list ) ); java_list.remove( 5 ); assertTrue( "collection: " + collection + ", should contain all in list: " + java_list, collection.retainAll( java_list ) ); assertFalse( collection.contains( vals[5] ) ); assertFalse( map.containsKey( keys[5] ) ); assertFalse( map.containsValue( vals[5] ) ); assertTrue( "collection: " + collection + ", should contain all in list: " + java_list, collection.containsAll( java_list ) ); } public void testValueCollectionRetainAllTCollection() { int element_count = 20; String[] keys = new String[element_count]; int[] vals = new int[element_count]; TObjectIntMap map = new TObjectIntHashMap(); for ( int i = 0; i < element_count; i++ ) { keys[i] = Integer.toString( i + 1 ); vals[i] = i + 1; map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); TIntCollection collection = map.valueCollection(); for ( int i = 0; i < collection.size(); i++ ) { assertTrue( collection.contains( vals[i] ) ); } assertFalse( collection.isEmpty() ); assertFalse( "collection: " + collection + ", should be unmodified.", collection.retainAll( collection ) ); TIntCollection other = new TIntArrayList( collection ); assertFalse( "collection: " + collection + ", should be unmodified. other: " + other, collection.retainAll( other ) ); other.remove( vals[5] ); assertTrue( "collection: " + collection + ", should be modified. other: " + other, collection.retainAll( other ) ); assertFalse( collection.contains( vals[5] ) ); assertFalse( map.containsKey( keys[5] ) ); assertFalse( map.containsValue( vals[5] ) ); assertTrue( "collection: " + collection + ", should contain all in other: " + other, collection.containsAll( other ) ); } public void testValueCollectionRetainAllArray() { int element_count = 20; String[] keys = new String[element_count]; int[] vals = new int[element_count]; TObjectIntMap map = new TObjectIntHashMap(); for ( int i = 0; i < element_count; i++ ) { keys[i] = Integer.toString( i + 1 ); vals[i] = i + 1; map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); TIntCollection collection = map.valueCollection(); for ( int i = 0; i < collection.size(); i++ ) { assertTrue( collection.contains( vals[i] ) ); } assertFalse( collection.isEmpty() ); assertFalse( "collection: " + collection + ", should be unmodified. array: " + Arrays.toString( vals ), collection.retainAll( vals ) ); int[] other = new int[element_count - 1]; for ( int i = 0; i < element_count; i++ ) { if ( i < 5 ) { other[i] = i + 1; } if ( i > 5 ) { other[i - 1] = i + 1; } } assertTrue( "collection: " + collection + ", should be modified. array: " + Arrays.toString( other ), collection.retainAll( other ) ); } public void testValueCollectionRemoveAllCollection() { int element_count = 20; String[] keys = new String[element_count]; int[] vals = new int[element_count]; TObjectIntMap map = new TObjectIntHashMap(); for ( int i = 0; i < element_count; i++ ) { keys[i] = Integer.toString( i + 1 ); vals[i] = i + 1; map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); TIntCollection collection = map.valueCollection(); for ( int i = 0; i < collection.size(); i++ ) { assertTrue( collection.contains( vals[i] ) ); } assertFalse( collection.isEmpty() ); List java_list = new ArrayList(); assertFalse( "collection: " + collection + ", should contain all in list: " + java_list, collection.removeAll( java_list ) ); java_list.add( vals[5] ); assertTrue( "collection: " + collection + ", should contain all in list: " + java_list, collection.removeAll( java_list ) ); assertFalse( collection.contains( vals[5] ) ); assertFalse( map.containsKey( keys[5] ) ); assertFalse( map.containsValue( vals[5] ) ); java_list = new ArrayList(); for ( int value : vals ) { java_list.add( value ); } assertTrue( "collection: " + collection + ", should contain all in list: " + java_list, collection.removeAll( java_list ) ); assertTrue( collection.isEmpty() ); } public void testValueCollectionRemoveAllTCollection() { int element_count = 20; String[] keys = new String[element_count]; int[] vals = new int[element_count]; TObjectIntMap map = new TObjectIntHashMap(); for ( int i = 0; i < element_count; i++ ) { keys[i] = Integer.toString( i + 1 ); vals[i] = i + 1; map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); TIntCollection collection = map.valueCollection(); for ( int i = 0; i < collection.size(); i++ ) { assertTrue( collection.contains( vals[i] ) ); } assertFalse( collection.isEmpty() ); TIntCollection other = new TIntArrayList(); assertFalse( "collection: " + collection + ", should be unmodified.", collection.removeAll( other ) ); other = new TIntArrayList( collection ); other.remove( vals[5] ); assertTrue( "collection: " + collection + ", should be modified. other: " + other, collection.removeAll( other ) ); assertEquals( 1, collection.size() ); for ( int i = 0; i < element_count; i++ ) { if ( i == 5 ) { assertTrue( collection.contains( vals[i] ) ); assertTrue( map.containsKey( keys[i] ) ); assertTrue( map.containsValue( vals[i] ) ); } else { assertFalse( collection.contains( vals[i] ) ); assertFalse( map.containsKey( keys[i] ) ); assertFalse( map.containsValue( vals[i] ) ); } } assertFalse( "collection: " + collection + ", should be unmodified. other: " + other, collection.removeAll( other ) ); assertTrue( "collection: " + collection + ", should be modified. other: " + other, collection.removeAll( collection ) ); assertTrue( collection.isEmpty() ); } public void testValueCollectionRemoveAllArray() { int element_count = 20; String[] keys = new String[element_count]; int[] vals = new int[element_count]; TObjectIntMap map = new TObjectIntHashMap(); for ( int i = 0; i < element_count; i++ ) { keys[i] = Integer.toString( i + 1 ); vals[i] = i + 1; map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); TIntCollection collection = map.valueCollection(); for ( int i = 0; i < collection.size(); i++ ) { assertTrue( collection.contains( vals[i] ) ); } assertFalse( collection.isEmpty() ); int[] other = {1138}; assertFalse( "collection: " + collection + ", should be unmodified. array: " + Arrays.toString( vals ), collection.removeAll( other ) ); other = new int[element_count - 1]; for ( int i = 0; i < element_count; i++ ) { if ( i < 5 ) { other[i] = i + 1; } if ( i > 5 ) { other[i - 1] = i + 1; } } assertTrue( "collection: " + collection + ", should be modified. array: " + Arrays.toString( other ), collection.removeAll( other ) ); assertEquals( 1, collection.size() ); for ( int i = 0; i < element_count; i++ ) { if ( i == 5 ) { assertTrue( collection.contains( vals[i] ) ); assertTrue( map.containsKey( keys[i] ) ); assertTrue( map.containsValue( vals[i] ) ); } else { assertFalse( collection.contains( vals[i] ) ); assertFalse( map.containsKey( keys[i] ) ); assertFalse( map.containsValue( vals[i] ) ); } } } public void testValues() { int element_count = 20; String[] keys = new String[element_count]; int[] vals = new int[element_count]; TObjectIntMap map = new TObjectIntHashMap( element_count, 0.5f, Integer.MIN_VALUE ); for ( int i = 0; i < element_count; i++ ) { keys[i] = Integer.toString( i + 1 ); vals[i] = i + 1; map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); // No argument int[] values_array = map.values(); assertEquals( element_count, values_array.length ); TIntList values_list = new TIntArrayList( values_array ); for ( int i = 0; i < element_count; i++ ) { assertTrue( values_list.contains( vals[i] ) ); } // Zero length array values_array = map.values( new int[0] ); assertEquals( element_count, values_array.length ); values_list = new TIntArrayList( values_array ); for ( int i = 0; i < element_count; i++ ) { assertTrue( values_list.contains( vals[i] ) ); } // appropriate length array values_array = map.values( new int[map.size()] ); assertEquals( element_count, values_array.length ); values_list = new TIntArrayList( values_array ); for ( int i = 0; i < element_count; i++ ) { assertTrue( values_list.contains( vals[i] ) ); } // longer array values_array = map.values( new int[element_count * 2] ); assertEquals( element_count * 2, values_array.length ); values_list = new TIntArrayList( values_array ); for ( int i = 0; i < element_count; i++ ) { assertTrue( values_list.contains( vals[i] ) ); } assertEquals( map.getNoEntryValue(), values_array[element_count] ); } public void testIterator() { TObjectIntHashMap map = new TObjectIntHashMap(); TObjectIntIterator iterator = map.iterator(); assertFalse( iterator.hasNext() ); map.put( "one", 1 ); map.put( "two", 2 ); iterator = map.iterator(); assertTrue( iterator.hasNext() ); iterator.advance(); String first_key = iterator.key(); assertNotNull( "key was null", first_key ); assertTrue( "invalid key: " + first_key, first_key.equals( "one" ) || first_key.equals( "two" ) ); if ( first_key.equals( "one" ) ) { assertEquals( 1, iterator.value() ); } else { assertEquals( 2, iterator.value() ); } assertTrue( iterator.hasNext() ); iterator.advance(); String second_key = iterator.key(); assertNotNull( "key was null", second_key ); assertTrue( "invalid key: " + second_key, second_key.equals( "one" ) || second_key.equals( "two" ) ); if ( second_key.equals( "one" ) ) { assertEquals( 1, iterator.value() ); } else { assertEquals( 2, iterator.value() ); } assertFalse( first_key + ", " + second_key, first_key.equals( second_key ) ); assertFalse( iterator.hasNext() ); // New Iterator iterator = map.iterator(); iterator.advance(); first_key = iterator.key(); iterator.setValue( 1138 ); assertEquals( 1138, iterator.value() ); assertEquals( 1138, map.get( first_key ) ); } public void testIteratorRemoval() { TObjectIntHashMap map = new TObjectIntHashMap(); map.put( "one", 1 ); map.put( "two", 2 ); map.put( "three", 3 ); map.put( "four", 4 ); map.put( "five", 5 ); map.put( "six", 6 ); map.put( "seven", 7 ); map.put( "eight", 8 ); map.put( "nine", 9 ); map.put( "ten", 10 ); TObjectIntIterator iterator = map.iterator(); while ( map.size() > 5 && iterator.hasNext() ) { iterator.advance(); String key = iterator.key(); iterator.remove(); assertFalse( "map still contains key: " + key, map.containsKey( key ) ); } assertEquals( 5, map.size() ); iterator = map.iterator(); assertTrue( iterator.hasNext() ); iterator.advance(); assertTrue( iterator.hasNext() ); iterator.advance(); assertTrue( iterator.hasNext() ); iterator.advance(); assertTrue( iterator.hasNext() ); iterator.advance(); assertTrue( iterator.hasNext() ); iterator.advance(); assertFalse( iterator.hasNext() ); iterator = map.iterator(); int elements = map.size(); while ( iterator.hasNext() ) { iterator.advance(); String key = iterator.key(); iterator.remove(); assertFalse( "map still contains key: " + key, map.containsKey( key ) ); elements--; } assertEquals( 0, elements ); assertEquals( 0, map.size() ); assertTrue( map.isEmpty() ); } public void testIteratorRemoval2() { int element_count = 10000; int remaining = element_count / 2; TObjectIntHashMap map = new TObjectIntHashMap( element_count, 0.5f, Integer.MIN_VALUE ); for ( int pass = 0; pass < 10; pass++ ) { Random r = new Random(); for ( int i = 0; i <= element_count; i++ ) { map.put( String.valueOf( r.nextInt() ), i ); } TObjectIntIterator iterator = map.iterator(); while ( map.size() > remaining && iterator.hasNext() ) { iterator.advance(); iterator.remove(); } } } public void testIncrement() { int element_count = 20; String[] keys = new String[element_count]; int[] vals = new int[element_count]; TObjectIntMap map = new TObjectIntHashMap( element_count, 0.5f, Integer.MIN_VALUE ); for ( int i = 0; i < element_count; i++ ) { keys[i] = Integer.toString( i + 1 ); vals[i] = i + 1; map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); assertFalse( map.increment( "non-existant" ) ); assertTrue( map.increment( "1" ) ); assertEquals( 2, map.get( "1" ) ); } public void testAdjustValue() { TObjectIntHashMap map = new TObjectIntHashMap(); map.put( "one", 1 ); boolean changed = map.adjustValue( "one", 1 ); assertTrue( changed ); assertEquals( 2, map.get( "one" ) ); changed = map.adjustValue( "one", 5 ); assertTrue( changed ); assertEquals( 7, map.get( "one" ) ); changed = map.adjustValue( "one", -3 ); assertTrue( changed ); assertEquals( 4, map.get( "one" ) ); changed = map.adjustValue( "two", 1 ); assertFalse( changed ); assertFalse( map.containsKey( "two" ) ); } public void testAdjustOrPutValue() { TObjectIntHashMap map = new TObjectIntHashMap(); map.put( "one", 1 ); long new_value = map.adjustOrPutValue( "one", 1, 100 ); assertEquals( 2, new_value ); assertEquals( 2, map.get( "one" ) ); new_value = map.adjustOrPutValue( "one", 5, 100 ); assertEquals( 7, new_value ); assertEquals( 7, map.get( "one" ) ); new_value = map.adjustOrPutValue( "one", -3, 100 ); assertEquals( 4, new_value ); assertEquals( 4, map.get( "one" ) ); new_value = map.adjustOrPutValue( "two", 1, 100 ); assertEquals( 100, new_value ); assertTrue( map.containsKey( "two" ) ); assertEquals( 100, map.get( "two" ) ); new_value = map.adjustOrPutValue( "two", 1, 100 ); assertEquals( 101, new_value ); assertEquals( 101, map.get( "two" ) ); } public void testForEachKey() { int element_count = 20; String[] keys = new String[element_count]; int[] vals = new int[element_count]; TObjectIntMap map = new TObjectIntHashMap( element_count, 0.5f, Integer.MIN_VALUE ); for ( int i = 0; i < element_count; i++ ) { keys[i] = Integer.toString( i + 1 ); vals[i] = i + 1; map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); class ForEach implements TObjectProcedure { List built = new ArrayList(); public boolean execute( String value ) { built.add( value ); return true; } List getBuilt() { return built; } } ForEach foreach = new ForEach(); map.forEachKey( foreach ); List built = foreach.getBuilt(); List keys_list = Arrays.asList( map.keys( new String[map.size()] ) ); assertEquals( keys_list, built ); Collections.sort( built ); Collections.sort( keys_list ); assertEquals( keys_list, built ); class ForEachFalse implements TObjectProcedure { List built = new ArrayList(); public boolean execute( String value ) { built.add( value ); return false; } List getBuilt() { return built; } } ForEachFalse foreach_false = new ForEachFalse(); map.forEachKey( foreach_false ); built = foreach_false.getBuilt(); keys_list = Arrays.asList( map.keys( new String[map.size()] ) ); assertEquals( 1, built.size() ); assertEquals( keys_list.get( 0 ), built.get( 0 ) ); } public void testForEachValue() { int element_count = 20; String[] keys = new String[element_count]; int[] vals = new int[element_count]; TObjectIntMap map = new TObjectIntHashMap( element_count, 0.5f, Integer.MIN_VALUE ); for ( int i = 0; i < element_count; i++ ) { keys[i] = Integer.toString( i + 1 ); vals[i] = i + 1; map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); class ForEach implements TIntProcedure { TIntList built = new TIntArrayList(); public boolean execute( int value ) { built.add( value ); return true; } TIntList getBuilt() { return built; } } ForEach foreach = new ForEach(); map.forEachValue( foreach ); TIntList built = foreach.getBuilt(); TIntList values = new TIntArrayList( map.values() ); assertEquals( values, built ); built.sort(); values.sort(); assertEquals( values, built ); class ForEachFalse implements TIntProcedure { TIntList built = new TIntArrayList(); public boolean execute( int value ) { built.add( value ); return false; } TIntList getBuilt() { return built; } } ForEachFalse foreach_false = new ForEachFalse(); map.forEachValue( foreach_false ); built = foreach_false.getBuilt(); values = new TIntArrayList( map.values() ); assertEquals( 1, built.size() ); assertEquals( values.get( 0 ), built.get( 0 ) ); } public void testForEachEntry() { int element_count = 20; String[] keys = new String[element_count]; int[] vals = new int[element_count]; TObjectIntMap map = new TObjectIntHashMap( element_count, 0.5f, Integer.MIN_VALUE ); for ( int i = 0; i < element_count; i++ ) { keys[i] = Integer.toString( i + 1 ); vals[i] = i + 1; map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); class ForEach implements TObjectIntProcedure { TObjectIntMap built = new TObjectIntHashMap(); public boolean execute( String key, int value ) { built.put( key, value ); return true; } TObjectIntMap getBuilt() { return built; } } ForEach foreach = new ForEach(); map.forEachEntry( foreach ); TObjectIntMap built = foreach.getBuilt(); assertEquals( map, built ); class ForEachFalse implements TObjectIntProcedure { TObjectIntMap built = new TObjectIntHashMap(); public boolean execute( String key, int value ) { built.put( key, value ); return false; } TObjectIntMap getBuilt() { return built; } } ForEachFalse foreach_false = new ForEachFalse(); map.forEachEntry( foreach_false ); built = foreach_false.getBuilt(); assertEquals( 1, built.size() ); assertTrue( map.containsKey( built.keys()[0] ) ); assertTrue( map.containsValue( built.values()[0] ) ); } public void testRetain() { TObjectIntHashMap map = new TObjectIntHashMap(); map.put( "one", 1 ); map.put( "two", 2 ); map.put( "three", 3 ); map.put( "four", 4 ); map.put( "five", 5 ); map.put( "six", 6 ); map.put( "seven", 7 ); map.put( "eight", 8 ); map.put( "nine", 9 ); map.put( "ten", 10 ); map.retainEntries( new TObjectIntProcedure() { public boolean execute( String a, int b ) { return b > 5 && b <= 8; } } ); assertEquals( 3, map.size() ); assertFalse( map.containsKey( "one" ) ); assertFalse( map.containsKey( "two" ) ); assertFalse( map.containsKey( "three" ) ); assertFalse( map.containsKey( "four" ) ); assertFalse( map.containsKey( "five" ) ); assertTrue( map.containsKey( "six" ) ); assertTrue( map.containsKey( "seven" ) ); assertTrue( map.containsKey( "eight" ) ); assertFalse( map.containsKey( "nine" ) ); assertFalse( map.containsKey( "ten" ) ); map.put( "eleven", 11 ); map.put( "twelve", 12 ); map.put( "thirteen", 13 ); map.put( "fourteen", 14 ); map.put( "fifteen", 15 ); map.put( "sixteen", 16 ); map.put( "seventeen", 17 ); map.put( "eighteen", 18 ); map.put( "nineteen", 19 ); map.put( "twenty", 20 ); map.retainEntries( new TObjectIntProcedure() { public boolean execute( String a, int b ) { return b > 15; } } ); assertEquals( 5, map.size() ); assertFalse( map.containsKey( "one" ) ); assertFalse( map.containsKey( "two" ) ); assertFalse( map.containsKey( "three" ) ); assertFalse( map.containsKey( "four" ) ); assertFalse( map.containsKey( "five" ) ); assertFalse( map.containsKey( "six" ) ); assertFalse( map.containsKey( "seven" ) ); assertFalse( map.containsKey( "eight" ) ); assertFalse( map.containsKey( "nine" ) ); assertFalse( map.containsKey( "ten" ) ); assertFalse( map.containsKey( "eleven" ) ); assertFalse( map.containsKey( "twelve" ) ); assertFalse( map.containsKey( "thirteen" ) ); assertFalse( map.containsKey( "fourteen" ) ); assertFalse( map.containsKey( "fifteen" ) ); assertTrue( map.containsKey( "sixteen" ) ); assertTrue( map.containsKey( "seventeen" ) ); assertTrue( map.containsKey( "eighteen" ) ); assertTrue( map.containsKey( "nineteen" ) ); assertTrue( map.containsKey( "twenty" ) ); map.retainEntries( new TObjectIntProcedure() { public boolean execute( String a, int b ) { return false; } } ); assertEquals( 0, map.size() ); } public void testTransformValues() { int element_count = 20; String[] keys = new String[element_count]; int[] vals = new int[element_count]; TObjectIntMap map = new TObjectIntHashMap( element_count, 0.5f, Integer.MIN_VALUE ); for ( int i = 0; i < element_count; i++ ) { keys[i] = Integer.toString( i + 1 ); vals[i] = i + 1; map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); map.transformValues( new TIntFunction() { public int execute( int value ) { return value * value; } } ); for ( int i = 0; i < element_count; i++ ) { int expected = vals[i] * vals[i]; assertEquals( expected, map.get( keys[i] ) ); } } public void testEquals() { int element_count = 20; String[] keys = new String[element_count]; int[] vals = new int[element_count]; TObjectIntMap map = new TObjectIntHashMap( element_count, 0.5f, Integer.MIN_VALUE ); for ( int i = 0; i < element_count; i++ ) { keys[i] = Integer.toString( i + 1 ); vals[i] = i + 1; map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); TObjectIntHashMap fully_specified = new TObjectIntHashMap( 20, 0.75f, Integer.MIN_VALUE ); for ( int i = 0; i < element_count; i++ ) { fully_specified.put( keys[i], vals[i] ); } assertEquals( map, fully_specified ); assertFalse( "shouldn't equal random object", map.equals( new Object() ) ); int value = 11010110; // I thought I saw a two! assertEquals( map.getNoEntryValue(), map.put( null, value ) ); assertEquals( map.getNoEntryValue(), fully_specified.put( null, value ) ); assertEquals( value, map.get( null ) ); assertEquals( value, fully_specified.get( null ) ); assertTrue( "incorrectly not-equal map: " + map + "\nfully_specified: " + fully_specified, map.equals( fully_specified ) ); assertTrue( "incorrectly not-equal map: " + map + "\nfully_specified: " + fully_specified, fully_specified.equals( map ) ); assertEquals( map.getNoEntryValue(), fully_specified.put( "non-null-key", value ) ); assertFalse( "incorrectly equal map: " + map + "\nfully_specified: " + fully_specified, map.equals( fully_specified ) ); assertFalse( "incorrectly equal map: " + map + "\nfully_specified: " + fully_specified, fully_specified.equals( map ) ); int no_value = map.getNoEntryValue(); assertEquals( map.getNoEntryValue(), map.put( "non-null-key", no_value ) ); assertEquals( value, fully_specified.put( "non-null-key", no_value ) ); assertTrue( "incorrectly not-equal map: " + map + "\nfully_specified: " + fully_specified, map.equals( fully_specified ) ); assertTrue( "incorrectly not-equal map: " + map + "\nfully_specified: " + fully_specified, fully_specified.equals( map ) ); assertEquals( no_value, map.put( "non-null-key", value ) ); assertFalse( "incorrectly equal map: " + map + "\nfully_specified: " + fully_specified, map.equals( fully_specified ) ); assertFalse( "incorrectly equal map: " + map + "\nfully_specified: " + fully_specified, fully_specified.equals( map ) ); assertEquals( map.getNoEntryValue(), fully_specified.put( "blargh", value ) ); assertFalse( "incorrectly equal map: " + map + "\nfully_specified: " + fully_specified, map.equals( fully_specified ) ); } public void testHashCode() { int element_count = 20; String[] keys = new String[element_count]; int[] vals = new int[element_count]; int counter = 0; TObjectIntMap map = new TObjectIntHashMap( element_count, 0.5f, Integer.MIN_VALUE ); for ( int i = 0; i < element_count; i++, counter++ ) { keys[i] = Integer.toString( counter + 1 ); vals[i] = counter + 1; map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); assertEquals( map.hashCode(), map.hashCode() ); Map> string_tmap_map = new HashMap>(); string_tmap_map.put( "first", map ); string_tmap_map.put( "second", map ); assertSame( map, string_tmap_map.get( "first" ) ); assertSame( map, string_tmap_map.get( "second" ) ); TObjectIntMap map2 = new TObjectIntHashMap( element_count, 0.5f, Integer.MIN_VALUE ); for ( int i = 0; i < element_count; i++, counter++ ) { keys[i] = Integer.toString( counter + 1 ); vals[i] = counter + 1; map2.put( keys[i], vals[i] ); } assertEquals( element_count, map2.size() ); assertEquals( map2.hashCode(), map2.hashCode() ); TObjectIntMap map3 = new TObjectIntHashMap( element_count, 0.5f, Integer.MIN_VALUE ); for ( int i = 0; i < element_count; i++, counter++ ) { keys[i] = Integer.toString( counter + 1 ); vals[i] = counter + 1; map3.put( keys[i], vals[i] ); } assertEquals( element_count, map3.size() ); assertEquals( map3.hashCode(), map3.hashCode() ); assertFalse( map.hashCode() == map2.hashCode() ); assertFalse( map.hashCode() == map3.hashCode() ); assertFalse( map2.hashCode() == map3.hashCode() ); Map, String> tmap_string_map = new HashMap, String>(); tmap_string_map.put( map, "map1" ); tmap_string_map.put( map2, "map2" ); tmap_string_map.put( map3, "map3" ); assertEquals( "map1", tmap_string_map.get( map ) ); assertEquals( "map2", tmap_string_map.get( map2 ) ); assertEquals( "map3", tmap_string_map.get( map3 ) ); } @SuppressWarnings({"unchecked"}) public void testSerialize() throws Exception { Integer[] keys = {1138, 42, 86, 99, 101, 727, 117}; int[] vals = new int[keys.length]; TObjectIntMap map = new TObjectIntHashMap(); for ( int i = 0; i < keys.length; i++ ) { vals[i] = keys[i] * 2; map.put( keys[i], vals[i] ); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream( baos ); oos.writeObject( map ); ByteArrayInputStream bias = new ByteArrayInputStream( baos.toByteArray() ); ObjectInputStream ois = new ObjectInputStream( bias ); TObjectIntMap deserialized = (TObjectIntMap) ois.readObject(); assertEquals( map, deserialized ); } public void testToString() { TObjectIntHashMap m = new TObjectIntHashMap(); m.put( "One", 11 ); m.put( "Two", 22 ); String to_string = m.toString(); assertTrue( to_string, to_string.equals( "{One=11,Two=22}" ) || to_string.equals( "{Two=22,One=11}" ) ); } public void testDecorator() { // TObjectIntHashMap map = new TObjectIntHashMap(); // // map.put( "one", 1 ); // map.put( "two", 2 ); // // Map decorator = new TObjectIntHashMapDecorator( map ); // // assertEquals( 2, decorator.size() ); // assertEquals( Integer.valueOf( 1 ), decorator.get( "one" ) ); // assertEquals( Integer.valueOf( 2 ), decorator.get( "two" ) ); // // Set decorator_keys = decorator.keySet(); // assertEquals( 2, decorator_keys.size() ); // Iterator it = decorator_keys.iterator(); // int count = 0; // while( it.hasNext() ) { // count++; // System.out.println(it.next()); // } // assertEquals( 2, count ); // // assertSame(map, ( ( TObjectIntHashMapDecorator ) decorator ).getMap() ); } public void testBug3232758() { TObjectIntHashMap map = new TObjectIntHashMap( 1, 3 ); map.put( "1009", 0 ); map.put( "1007", 1 ); map.put( "1006", 2 ); map.put( "1005", 3 ); map.put( "1004", 4 ); map.put( "1002", 5 ); map.put( "1001", 6 ); for ( Object o : map.keys() ) { map.remove( o ); } } } trove-3.0.3/test/gnu/trove/map/hash/TObjectPrimitiveCustomHashMapTest.java0000644000175000017500000000503011763017634025622 0ustar ericherichpackage gnu.trove.map.hash; import gnu.trove.map.TObjectIntMap; import gnu.trove.map.custom_hash.TObjectIntCustomHashMap; import gnu.trove.strategy.HashingStrategy; import junit.framework.TestCase; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Set; /** * */ public class TObjectPrimitiveCustomHashMapTest extends TestCase { // Example from Trove overview doc public void testArray() { char[] foo = new char[] { 'a', 'b', 'c' }; char[] bar = new char[] { 'a', 'b', 'c' }; assertFalse( foo.hashCode() == bar.hashCode() ); //noinspection ArrayEquals assertFalse( foo.equals( bar ) ); HashingStrategy strategy = new ArrayHashingStrategy(); assertTrue( strategy.computeHashCode( foo ) == strategy.computeHashCode( bar ) ); assertTrue( strategy.equals( foo, bar ) ); TObjectIntMap map = new TObjectIntCustomHashMap( strategy ); map.put( foo, 12 ); assertTrue( map.containsKey( foo ) ); assertTrue( map.containsKey( bar ) ); assertEquals( 12, map.get( foo ) ); assertEquals( 12, map.get( bar ) ); Set keys = map.keySet(); assertTrue( keys.contains( foo ) ); assertTrue( keys.contains( bar ) ); } public void testSerialization() throws Exception { char[] foo = new char[] { 'a', 'b', 'c' }; char[] bar = new char[] { 'a', 'b', 'c' }; HashingStrategy strategy = new ArrayHashingStrategy(); TObjectIntMap map = new TObjectIntCustomHashMap( strategy ); map.put( foo, 33 ); // Make sure it still works after being serialized ObjectOutputStream oout = null; ByteArrayOutputStream bout = null; ObjectInputStream oin = null; ByteArrayInputStream bin = null; try { bout = new ByteArrayOutputStream(); oout = new ObjectOutputStream( bout ); oout.writeObject( map ); bin = new ByteArrayInputStream( bout.toByteArray() ); oin = new ObjectInputStream( bin ); map = ( TObjectIntMap ) oin.readObject(); } finally { if ( oin != null ) oin.close(); if ( bin != null ) bin.close(); if ( oout != null ) oout.close(); if ( bout != null ) bout.close(); } assertTrue( map.containsKey( foo ) ); assertTrue( map.containsKey( bar ) ); assertEquals( 33, map.get( foo ) ); assertEquals( 33, map.get( bar ) ); Set keys = map.keySet(); assertTrue( keys.contains( foo ) ); assertTrue( keys.contains( bar ) ); } } trove-3.0.3/test/gnu/trove/map/hash/NoEntryValueTest.java0000644000175000017500000000170411763017634022341 0ustar ericherichpackage gnu.trove.map.hash; import gnu.trove.map.TObjectIntMap; import junit.framework.TestCase; import java.util.Arrays; /** * Test for a number of bugs related to no_entry_value, including 3432402 */ public class NoEntryValueTest extends TestCase { public void testAdjustToNoEntry() { TObjectIntMap map = new TObjectIntHashMap(); assertEquals( 0, map.getNoEntryValue() ); assertEquals( 0, map.get( "NotInThere" ) ); map.put( "Value", 1 ); assertEquals( 1, map.size() ); assertEquals( 1, map.get( "Value" ) ); assertTrue( map.containsKey( "Value" ) ); assertTrue( map.containsValue( 1 ) ); assertTrue( Arrays.equals( new int[] { 1 }, map.values() ) ); map.adjustValue( "Value", -1 ); assertEquals( 1, map.size() ); assertEquals( 0, map.get( "Value" ) ); assertTrue( map.containsKey( "Value" ) ); assertTrue( map.containsValue( 0 ) ); assertTrue( Arrays.equals( new int[] { 0 }, map.values() ) ); } } trove-3.0.3/test/gnu/trove/map/hash/TPrimitivePrimitiveHashMapTest.java0000644000175000017500000021645211763017634025205 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2006-2008, Rob Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.map.hash; //import gnu.trove.decorator.TByteIntHashMapDecorator; import gnu.trove.list.array.TIntArrayList; import gnu.trove.list.array.TLongArrayList; import gnu.trove.list.TIntList; import gnu.trove.list.TLongList; import gnu.trove.iterator.TIntLongIterator; import gnu.trove.iterator.TIntIterator; import gnu.trove.iterator.TLongIterator; import gnu.trove.map.TIntLongMap; import gnu.trove.map.TIntIntMap; import gnu.trove.set.TIntSet; import gnu.trove.set.TLongSet; import gnu.trove.set.hash.TIntHashSet; import gnu.trove.set.hash.TLongHashSet; import gnu.trove.procedure.TIntProcedure; import gnu.trove.procedure.TLongProcedure; import gnu.trove.procedure.TIntLongProcedure; import gnu.trove.function.TLongFunction; import gnu.trove.TLongCollection; import gnu.trove.TIntCollection; import junit.framework.TestCase; import java.util.*; import java.io.ByteArrayOutputStream; import java.io.ObjectOutputStream; import java.io.ByteArrayInputStream; import java.io.ObjectInputStream; /** * */ public class TPrimitivePrimitiveHashMapTest extends TestCase { final int KEY_ONE = 100; final int KEY_TWO = 101; public TPrimitivePrimitiveHashMapTest( String name ) { super( name ); } public void testConstructors() { int[] keys = {1138, 42, 86, 99, 101}; long[] vals = {1138, 42, 86, 99, 101}; TIntLongMap map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { map.put( keys[i], vals[i] ); } assertEquals( keys.length, map.size() ); TIntLongMap capacity = new TIntLongHashMap( 20 ); for ( int i = 0; i < keys.length; i++ ) { capacity.put( keys[i], vals[i] ); } assertEquals( keys.length, capacity.size() ); TIntLongMap cap_and_factor = new TIntLongHashMap( 20, 0.75f ); for ( int i = 0; i < keys.length; i++ ) { cap_and_factor.put( keys[i], vals[i] ); } assertEquals( keys.length, cap_and_factor.size() ); TIntLongMap fully_specified = new TIntLongHashMap( 20, 0.5f, Integer.MIN_VALUE, Long.MIN_VALUE ); for ( int i = 0; i < keys.length; i++ ) { fully_specified.put( keys[i], vals[i] ); } assertEquals( keys.length, fully_specified.size() ); TIntLongMap copy = new TIntLongHashMap( map ); assertEquals( keys.length, fully_specified.size() ); TIntLongMap arrays = new TIntLongHashMap( keys, vals ); assertEquals( keys.length, arrays.size() ); // Equals in all combinations is paranoid.. but.. assertEquals( map, map ); assertEquals( map, capacity ); assertEquals( map, cap_and_factor ); assertEquals( map, fully_specified ); assertEquals( map, copy ); assertEquals( map, arrays ); assertEquals( capacity, map ); assertEquals( capacity, capacity ); assertEquals( capacity, cap_and_factor ); assertEquals( capacity, fully_specified ); assertEquals( capacity, copy ); assertEquals( capacity, arrays ); assertEquals( cap_and_factor, map ); assertEquals( cap_and_factor, capacity ); assertEquals( cap_and_factor, cap_and_factor ); assertEquals( cap_and_factor, fully_specified ); assertEquals( cap_and_factor, copy ); assertEquals( cap_and_factor, arrays ); assertEquals( fully_specified, map ); assertEquals( fully_specified, capacity ); assertEquals( fully_specified, cap_and_factor ); assertEquals( fully_specified, fully_specified ); assertEquals( fully_specified, copy ); assertEquals( fully_specified, arrays ); assertEquals( copy, map ); assertEquals( copy, capacity ); assertEquals( copy, cap_and_factor ); assertEquals( copy, fully_specified ); assertEquals( copy, copy ); assertEquals( copy, arrays ); assertEquals( arrays, map ); assertEquals( arrays, capacity ); assertEquals( arrays, cap_and_factor ); assertEquals( arrays, fully_specified ); assertEquals( arrays, copy ); assertEquals( arrays, arrays ); } /** Be sure that size is large enough to force a resize or two. */ public void testRehash() { int size = 1000; int[] keys = new int[size]; long[] vals = new long[size]; for ( int i = 0; i < size; i++ ) { keys[i] = i + 1; vals[i] = keys[i] * 2; } TIntLongMap map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { map.put( keys[i], vals[i] ); } assertEquals( keys.length, map.size() ); for ( int i = 0; i < keys.length; i++ ) { int key = keys[i]; long val = vals[i]; assertEquals( "got incorrect value for index " + i + ", map: " + map, val, map.get( key ) ); } } public void testPutAll() { int[] keys = {1138, 42, 86, 99, 101}; long[] vals = {1138, 42, 86, 99, 101}; TIntLongMap map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { map.put( keys[i], vals[i] * 2 ); } assertEquals( keys.length, map.size() ); TIntLongMap target = new TIntLongHashMap(); target.put( 1, 2 ); assertEquals( 1, target.size() ); target.putAll( map ); assertEquals( keys.length + 1, target.size() ); for ( int i = 0; i < keys.length; i++ ) { assertEquals( vals[i] * 2, target.get( keys[i] ) ); } assertEquals( 2, target.get( 1 ) ); // java.util.Map source Map java_map = new HashMap(); for ( int i = 0; i < keys.length; i++ ) { java_map.put( keys[i], vals[i] * 2 ); } // fresh TIntLongMap target = new TIntLongHashMap(); target.put( 1, 2 ); assertEquals( 1, target.size() ); target.putAll( java_map ); assertEquals( "map size is incorrect: " + keys.length + ", source: " + java_map + ", target: " + target, keys.length + 1, target.size() ); for ( int i = 0; i < keys.length; i++ ) { assertEquals( vals[i] * 2, target.get( keys[i] ) ); } assertEquals( 2, target.get( 1 ) ); } public void testClear() { int[] keys = {1138, 42, 86, 99, 101}; long[] vals = {1138, 42, 86, 99, 101}; TIntLongMap map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { map.put( keys[i], vals[i] * 2 ); } assertEquals( keys.length, map.size() ); map.clear(); assertEquals( 0, map.size() ); assertTrue( map.isEmpty() ); TIntLongMap empty = new TIntLongHashMap(); assertEquals( empty, map ); // Map jmap = new HashMap(); // jmap.isEmpty() } public void testRemove() { int[] keys = {1138, 42, 86, 99, 101, 727, 117}; long[] vals = new long[keys.length]; TIntLongMap map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { vals[i] = keys[i] * 2; map.put( keys[i], vals[i] ); } assertEquals( keys.length, map.size() ); for ( int i = 0; i < keys.length; i++ ) { assertEquals( vals[i], map.get( keys[i] ) ); } assertEquals( vals[0], map.remove( keys[0] ) ); assertEquals( vals[3], map.remove( keys[3] ) ); assertEquals( map.getNoEntryValue(), map.remove( keys[0] ) ); assertEquals( vals[5], map.remove( keys[5] ) ); assertEquals( map.getNoEntryValue(), map.remove( 11010110 ) ); } public void testKeySetMisc() { int[] keys = {1138, 42, 86, 99, 101, 727, 117}; long[] vals = new long[keys.length]; TIntLongMap map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { vals[i] = keys[i] * 2; map.put( keys[i], vals[i] ); } TIntSet set = map.keySet(); int[] sorted_keys = new int[ keys.length ]; System.arraycopy( keys, 0, sorted_keys, 0, keys.length ); Arrays.sort( sorted_keys ); int[] setarray = set.toArray(); Arrays.sort( setarray ); assertTrue( "expected: " + Arrays.toString( sorted_keys ) + ", was: " + Arrays.toString( setarray ), Arrays.equals( sorted_keys, setarray ) ); setarray = set.toArray( new int[0] ); Arrays.sort( setarray ); assertTrue( "expected: " + Arrays.toString( sorted_keys ) + ", was: " + Arrays.toString( setarray ), Arrays.equals( sorted_keys, setarray ) ); assertFalse( "remove of element not in set succeded: " + set, set.remove( 1 ) ); assertEquals( keys.length, set.size() ); assertEquals( keys.length, map.size() ); assertTrue( "remove of element in set failed: " + set, set.remove( 42 ) ); assertEquals( keys.length - 1, set.size() ); assertEquals( keys.length - 1, map.size() ); try { set.add( 42 ); fail( "Expected UnsupportedOperationException" ); } catch ( UnsupportedOperationException ex ) { // Expected } } public void testKeySetContainsAll() { int[] keys = {1138, 42, 86, 99, 101, 727, 117}; long[] vals = new long[keys.length]; TIntLongMap map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { vals[i] = keys[i] * 2; map.put( keys[i], vals[i] ); } TIntSet set = map.keySet(); assertEquals( map.size(), set.size() ); assertFalse( set.isEmpty() ); // test with a java.util.Map Set java_set = new HashSet(); for ( int i = 0; i < keys.length; i++ ) { java_set.add( Integer.valueOf( keys[i] ) ); } assertTrue( set.containsAll( java_set ) ); java_set.add( Integer.valueOf( 12 ) ); assertFalse( set.containsAll( java_set ) ); java_set.remove( Integer.valueOf( 12 ) ); assertTrue( set.containsAll( java_set ) ); java_set.add( Long.valueOf( 12 ) ); assertFalse( set.containsAll( java_set ) ); // test with a TCollection TIntSet tintset = new TIntHashSet( keys ); assertTrue( set.containsAll( tintset ) ); tintset.add( 12 ); assertFalse( set.containsAll( tintset ) ); // test raw array assertTrue( set.containsAll( keys ) ); keys[3] = keys[3] + 1; assertFalse( set.containsAll( keys ) ); } public void testKeySetAddAll() { int[] keys = {1138, 42, 86, 99, 101, 727, 117}; long[] vals = new long[keys.length]; TIntLongMap map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { vals[i] = keys[i] * 2; map.put( keys[i], vals[i] ); } TIntSet set = map.keySet(); assertEquals( map.size(), set.size() ); assertFalse( set.isEmpty() ); // test with a java.util.Map Set java_set = new HashSet(); for ( int i = 0; i < keys.length; i++ ) { java_set.add( Integer.valueOf( keys[i] ) ); } try { set.addAll( java_set ); fail( "Expected UnsupportedOperationException" ); } catch ( UnsupportedOperationException ex ) { // Expected } try { set.addAll( set ); fail( "Expected UnsupportedOperationException" ); } catch ( UnsupportedOperationException ex ) { // Expected } try { set.addAll( keys ); fail( "Expected UnsupportedOperationException" ); } catch ( UnsupportedOperationException ex ) { // Expected } } public void testKeySetRetainAllCollection() { int[] keys = {1138, 42, 86, 99, 101, 727, 117}; long[] vals = new long[keys.length]; TIntLongMap map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { vals[i] = keys[i] * 2; map.put( keys[i], vals[i] ); } TIntSet set = map.keySet(); assertEquals( map.size(), set.size() ); assertFalse( set.isEmpty() ); // test with a java.util.Map Set java_set = new HashSet(); for ( int i = 0; i < keys.length; i++ ) { java_set.add( Integer.valueOf( keys[i] ) ); } assertFalse( set.retainAll( java_set ) ); assertEquals( keys.length, set.size() ); assertEquals( keys.length, map.size() ); for ( int i = 0; i < keys.length; i++ ) { assertTrue( set.contains( keys[i] ) ); assertTrue( map.containsKey( keys[i] ) ); } java_set.remove( 42 ); assertTrue( "set should have been modified: " + set + ", java: " + java_set, set.retainAll( java_set ) ); assertEquals( keys.length - 1, set.size() ); assertEquals( keys.length - 1, map.size() ); for ( int i = 0; i < keys.length; i++ ) { if ( keys[i] != 42 ) { assertTrue( set.contains( keys[i] ) ); assertTrue( map.containsKey( keys[i] ) ); } else { assertFalse( set.contains( keys[i] ) ); assertFalse( map.containsKey( keys[i] ) ); } } } public void testKeySetRetainAllTCollection() { int[] keys = {1138, 42, 86, 99, 101, 727, 117}; long[] vals = new long[keys.length]; TIntLongMap map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { vals[i] = keys[i] * 2; map.put( keys[i], vals[i] ); } TIntSet set = map.keySet(); assertEquals( map.size(), set.size() ); assertFalse( set.isEmpty() ); assertFalse( set.retainAll( set ) ); // test with a TCollection TIntSet tintset = new TIntHashSet( keys ); assertFalse( "set: " + set + ", collection: " + tintset, set.retainAll( tintset ) ); TIntCollection collection = new TIntArrayList( keys ); assertFalse( "set: " + set + ", collection: " + collection, set.retainAll( collection ) ); collection.remove( 42 ); assertTrue( "set: " + set + ", collection: " + collection, set.retainAll( collection ) ); assertEquals( keys.length - 1, set.size() ); assertEquals( keys.length - 1, map.size() ); } public void testKeySetRetainAllArray() { int[] keys = {1138, 42, 86, 99, 101, 727, 117}; long[] vals = new long[keys.length]; TIntLongMap map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { vals[i] = keys[i] * 2; map.put( keys[i], vals[i] ); } TIntSet set = map.keySet(); assertEquals( map.size(), set.size() ); assertFalse( set.isEmpty() ); // test raw array map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { vals[i] = keys[i] * 2; map.put( keys[i], vals[i] ); } set = map.keySet(); assertFalse( set.retainAll( keys ) ); assertTrue( set.containsAll( keys ) ); keys[3] = keys[3] + 1; assertTrue( set.retainAll( keys ) ); keys[3] = keys[3] - 1; assertEquals( "removed: " + keys[3] + ", set: " + set, keys.length - 1, set.size() ); assertEquals( "removed: " + keys[3] + ", set: " + set + "\nmap: " + map, set.size(), map.size() ); } public void testKeySetRemoveAllCollection() { int[] keys = {1138, 42, 86, 99, 101, 727, 117}; long[] vals = new long[keys.length]; TIntLongMap map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { vals[i] = keys[i] * 2; map.put( keys[i], vals[i] ); } TIntSet set = map.keySet(); assertEquals( map.size(), set.size() ); assertFalse( set.isEmpty() ); // test with a java.util.Map Set java_set = new HashSet(); assertFalse( set.removeAll( java_set ) ); assertEquals( keys.length, set.size() ); assertEquals( keys.length, map.size() ); for ( int i = 0; i < keys.length; i++ ) { assertTrue( set.contains( keys[i] ) ); assertTrue( map.containsKey( keys[i] ) ); } for ( int i = 0; i < keys.length; i++ ) { java_set.add( Integer.valueOf( keys[i] ) ); } java_set.remove( 42 ); assertTrue( "set should have been modified: " + set + ", java: " + java_set, set.removeAll( java_set ) ); assertEquals( "set: " + set, 1, set.size() ); assertEquals( "set: " + set, 1, map.size() ); for ( int i = 0; i < keys.length; i++ ) { if ( keys[i] == 42 ) { assertTrue( set.contains( keys[i] ) ); assertTrue( map.containsKey( keys[i] ) ); } else { assertFalse( set.contains( keys[i] ) ); assertFalse( map.containsKey( keys[i] ) ); } } } public void testKeySetRemoveAllTCollection() { int[] keys = {1138, 42, 86, 99, 101, 727, 117}; long[] vals = new long[keys.length]; TIntLongMap map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { vals[i] = keys[i] * 2; map.put( keys[i], vals[i] ); } TIntSet set = map.keySet(); assertEquals( map.size(), set.size() ); assertFalse( set.isEmpty() ); assertTrue( set.removeAll( set ) ); assertTrue( set.isEmpty() ); // repopulate the set. map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { vals[i] = keys[i] * 2; map.put( keys[i], vals[i] ); } set = map.keySet(); // With empty set TIntSet tintset = new TIntHashSet(); assertFalse( "set: " + set + ", collection: " + tintset, set.removeAll( tintset ) ); // With partial set tintset = new TIntHashSet( keys ); tintset.remove( 42 ); assertTrue( "set: " + set + ", collection: " + tintset, set.removeAll( tintset ) ); assertEquals( "set: " + set, 1, set.size() ); assertEquals( "set: " + set, 1, map.size() ); for ( int i = 0; i < keys.length; i++ ) { if ( keys[i] == 42 ) { assertTrue( set.contains( keys[i] ) ); assertTrue( map.containsKey( keys[i] ) ); } else { assertFalse( set.contains( keys[i] ) ); assertFalse( map.containsKey( keys[i] ) ); } } // repopulate the set. map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { vals[i] = keys[i] * 2; map.put( keys[i], vals[i] ); } set = map.keySet(); // Empty list TIntCollection collection = new TIntArrayList(); assertFalse( "set: " + set + ", collection: " + collection, set.removeAll( collection ) ); // partial list collection = new TIntArrayList( keys ); collection.remove( 42 ); assertTrue( "set: " + set + ", collection: " + collection, set.removeAll( collection ) ); assertEquals( "set: " + set, 1, set.size() ); assertEquals( "set: " + set, 1, map.size() ); for ( int i = 0; i < keys.length; i++ ) { if ( keys[i] == 42 ) { assertTrue( set.contains( keys[i] ) ); assertTrue( map.containsKey( keys[i] ) ); } else { assertFalse( set.contains( keys[i] ) ); assertFalse( map.containsKey( keys[i] ) ); } } } public void testKeySetRemoveAllArray() { int[] keys = {1138, 42, 86, 99, 101, 727, 117}; long[] vals = new long[keys.length]; TIntLongMap map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { vals[i] = keys[i] * 2; map.put( keys[i], vals[i] ); } TIntSet set = map.keySet(); assertEquals( map.size(), set.size() ); assertFalse( set.isEmpty() ); // test raw array map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { vals[i] = keys[i] * 2; map.put( keys[i], vals[i] ); } set = map.keySet(); keys[3] = keys[3] + 1; assertTrue( set.removeAll( keys ) ); keys[3] = keys[3] - 1; assertEquals( "removed: " + keys[3] + ", set: " + set, 1, set.size() ); assertEquals( "removed: " + keys[3] + ", set: " + set + "\nmap: " + map, set.size(), map.size() ); } public void testKeySetForEach() { int[] keys = {1138, 42, 86, 99, 101, 727, 117}; long[] vals = new long[keys.length]; TIntLongMap map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { vals[i] = keys[i] * 2; map.put( keys[i], vals[i] ); } TIntSet set = map.keySet(); assertEquals( map.size(), set.size() ); assertFalse( set.isEmpty() ); class ForEach implements TIntProcedure { TIntList built = new TIntArrayList(); public boolean execute( int value ) { built.add( value ); return true; } TIntList getBuilt() { return built; } } ForEach foreach = new ForEach(); set.forEach( foreach ); TIntList built = foreach.getBuilt(); for ( int i = 0; i < set.size(); i++ ) { assertTrue( set.contains( built.get( i ) ) ); } } public void testKeySetEquals() { int[] keys = {1138, 42, 86, 99, 101, 727, 117}; long[] vals = new long[keys.length]; TIntLongMap map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { vals[i] = keys[i] * 2; map.put( keys[i], vals[i] ); } TIntSet set = map.keySet(); assertEquals( map.size(), set.size() ); assertFalse( set.isEmpty() ); TIntSet other = new TIntHashSet(); other.addAll( keys ); assertTrue( "sets incorrectly not equal: " + set + ", " + other, set.equals( other ) ); int[] mismatched = {72, 49, 53, 1024, 999}; TIntSet unequal = new TIntHashSet(); unequal.addAll( mismatched ); assertFalse( "sets incorrectly equal: " + set + ", " + unequal, set.equals( unequal ) ); // Change length, different code branch unequal.add( 1 ); assertFalse( "sets incorrectly equal: " + set + ", " + unequal, set.equals( unequal ) ); assertFalse( "set incorrectly equals a random object", set.equals( new Object() ) ); } public void testKeySetHashCode() { int[] keys = {1138, 42, 86, 99, 101, 727, 117}; long[] vals = new long[keys.length]; TIntLongMap map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { vals[i] = keys[i] * 2; map.put( keys[i], vals[i] ); } TIntSet set = map.keySet(); assertEquals( map.size(), set.size() ); assertFalse( set.isEmpty() ); TIntSet other = new TIntHashSet(); other.addAll( keys ); assertTrue( "hashcodes incorrectly not equal: " + set + ", " + other, set.hashCode() == other.hashCode() ); int[] mismatched = {72, 49, 53, 1024, 999}; TIntSet unequal = new TIntHashSet(); unequal.addAll( mismatched ); assertFalse( "hashcodes unlikely equal: " + set + ", " + unequal, set.hashCode() == unequal.hashCode() ); } public void testKeySetIterator() { int[] keys = {1138, 42, 86, 99, 101, 727, 117}; long[] vals = new long[keys.length]; TIntLongMap map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { vals[i] = keys[i] * 2; map.put( keys[i], vals[i] ); } TIntList list = new TIntArrayList( keys ); TIntSet set = map.keySet(); assertEquals( map.getNoEntryKey(), set.getNoEntryValue() ); // test basic iterator function. TIntIterator iter = set.iterator(); while ( iter.hasNext() ) { int key = iter.next(); assertTrue( "key set should only contain keys: " + key + ", set; " + set, list.contains( key ) ); } assertFalse( iter.hasNext() ); try { iter.next(); fail( "Expect NoSuchElementException" ); } catch ( NoSuchElementException ex ) { // Expected. } // Start over with new iterator -- test iter.remove() iter = set.iterator(); while ( iter.hasNext() ) { int key = iter.next(); assertTrue( "key set should only contain keys: " + key + ", set; " + set, list.contains( key ) ); if ( key == keys[3] ) { iter.remove(); assertFalse( "set contains removed element: " + key + ", set: " + set, set.contains( key ) ); } } assertEquals( map.size(), set.size() ); assertEquals( keys.length - 1, map.size() ); assertEquals( map.getNoEntryValue(), map.get( keys[3] ) ); } public void testKeys() { TIntLongMap map = new TIntLongHashMap(); map.put( KEY_ONE, 10 ); map.put( KEY_TWO, 20 ); assertEquals( 2, map.size() ); int[] keys = map.keys( new int[map.size()] ); assertEquals( 2, keys.length ); TIntList keys_list = new TIntArrayList( keys ); assertTrue( keys_list.contains( KEY_ONE ) ); assertTrue( keys_list.contains( KEY_TWO ) ); int[] keys2 = map.keys(); assertEquals( 2, keys2.length ); TIntList keys_list2 = new TIntArrayList( keys2 ); assertTrue( keys_list2.contains( KEY_ONE ) ); assertTrue( keys_list2.contains( KEY_TWO ) ); int element_count = 20; map = new TIntLongHashMap(); for ( int i = 0; i < element_count; i++ ) { map.put( i, i * i ); } assertEquals( element_count, map.size() ); keys = map.keys( new int[0] ); Arrays.sort( keys ); assertEquals( element_count, keys.length ); for ( int i = 0; i < element_count; i++ ) { assertEquals( "expected: " + i + " got: " + keys[i] + ", i: " + i + ", keys: " + Arrays.toString( keys ), i, keys[i] ); assertEquals( i * i, map.get( keys[i] ) ); } } public void testValueCollectionMisc() { int[] keys = {1138, 42, 86, 99, 101, 727, 117}; long[] vals = new long[keys.length]; TIntLongMap map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { vals[i] = keys[i] * 2; map.put( keys[i], vals[i] ); } TLongCollection values = map.valueCollection(); long[] sorted_keys = new long[ vals.length ]; System.arraycopy( vals, 0, sorted_keys, 0, vals.length ); Arrays.sort( sorted_keys ); long[] setarray = values.toArray(); Arrays.sort( setarray ); assertTrue( "expected: " + Arrays.toString( sorted_keys ) + ", was: " + Arrays.toString( setarray ), Arrays.equals( sorted_keys, setarray ) ); setarray = values.toArray( new long[0] ); Arrays.sort( setarray ); assertTrue( "expected: " + Arrays.toString( sorted_keys ) + ", was: " + Arrays.toString( setarray ), Arrays.equals( sorted_keys, setarray ) ); assertFalse( "remove of element not in collection succeded: " + values, values.remove( 1 ) ); assertEquals( keys.length, values.size() ); assertEquals( keys.length, map.size() ); assertTrue( "remove of element in collection failed: " + values, values.remove( 42 * 2 ) ); assertEquals( keys.length - 1, values.size() ); assertEquals( keys.length - 1, map.size() ); try { values.add( 42 ); fail( "Expected UnsupportedOperationException" ); } catch ( UnsupportedOperationException ex ) { // Expected } } public void testValueCollectionContainsAll() { int[] keys = {1138, 42, 86, 99, 101, 727, 117}; long[] vals = new long[keys.length]; TIntLongMap map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { vals[i] = keys[i] * 2; map.put( keys[i], vals[i] ); } TLongCollection values = map.valueCollection(); assertEquals( map.size(), values.size() ); assertFalse( values.isEmpty() ); // test with a java.util.Map Set java_set = new HashSet(); for ( int i = 0; i < vals.length; i++ ) { java_set.add( Long.valueOf( vals[i] ) ); } assertTrue( values.containsAll( java_set ) ); java_set.add( Integer.valueOf( 12 ) ); assertFalse( values.containsAll( java_set ) ); java_set.remove( Integer.valueOf( 12 ) ); assertTrue( values.containsAll( java_set ) ); java_set.add( Long.valueOf( 12 ) ); assertFalse( values.containsAll( java_set ) ); // test with a TCollection TLongSet tintset = new TLongHashSet( vals ); assertTrue( values.containsAll( tintset ) ); tintset.add( 12 ); assertFalse( values.containsAll( tintset ) ); // test raw array assertTrue( values.containsAll( vals ) ); vals[3] = vals[3] + 1; assertFalse( values.containsAll( vals ) ); } public void testValueCollectionAddAll() { int[] keys = {1138, 42, 86, 99, 101, 727, 117}; long[] vals = new long[keys.length]; TIntLongMap map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { vals[i] = keys[i] * 2; map.put( keys[i], vals[i] ); } TLongCollection values = map.valueCollection(); assertEquals( map.size(), values.size() ); assertFalse( values.isEmpty() ); // test with a java.util.Map Set java_set = new HashSet(); for ( int i = 0; i < vals.length; i++ ) { java_set.add( Long.valueOf( vals[i] ) ); } try { values.addAll( java_set ); fail( "Expected UnsupportedOperationException" ); } catch ( UnsupportedOperationException ex ) { // Expected } try { values.addAll( values ); fail( "Expected UnsupportedOperationException" ); } catch ( UnsupportedOperationException ex ) { // Expected } try { values.addAll( vals ); fail( "Expected UnsupportedOperationException" ); } catch ( UnsupportedOperationException ex ) { // Expected } } public void testValueCollectionRetainAllCollection() { int[] keys = {1138, 42, 86, 99, 101, 727, 117}; long[] vals = new long[keys.length]; TIntLongMap map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { vals[i] = keys[i] * 2; map.put( keys[i], vals[i] ); } TLongCollection values = map.valueCollection(); assertEquals( map.size(), values.size() ); assertFalse( values.isEmpty() ); // test with a java.util.Map Set java_set = new HashSet(); for ( int i = 0; i < vals.length; i++ ) { java_set.add( Long.valueOf( vals[i] ) ); } assertFalse( values.retainAll( java_set ) ); assertEquals( keys.length, values.size() ); assertEquals( keys.length, map.size() ); for ( int i = 0; i < keys.length; i++ ) { assertTrue( values.contains( vals[i] ) ); assertTrue( map.containsValue( vals[i] ) ); } java_set.remove( Long.valueOf( 42 * 2 ) ); assertTrue( "collection should have been modified: " + values + "\njava: " + java_set, values.retainAll( java_set ) ); assertEquals( keys.length - 1, values.size() ); assertEquals( keys.length - 1, map.size() ); for ( int i = 0; i < keys.length; i++ ) { if ( keys[i] != 42 ) { assertTrue( values.contains( vals[i] ) ); assertTrue( map.containsValue( vals[i] ) ); } else { assertFalse( values.contains( vals[i] ) ); assertFalse( map.containsValue( vals[i] ) ); } } } public void testValueCollectionRetainAllTCollection() { int[] keys = {1138, 42, 86, 99, 101, 727, 117}; long[] vals = new long[keys.length]; TIntLongMap map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { vals[i] = keys[i] * 2; map.put( keys[i], vals[i] ); } TLongCollection values = map.valueCollection(); assertEquals( map.size(), values.size() ); assertFalse( values.isEmpty() ); assertFalse( values.retainAll( values ) ); // test with a TCollection TLongSet tintset = new TLongHashSet( vals ); assertFalse( "values: " + values + ", collection: " + tintset, values.retainAll( tintset ) ); TLongCollection collection = new TLongArrayList( vals ); assertFalse( "values: " + values + ", collection: " + collection, values.retainAll( collection ) ); collection.remove( 42 * 2 ); assertTrue( "values: " + values + ", collection: " + collection, values.retainAll( collection ) ); assertEquals( keys.length - 1, values.size() ); assertEquals( keys.length - 1, map.size() ); } public void testValueCollectionRetainAllArray() { int[] keys = {1138, 42, 86, 99, 101, 727, 117}; long[] vals = new long[keys.length]; TIntLongMap map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { vals[i] = keys[i] * 2; map.put( keys[i], vals[i] ); } TLongCollection values = map.valueCollection(); assertEquals( map.size(), values.size() ); assertFalse( values.isEmpty() ); // test raw array map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { vals[i] = keys[i] * 2; map.put( keys[i], vals[i] ); } values = map.valueCollection(); assertFalse( values.retainAll( vals ) ); assertTrue( values.containsAll( vals ) ); vals[3] = vals[3] + 1; assertTrue( values.retainAll( vals ) ); vals[3] = vals[3] - 1; assertEquals( "removed: " + keys[3] + ", values: " + values, keys.length - 1, values.size() ); assertEquals( "removed: " + keys[3] + ", set: " + values + "\nmap: " + map, values.size(), map.size() ); } public void testValueCollectionRemoveAllCollection() { int[] keys = {1138, 42, 86, 99, 101, 727, 117}; long[] vals = new long[keys.length]; TIntLongMap map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { vals[i] = keys[i] * 2; map.put( keys[i], vals[i] ); } TLongCollection values = map.valueCollection(); assertEquals( map.size(), values.size() ); assertFalse( values.isEmpty() ); // test with a java.util.Map Set java_set = new HashSet(); assertFalse( values.removeAll( java_set ) ); assertEquals( vals.length, values.size() ); assertEquals( vals.length, map.size() ); for ( int i = 0; i < keys.length; i++ ) { assertTrue( values.contains( vals[i] ) ); assertTrue( map.containsValue( vals[i] ) ); } for ( int i = 0; i < vals.length; i++ ) { java_set.add( Long.valueOf( vals[i] ) ); } java_set.remove( Long.valueOf( 42 * 2 ) ); assertTrue( "values should have been modified: " + values + ", java: " + java_set, values.removeAll( java_set ) ); assertEquals( "set: " + values, 1, values.size() ); assertEquals( "set: " + values, 1, map.size() ); for ( int i = 0; i < vals.length; i++ ) { if ( vals[i] == 42 * 2 ) { assertTrue( values.contains( vals[i] ) ); assertTrue( map.containsValue( vals[i] ) ); } else { assertFalse( values.contains( vals[i] ) ); assertFalse( map.containsValue( vals[i] ) ); } } } public void testValueCollectionRemoveAllTCollection() { int[] keys = {1138, 42, 86, 99, 101, 727, 117}; long[] vals = new long[keys.length]; TIntLongMap map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { vals[i] = keys[i] * 2; map.put( keys[i], vals[i] ); } TLongCollection values = map.valueCollection(); assertEquals( map.size(), values.size() ); assertFalse( values.isEmpty() ); assertTrue( values.removeAll( values ) ); assertTrue( values.isEmpty() ); // repopulate the set. map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { vals[i] = keys[i] * 2; map.put( keys[i], vals[i] ); } values = map.valueCollection(); // With empty set TLongSet tlongset = new TLongHashSet(); assertFalse( "values: " + values + ", collection: " + tlongset, values.removeAll( tlongset ) ); // With partial set tlongset = new TLongHashSet( vals ); tlongset.remove( 42 * 2 ); assertTrue( "values: " + values + ", collection: " + tlongset, values.removeAll( tlongset ) ); assertEquals( "set: " + values, 1, values.size() ); assertEquals( "set: " + values, 1, map.size() ); for ( int i = 0; i < keys.length; i++ ) { if ( keys[i] == 42 ) { assertTrue( values.contains( vals[i] ) ); assertTrue( map.containsValue( vals[i] ) ); } else { assertFalse( values.contains( vals[i] ) ); assertFalse( map.containsValue( vals[i] ) ); } } // repopulate the set. map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { vals[i] = keys[i] * 2; map.put( keys[i], vals[i] ); } values = map.valueCollection(); // Empty list TLongCollection collection = new TLongArrayList(); assertFalse( "values: " + values + ", collection: " + collection, values.removeAll( collection ) ); // partial list collection = new TLongArrayList( vals ); collection.remove( 42 * 2 ); assertTrue( "values: " + values + ", collection: " + collection, values.removeAll( collection ) ); assertEquals( "values: " + values, 1, values.size() ); assertEquals( "values: " + values, 1, map.size() ); for ( int i = 0; i < keys.length; i++ ) { if ( vals[i] == 42 * 2 ) { assertTrue( values.contains( vals[i] ) ); assertTrue( map.containsValue( vals[i] ) ); } else { assertFalse( values.contains( vals[i] ) ); assertFalse( map.containsValue( vals[i] ) ); } } } public void testValueCollectionRemoveAllArray() { int[] keys = {1138, 42, 86, 99, 101, 727, 117}; long[] vals = new long[keys.length]; TIntLongMap map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { vals[i] = keys[i] * 2; map.put( keys[i], vals[i] ); } TLongCollection values = map.valueCollection(); assertEquals( map.size(), values.size() ); assertFalse( values.isEmpty() ); // test raw array map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { vals[i] = keys[i] * 2; map.put( keys[i], vals[i] ); } values = map.valueCollection(); vals[3] = vals[3] + 1; assertTrue( values.removeAll( vals ) ); vals[3] = vals[3] - 1; assertEquals( "removed: " + keys[3] + ", values: " + values, 1, values.size() ); assertEquals( "removed: " + keys[3] + ", values: " + values + "\nmap: " + map, values.size(), map.size() ); } public void testValueCollectionForEach() { int[] keys = {1138, 42, 86, 99, 101, 727, 117}; long[] vals = new long[keys.length]; TIntLongMap map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { vals[i] = keys[i] * 2; map.put( keys[i], vals[i] ); } TLongCollection values = map.valueCollection(); assertEquals( map.size(), values.size() ); assertFalse( values.isEmpty() ); class ForEach implements TLongProcedure { TLongList built = new TLongArrayList(); public boolean execute( long value ) { built.add( value ); return true; } TLongList getBuilt() { return built; } } ForEach foreach = new ForEach(); values.forEach( foreach ); TLongList built = foreach.getBuilt(); for ( int i = 0; i < values.size(); i++ ) { assertTrue( values.contains( built.get( i ) ) ); } } public void testValueCollectionEquals() { int[] keys = {1138, 42, 86, 99, 101, 727, 117}; long[] vals = new long[keys.length]; TIntLongMap map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { vals[i] = keys[i] * 2; map.put( keys[i], vals[i] ); } TLongCollection values = map.valueCollection(); assertEquals( map.size(), values.size() ); assertFalse( values.isEmpty() ); assertEquals( values, values ); TLongList values_list = new TLongArrayList( values ); assertFalse( "collections should not be equal: " + values + ", " + values_list, values.equals( values_list ) ); TLongList list = new TLongArrayList( vals ); values_list.sort(); list.sort(); assertTrue( "collections incorrectly not equal: " + values_list + ", " + list, values_list.equals( list ) ); assertTrue( "collections incorrectly not equal: " + values_list + ", " + list, values_list.equals( list ) ); long[] mismatched = {72, 49, 53, 1024, 999}; TLongCollection unequal = new TLongArrayList(); unequal.addAll( mismatched ); assertFalse( "collections incorrectly equal: " + values_list + ", " + unequal, values_list.equals( unequal ) ); // Change length, different code branch unequal.add( 1 ); assertFalse( "collections incorrectly equal: " + values_list + ", " + unequal, values_list.equals( unequal ) ); assertFalse( "values incorrectly equals a random object", values_list.equals( new Object() ) ); // value in map twice, in list twice. list = new TLongArrayList( vals ); map.put( 1, vals[0] ); values_list = new TLongArrayList( map.valueCollection() ); list.add( vals[0] ); values_list.sort(); list.sort(); assertTrue( "collections incorrectly not equal: " + values_list + ", " + list, values_list.equals( list ) ); // value in the map twice, same length list, but value only in list once. list = new TLongArrayList( vals ); list.add( -1 ); list.sort(); assertFalse( "collections incorrectly equal: " + values_list + ", " + list, values_list.equals( list ) ); } public void testValueCollectionHashCode() { int[] keys = {1138, 42, 86, 99, 101, 727, 117}; long[] vals = new long[keys.length]; TIntLongMap map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { vals[i] = keys[i] * 2; map.put( keys[i], vals[i] ); } TLongCollection values = map.valueCollection(); assertEquals( map.size(), values.size() ); assertFalse( values.isEmpty() ); assertEquals( "hashcodes incorrectly not equal: " + map + ", " + values, values.hashCode(), values.hashCode() ); assertFalse( "hashcodes incorrectly equal: " + map + ", " + values, map.hashCode() == values.hashCode() ); } public void testValueCollectionIterator() { int[] keys = {1138, 42, 86, 99, 101, 727, 117}; long[] vals = new long[keys.length]; TIntLongMap map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { vals[i] = keys[i] * 2; map.put( keys[i], vals[i] ); } TLongList list = new TLongArrayList( vals ); TLongCollection set = map.valueCollection(); assertEquals( map.getNoEntryValue(), set.getNoEntryValue() ); // test basic iterator function. TLongIterator iter = set.iterator(); while ( iter.hasNext() ) { long val = iter.next(); assertTrue( "value collection should only contain values: " + val + ", set; " + set, list.contains( val ) ); } assertFalse( iter.hasNext() ); try { iter.next(); fail( "Expect NoSuchElementException" ); } catch ( NoSuchElementException ex ) { // Expected. } // Start over with new iterator -- test iter.remove() iter = set.iterator(); while ( iter.hasNext() ) { long val = iter.next(); assertTrue( "value collection should only contain values: " + val + ", set; " + set, list.contains( val ) ); if ( val == vals[3] ) { iter.remove(); assertFalse( "set contains removed element: " + val + ", set: " + set, set.contains( val ) ); } } assertEquals( map.size(), set.size() ); assertEquals( keys.length - 1, map.size() ); assertEquals( map.getNoEntryValue(), map.get( keys[3] ) ); } public void testValues() { TIntLongMap map = new TIntLongHashMap(); map.put( KEY_ONE, 1 ); map.put( KEY_TWO, 2 ); assertEquals( 2, map.size() ); long[] values = map.values( new long[map.size()] ); assertEquals( 2, values.length ); TLongList values_list = new TLongArrayList( values ); assertTrue( values_list.contains( 1 ) ); assertTrue( values_list.contains( 2 ) ); long[] values2 = map.values(); assertEquals( 2, values2.length ); TLongList keys_list2 = new TLongArrayList( values2 ); assertTrue( keys_list2.contains( 1 ) ); assertTrue( keys_list2.contains( 2 ) ); int element_count = 20; map = new TIntLongHashMap(); for ( int i = 0; i < element_count; i++ ) { map.put( i, i * i ); } assertEquals( element_count, map.size() ); long[] vals = map.values( new long[0] ); Arrays.sort( vals ); assertEquals( element_count, vals.length ); for ( int i = 0; i < element_count; i++ ) { assertEquals( "expected: " + i * i + " got: " + vals[i] + ", i: " + i + ", vals: " + Arrays.toString( vals ), i * i, vals[i] ); assertEquals( i * i, map.get( i ) ); } } public void testForEachKey() { int element_count = 20; TIntLongMap map = new TIntLongHashMap(); for ( int i = 1; i <= element_count; i++ ) { map.put( i, i * i ); } class ForEach implements TIntProcedure { TIntList built = new TIntArrayList(); public boolean execute( int value ) { built.add( value ); return true; } TIntList getBuilt() { return built; } } ForEach foreach = new ForEach(); map.forEachKey( foreach ); TIntList built = foreach.getBuilt(); TIntList keys = new TIntArrayList( map.keys() ); assertEquals( keys, built ); built.sort(); keys.sort(); assertEquals( keys, built ); class ForEachFalse implements TIntProcedure { TIntList built = new TIntArrayList(); public boolean execute( int value ) { built.add( value ); return false; } TIntList getBuilt() { return built; } } ForEachFalse foreach_false = new ForEachFalse(); map.forEachKey( foreach_false ); built = foreach_false.getBuilt(); keys = new TIntArrayList( map.keys() ); assertEquals( 1, built.size() ); assertEquals( keys.get( 0 ), built.get( 0 ) ); } public void testForEachValue() { int element_count = 20; TIntLongMap map = new TIntLongHashMap(); for ( int i = 1; i <= element_count; i++ ) { map.put( i, i * i ); } class ForEach implements TLongProcedure { TLongList built = new TLongArrayList(); public boolean execute( long value ) { built.add( value ); return true; } TLongList getBuilt() { return built; } } ForEach foreach = new ForEach(); map.forEachValue( foreach ); TLongList built = foreach.getBuilt(); TLongList vals = new TLongArrayList( map.values() ); assertEquals( vals, built ); built.sort(); vals.sort(); assertEquals( vals, built ); class ForEachFalse implements TLongProcedure { TLongList built = new TLongArrayList(); public boolean execute( long value ) { built.add( value ); return false; } TLongList getBuilt() { return built; } } ForEachFalse foreach_false = new ForEachFalse(); map.forEachValue( foreach_false ); built = foreach_false.getBuilt(); vals = new TLongArrayList( map.values() ); assertEquals( 1, built.size() ); assertEquals( vals.get( 0 ), built.get( 0 ) ); } public void testForEachEntry() { int element_count = 20; TIntLongMap map = new TIntLongHashMap(); for ( int i = 1; i <= element_count; i++ ) { map.put( i, i * i ); } class ForEach implements TIntLongProcedure { TIntLongMap built = new TIntLongHashMap(); public boolean execute( int key, long value ) { built.put( key, value ); return true; } TIntLongMap getBuilt() { return built; } } ForEach foreach = new ForEach(); map.forEachEntry( foreach ); TIntLongMap built = foreach.getBuilt(); assertEquals( map, built ); } public void testTransformValues() { int element_count = 20; TIntLongMap map = new TIntLongHashMap(); for ( int i = 1; i <= element_count; i++ ) { map.put( i, i ); } class TransformValues implements TLongFunction { public long execute( long value ) { return value * value; } } TransformValues foreach = new TransformValues(); map.transformValues( foreach ); for ( int i = 1; i <= element_count; i++ ) { assertEquals( i * i, map.get( i ) ); } } public void testRetainEntries() { int element_count = 20; TIntLongMap map = new TIntLongHashMap(); for ( int i = 1; i <= element_count; i++ ) { map.put( i, i * i ); } class ForEach implements TIntLongProcedure { TIntLongMap built = new TIntLongHashMap(); // Evens in one map, odds in another. public boolean execute( int key, long value ) { if ( key % 2 == 1 ) { built.put( key, value ); return false; } return true; } TIntLongMap getBuilt() { return built; } } ForEach foreach = new ForEach(); map.retainEntries( foreach ); TIntLongMap built = foreach.getBuilt(); for ( int i = 1; i <= element_count; i++ ) { if ( i % 2 == 0 ) { assertTrue( map.containsKey( i ) ); assertFalse( built.containsKey( i ) ); assertTrue( map.containsValue( i * i ) ); assertFalse( built.containsValue( i * i ) ); assertEquals( i * i, map.get( i ) ); } else { assertFalse( map.containsKey( i ) ); assertTrue( built.containsKey( i ) ); assertFalse( map.containsValue( i * i ) ); assertTrue( built.containsValue( i * i ) ); assertEquals( i * i, built.get( i ) ); } } } public void testIncrement() { int element_count = 20; TIntLongMap map = new TIntLongHashMap(); for ( int i = 1; i <= element_count; i++ ) { map.put( i, i * i ); } for ( int i = 1; i <= element_count; i++ ) { if ( i % 2 == 0 ) { map.increment( i ); } } for ( int i = 1; i <= element_count; i++ ) { if ( i % 2 == 0 ) { assertEquals( i * i + 1, map.get( i ) ); } else { assertEquals( i * i, map.get( i ) ); } } } public void testDecorator() { // TByteIntHashMap map = new TByteIntHashMap(); // // map.put( KEY_ONE, 1 ); // map.put( KEY_TWO, 2 ); // // Map decorator = new TByteIntHashMapDecorator( map ); // // assertEquals( 2, decorator.size() ); // assertEquals( Integer.valueOf( 1 ), decorator.get( Byte.valueOf( KEY_ONE ) ) ); // assertEquals( Integer.valueOf( 2 ), decorator.get( Byte.valueOf( KEY_TWO ) ) ); // // Set decorator_keys = decorator.keySet(); // assertEquals( 2, decorator_keys.size() ); // Iterator it = decorator_keys.iterator(); // int count = 0; // while ( it.hasNext() ) { // count++; // System.out.println( it.next() ); // } // assertEquals( 2, count ); // // assertSame( map, ( (TByteIntHashMapDecorator) decorator ).getMap() ); } public void testIterator() { TIntLongMap map = new TIntLongHashMap(); TIntLongIterator iterator = map.iterator(); assertFalse( iterator.hasNext() ); map.put( KEY_ONE, 1 ); map.put( KEY_TWO, 2 ); iterator = map.iterator(); assertTrue( iterator.hasNext() ); iterator.advance(); boolean found_one; if ( iterator.value() == 1 ) { assertEquals( KEY_ONE, iterator.key() ); found_one = true; } else { assertEquals( 2, iterator.value() ); assertEquals( KEY_TWO, iterator.key() ); found_one = false; } assertTrue( iterator.hasNext() ); iterator.advance(); if ( found_one ) { assertEquals( 2, iterator.value() ); assertEquals( KEY_TWO, iterator.key() ); } else { assertEquals( 1, iterator.value() ); assertEquals( KEY_ONE, iterator.key() ); } assertFalse( iterator.hasNext() ); int key = iterator.key(); long old_value = iterator.value(); if ( found_one ) { assertEquals( 2, old_value ); assertEquals( KEY_TWO, iterator.key() ); } else { assertEquals( 1, old_value ); assertEquals( KEY_ONE, iterator.key() ); } assertEquals( old_value, iterator.setValue( old_value * 10 ) ); assertEquals( old_value * 10, iterator.value() ); assertFalse( map.containsValue( old_value ) ); assertTrue( map.containsValue( old_value * 10 ) ); assertEquals( old_value * 10, map.get( key ) ); iterator.remove(); assertFalse( map.containsValue( old_value * 10 ) ); assertEquals( map.getNoEntryValue(), map.get( key ) ); assertEquals( 1, map.size() ); } public void testAdjustValue() { TIntLongHashMap map = new TIntLongHashMap(); map.put( KEY_ONE, 1 ); boolean changed = map.adjustValue( KEY_ONE, 1 ); assertTrue( changed ); assertEquals( 2, map.get( KEY_ONE ) ); changed = map.adjustValue( KEY_ONE, 5 ); assertTrue( changed ); assertEquals( 7, map.get( KEY_ONE ) ); changed = map.adjustValue( KEY_ONE, -3 ); assertTrue( changed ); assertEquals( 4, map.get( KEY_ONE ) ); changed = map.adjustValue( KEY_TWO, 1 ); assertFalse( changed ); assertFalse( map.containsKey( KEY_TWO ) ); } public void testAdjustOrPutValue() { TIntLongMap map = new TIntLongHashMap(); map.put( KEY_ONE, 1 ); long new_value = map.adjustOrPutValue( KEY_ONE, 1, 100 ); assertEquals( 2, new_value ); assertEquals( 2, map.get( KEY_ONE ) ); new_value = map.adjustOrPutValue( KEY_ONE, 5, 100 ); assertEquals( 7, new_value ); assertEquals( 7, map.get( KEY_ONE ) ); new_value = map.adjustOrPutValue( KEY_ONE, -3, 100 ); assertEquals( 4, new_value ); assertEquals( 4, map.get( KEY_ONE ) ); new_value = map.adjustOrPutValue( KEY_TWO, 1, 100 ); assertEquals( 100, new_value ); assertTrue( map.containsKey( KEY_TWO ) ); assertEquals( 100, map.get( KEY_TWO ) ); new_value = map.adjustOrPutValue( KEY_TWO, 1, 100 ); assertEquals( 101, new_value ); assertEquals( 101, map.get( KEY_TWO ) ); } /** * Test for tracking issue #1204014. +0.0 and -0.0 have different bit patterns, but * should be counted the same as keys in a map. Checks for doubles and floats. */ // TODO: move to TPrimitiveObjectHashMap test. public void testFloatZeroHashing() { // TDoubleObjectHashMap po_double_map = new TDoubleObjectHashMap(); // TDoubleIntHashMap pp_double_map = new TDoubleIntHashMap(); // TFloatObjectHashMap po_float_map = new TFloatObjectHashMap(); // TFloatIntHashMap pp_float_map = new TFloatIntHashMap(); // // final double zero_double = 0.0; // final double negative_zero_double = -zero_double; // final float zero_float = 0.0f; // final float negative_zero_float = -zero_float; // // // Sanity check... make sure I'm really creating two different values. // final String zero_bits_double = // Long.toBinaryString( Double.doubleToLongBits( zero_double ) ); // final String negative_zero_bits_double = // Long.toBinaryString( Double.doubleToLongBits( negative_zero_double ) ); // assertFalse( zero_bits_double + " == " + negative_zero_bits_double, // zero_bits_double.equals( negative_zero_bits_double ) ); // // final String zero_bits_float = // Integer.toBinaryString( Float.floatToIntBits( zero_float ) ); // final String negative_zero_bits_float = // Integer.toBinaryString( Float.floatToIntBits( negative_zero_float ) ); // assertFalse( zero_bits_float + " == " + negative_zero_bits_float, // zero_bits_float.equals( negative_zero_bits_float ) ); // // // po_double_map.put( zero_double, "Zero" ); // po_double_map.put( negative_zero_double, "Negative Zero" ); // // pp_double_map.put( zero_double, 0 ); // pp_double_map.put( negative_zero_double, -1 ); // // po_float_map.put( zero_float, "Zero" ); // po_float_map.put( negative_zero_float, "Negative Zero" ); // // pp_float_map.put( zero_float, 0 ); // pp_float_map.put( negative_zero_float, -1 ); // // // assertEquals( 1, po_double_map.size() ); // assertEquals( po_double_map.get( zero_double ), "Negative Zero" ); // assertEquals( po_double_map.get( negative_zero_double ), "Negative Zero" ); // // assertEquals( 1, pp_double_map.size() ); // assertEquals( pp_double_map.get( zero_double ), -1 ); // assertEquals( pp_double_map.get( negative_zero_double ), -1 ); // // assertEquals( 1, po_float_map.size() ); // assertEquals( po_float_map.get( zero_float ), "Negative Zero" ); // assertEquals( po_float_map.get( negative_zero_float ), "Negative Zero" ); // // assertEquals( 1, pp_float_map.size() ); // assertEquals( pp_float_map.get( zero_float ), -1 ); // assertEquals( pp_float_map.get( negative_zero_float ), -1 ); // // // po_double_map.put( zero_double, "Zero" ); // pp_double_map.put( zero_double, 0 ); // po_float_map.put( zero_float, "Zero" ); // pp_float_map.put( zero_float, 0 ); // // // assertEquals( 1, po_double_map.size() ); // assertEquals( po_double_map.get( zero_double ), "Zero" ); // assertEquals( po_double_map.get( negative_zero_double ), "Zero" ); // // assertEquals( 1, pp_double_map.size() ); // assertEquals( pp_double_map.get( zero_double ), 0 ); // assertEquals( pp_double_map.get( negative_zero_double ), 0 ); // // assertEquals( 1, po_float_map.size() ); // assertEquals( po_float_map.get( zero_float ), "Zero" ); // assertEquals( po_float_map.get( negative_zero_float ), "Zero" ); // // assertEquals( 1, pp_float_map.size() ); // assertEquals( pp_float_map.get( zero_float ), 0 ); // assertEquals( pp_float_map.get( negative_zero_float ), 0 ); } public void testPutIfAbsent() { TIntLongMap map = new TIntLongHashMap(); map.put( 1, 10 ); map.put( 2, 20 ); map.put( 3, 30 ); assertEquals( 10, map.putIfAbsent( 1, 111 ) ); assertEquals( 10, map.get( 1 ) ); assertEquals( map.getNoEntryValue(), map.putIfAbsent( 9, 90 ) ); assertEquals( 90, map.get( 9 ) ); } public void testBug2037709() { TIntLongMap m = new TIntLongHashMap(); for ( int i = 0; i < 10; i++ ) { m.put( i, i ); } int sz = m.size(); assertEquals( 10, sz ); int[] keys = new int[sz]; m.keys( keys ); boolean[] seen = new boolean[sz]; Arrays.fill( seen, false ); for ( int i = 0; i < 10; i++ ) { seen[keys[i]] = true; } for ( int i = 0; i < 10; i++ ) { if ( !seen[i] ) { TestCase.fail( "Missing key for: " + i ); } } } public void testEquals() { int[] keys = {1138, 42, 86, 99, 101, 727, 117}; long[] vals = new long[keys.length]; TIntLongMap map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { vals[i] = keys[i] * 2; map.put( keys[i], vals[i] ); } assertEquals( map, map ); TIntIntMap int_map = new TIntIntHashMap(); for ( int i = 0; i < keys.length; i++ ) { int_map.put( keys[i], (int) vals[i] ); } assertFalse( map.equals( int_map ) ); // Change a value.. TIntLongMap unequal = new TIntLongHashMap( map ); map.put( keys[3], vals[3] + 1 ); assertFalse( map.equals( unequal ) ); // Change length unequal = new TIntLongHashMap( map ); map.put( 13, 26 ); assertFalse( map.equals( unequal ) ); } public void testHashCode() { int[] keys = {1138, 42, 86, 99, 101, 727, 117}; long[] vals = new long[keys.length]; TIntLongMap map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { vals[i] = keys[i] * 2; map.put( keys[i], vals[i] ); } TIntLongMap other = new TIntLongHashMap(); other.putAll( map ); assertTrue( "hashcodes incorrectly not equal: " + map + ", " + other, map.hashCode() == other.hashCode() ); TIntLongMap unequal = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { unequal.put( keys[i], keys[i] ); } assertFalse( "hashcodes unlikely equal: " + map + ", " + unequal, map.hashCode() == unequal.hashCode() ); int[] mismatched = {72, 49, 53, 1024, 999}; TIntLongMap mismatched_map = new TIntLongHashMap(); for ( int i = 0; i < mismatched.length; i++ ) { mismatched_map.put( mismatched[i], mismatched[i] * 37 ); } assertFalse( "hashcodes unlikely equal: " + map + ", " + unequal, map.hashCode() == unequal.hashCode() ); } public void testToString() { TIntLongMap m = new TIntLongHashMap(); m.put( 11, 1 ); m.put( 22, 2 ); String to_string = m.toString(); assertTrue( to_string, to_string.equals( "{11=1, 22=2}" ) || to_string.equals( "{22=2, 11=1}" ) ); } public void testSerialize() throws Exception { int[] keys = {1138, 42, 86, 99, 101, 727, 117}; long[] vals = new long[keys.length]; TIntLongMap map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { vals[i] = keys[i] * 2; map.put( keys[i], vals[i] ); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream( baos ); oos.writeObject( map ); ByteArrayInputStream bias = new ByteArrayInputStream( baos.toByteArray() ); ObjectInputStream ois = new ObjectInputStream( bias ); TIntLongMap deserialized = (TIntLongMap) ois.readObject(); assertEquals( map, deserialized ); } /** a non TIntLongHashMap to test putAll exception */ // class BadMap implements TIntLongMap { // public int getNoEntryKey() { return 0; } // public long getNoEntryValue() { return 0; } // public long put( int key, long value ) { return 0; } // public long putIfAbsent( int key, long value ) { return 0; } // public void putAll( Map map ) {} // public void putAll( TIntLongMap map ) {} // public long get( int key ) { return 0; } // public void clear() {} // public long remove( int key ) { return 0; } // public int size() { return 0; } // public TIntSet keySet() { return null; } // public int[] keys() { return new int[0]; } // public int[] keys( int[] array ) { return new int[0]; } // public TLongCollection valueCollection() { return null; } // public long[] values() { return new long[0]; } // public long[] values( long[] array ) { return new long[0]; } // public boolean containsValue( long val ) { return false; } // public boolean containsKey( int key ) { return false; } // public TIntLongIterator iterator() { return null; } // public boolean forEachKey( TIntProcedure procedure ) { return false; } // public boolean forEachValue( TLongProcedure procedure ) { return false; } // public boolean forEachEntry( TIntLongProcedure procedure ) { return false; } // public void transformValues( TLongFunction function ) { } // public boolean retainEntries( TIntLongProcedure procedure ) { return false; } // public boolean increment( int key ) { return false; } // public boolean adjustValue( int key, long amount ) { return false; } // public long adjustOrPutValue( int key, long adjust_amount, long put_amount ) { return 0; } // public boolean isEmpty() { return true; } // } } trove-3.0.3/test/gnu/trove/map/hash/TCustomHashMapTest.java0000644000175000017500000001047011763017634022606 0ustar ericherichpackage gnu.trove.map.hash; import gnu.trove.strategy.HashingStrategy; import junit.framework.TestCase; import java.io.*; import java.util.*; /** * */ public class TCustomHashMapTest extends TestCase { // Example from Trove overview doc public void testArray() { char[] foo = new char[]{ 'a', 'b', 'c' }; char[] bar = new char[]{ 'a', 'b', 'c' }; assertFalse( foo.hashCode() == bar.hashCode() ); //noinspection ArrayEquals assertFalse( foo.equals( bar ) ); HashingStrategy strategy = new ArrayHashingStrategy(); assertTrue( strategy.computeHashCode( foo ) == strategy.computeHashCode( bar ) ); assertTrue( strategy.equals( foo, bar ) ); Map map = new TCustomHashMap( strategy ); map.put( foo, "yay" ); assertTrue( map.containsKey( foo ) ); assertTrue( map.containsKey( bar ) ); assertEquals( "yay", map.get( foo ) ); assertEquals( "yay", map.get( bar ) ); Set keys = map.keySet(); assertTrue( keys.contains( foo ) ); assertTrue( keys.contains( bar ) ); } public void testSerialization() throws Exception { char[] foo = new char[]{ 'a', 'b', 'c' }; char[] bar = new char[]{ 'a', 'b', 'c' }; HashingStrategy strategy = new ArrayHashingStrategy(); Map map = new TCustomHashMap( strategy ); map.put( foo, "yay" ); // Make sure it still works after being serialized ObjectOutputStream oout = null; ByteArrayOutputStream bout = null; ObjectInputStream oin = null; ByteArrayInputStream bin = null; try { bout = new ByteArrayOutputStream(); oout = new ObjectOutputStream( bout ); oout.writeObject( map ); bin = new ByteArrayInputStream( bout.toByteArray() ); oin = new ObjectInputStream( bin ); map = ( Map ) oin.readObject(); } finally { if ( oin != null ) oin.close(); if ( bin != null ) bin.close(); if ( oout != null ) oout.close(); if ( bout != null ) bout.close(); } assertTrue( map.containsKey( foo ) ); assertTrue( map.containsKey( bar ) ); assertEquals( "yay", map.get( foo ) ); assertEquals( "yay", map.get( bar ) ); Set keys = map.keySet(); assertTrue( keys.contains( foo ) ); assertTrue( keys.contains( bar ) ); } static class ByteArrayStrategy implements HashingStrategy { // Copied from Arrays.hashCode, but applied only to the first four bytes public int computeHashCode( byte[] bytes ) { if ( bytes == null ) return 0; int h = 1; for ( int i = 0; i < 4; i++ ) h = 31 * h + bytes[ i ]; return h; } public boolean equals( byte[] o1, byte[] o2 ) { return Arrays.equals( o1, o2 ); } } private static byte[] random( int n, Random rnd ) { byte[] ba = new byte[ n ]; for ( int i = 0; i < ba.length; i++ ) { ba[ i ] = ( byte ) rnd.nextInt(); } return ba; } public void testBug4706479() throws Exception { Random rnd = new Random( 1234 ); TCustomHashMap map = new TCustomHashMap( new ByteArrayStrategy() ); List list = new ArrayList(); List expected = new ArrayList(); for ( int i = 0; i < 1000; i++ ) { byte[] ba = random( 16, rnd ); list.add( ba ); Integer obj = Integer.valueOf( i ); expected.add( obj ); map.put( ba, obj ); } assertEquals( list.size(), map.size() ); // Make sure all the arrays are found in the map for( byte[] array : map.keySet() ) { boolean found_it = false; for( byte[] test : list ) { if ( Arrays.equals( test, array ) ) { found_it = true; break; } } assertTrue( "Unable to find: " + Arrays.toString( array ), found_it ); } // Make sure all the Integers are found in the map for( Integer obj : map.values() ) { assertTrue( "Unable to find: " + obj, expected.contains( obj ) ); } for ( int i = 0; i < expected.size(); i++ ) { assertEquals( expected.get( i ), map.get( list.get( i ) ) ); } // Remove items for ( int i = 0; i < list.size(); i++ ) { assertEquals( expected.get( i ), map.remove( list.get( i ) ) ); } assertEquals( 0, map.size() ); assertTrue( map.isEmpty() ); for ( byte[] aList : list ) { assertNull( map.get( aList ) ); } } } trove-3.0.3/test/gnu/trove/map/hash/THashMapTest.java0000644000175000017500000014114611763017634021420 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001-2006, Eric D. Friedman All Rights Reserved. // Copyright (c) 2009, Rob Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.map.hash; import gnu.trove.function.TObjectFunction; import gnu.trove.impl.hash.HashTestKit; import gnu.trove.impl.hash.TObjectHash; import gnu.trove.procedure.TObjectObjectProcedure; import gnu.trove.procedure.TObjectProcedure; import gnu.trove.set.hash.THashSetTest; import junit.framework.TestCase; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.*; /** * Created: Sat Nov 3 10:31:38 2001 * * @author Eric D. Friedman * @author Rob Eden * @author Jeff Randall * @version $Id: THashMapTest.java,v 1.1.2.7 2010/03/02 04:09:50 robeden Exp $ */ public class THashMapTest extends TestCase { protected THashMap ss_map; protected THashMap si_map; protected int count; public THashMapTest( String name ) { super( name ); } public void setUp() throws Exception { super.setUp(); ss_map = new THashMap(); si_map = new THashMap(); count = 0; } public void tearDown() throws Exception { super.tearDown(); ss_map = null; si_map = null; count = 0; } public void testConstructors() { String[] keys = {"Key1", "Key2", "Key3", "Key4", "Key5"}; String[] values = {"Val1", "Val2", "Val3", "Val4", "Val5"}; for ( int i = 0; i < keys.length; i++ ) { ss_map.put( keys[i], values[i] ); } THashMap sized = new THashMap( 100 ); for ( int i = 0; i < keys.length; i++ ) { sized.put( keys[i], values[i] ); } assertTrue( "maps should be a copy of each other", ss_map.equals( sized ) ); THashMap factor = new THashMap( 100, 1.0f ); for ( int i = 0; i < keys.length; i++ ) { factor.put( keys[i], values[i] ); } assertTrue( "maps should be a copy of each other", ss_map.equals( factor ) ); THashMap copy = new THashMap( ss_map ); assertTrue( "maps should be a copy of each other", ss_map.equals( copy ) ); for ( int i = 0; i < keys.length; i++ ) { assertEquals( values[i], copy.get( keys[i] ) ); } Map java_hashmap = new HashMap(); for ( int i = 0; i < keys.length; i++ ) { java_hashmap.put( keys[i], values[i] ); } THashMap java_hashmap_copy = new THashMap( java_hashmap ); assertTrue( "maps should be a copy of each other", ss_map.equals( java_hashmap_copy ) ); } public void testEquals() { String[] keys = {"Key1", "Key2", "Key3", "Key4", "Key5"}; String[] values = {"Val1", "Val2", "Val3", "Val4", "Val5"}; for ( int i = 0; i < keys.length; i++ ) { ss_map.put( keys[i], values[i] ); } assertFalse( "should not equal random Object", ss_map.equals( new Object() ) ); THashMap copy = new THashMap( ss_map ); assertTrue( "maps should be a copy of each other", ss_map.equals( copy ) ); // Change the Length. copy.put( "Key6", "Val6" ); assertFalse( "maps should no longer be a copy of each other", ss_map.equals( copy ) ); } public void testPut() throws Exception { assertEquals( "put succeeded", null, ss_map.put( "One", "two" ) ); assertEquals( "size did not reflect put", 1, ss_map.size() ); assertEquals( "put/get failed", "two", ss_map.get( "One" ) ); assertEquals( "second put failed", "two", ss_map.put( "One", "foo" ) ); } public void testPutIfAbsent() throws Exception { assertEquals( "putIfAbsent succeeded", null, ss_map.putIfAbsent( "One", "two" ) ); assertEquals( "size did not reflect putIfAbsent", 1, ss_map.size() ); assertEquals( "putIfAbsent/get failed", "two", ss_map.get( "One" ) ); assertEquals( "second putIfAbsent failed", "two", ss_map.putIfAbsent( "One", "foo" ) ); assertEquals( "size did not reflect putIfAbsent", 1, ss_map.size() ); assertEquals( "putIfAbsent/get failed", "two", ss_map.get( "One" ) ); assertEquals( "third putIfAbsent failed", null, ss_map.putIfAbsent( "Two", "bar" ) ); assertEquals( "size did not reflect putIfAbsent", 2, ss_map.size() ); assertEquals( "putIfAbsent/get failed", "bar", ss_map.get( "Two" ) ); } public void testClear() throws Exception { assertEquals( "initial size was not zero", 0, ss_map.size() ); assertEquals( "put succeeded", null, ss_map.put( "One", "two" ) ); assertEquals( "size did not reflect put", 1, ss_map.size() ); ss_map.clear(); assertEquals( "cleared size was not zero", 0, ss_map.size() ); } public void testContains() throws Exception { String key = "hi"; assertTrue( "should not contain key initially", !si_map.contains( key ) ); assertEquals( "put succeeded", null, si_map.put( key, Integer.valueOf( 1 ) ) ); assertTrue( "key not found after put", si_map.contains( key ) ); assertFalse( "non-existant key found", si_map.contains( "bye" ) ); } public void testContainsKey() throws Exception { String key = "hi"; assertTrue( "should not contain key initially", !si_map.containsKey( key ) ); assertEquals( "put succeeded", null, si_map.put( key, Integer.valueOf( 1 ) ) ); assertTrue( "key not found after put", si_map.containsKey( key ) ); assertFalse( "non-existant key found", si_map.containsKey( "bye" ) ); } public void testContainsValue() throws Exception { String key = "hi"; String value = "bye"; assertTrue( "should not contain key initially", !ss_map.containsValue( value ) ); assertEquals( "put succeeded", null, ss_map.put( key, value ) ); assertTrue( "key not found after put", ss_map.containsValue( value ) ); assertFalse( "non-existant key found", ss_map.containsValue( "whee" ) ); } @SuppressWarnings({"SuspiciousMethodCalls"}) public void testGet() throws Exception { String key = "hi", val = "one", val2 = "two"; ss_map.put( key, val ); assertEquals( "get did not return expected value", val, ss_map.get( key ) ); ss_map.put( key, val2 ); assertEquals( "get did not return expected value on second put", val2, ss_map.get( key ) ); // Invalid key should return null assertNull( ss_map.get( new Object() ) ); } public void testValues() throws Exception { String k1 = "1", k2 = "2", k3 = "3", k4 = "4", k5 = "5"; String v1 = "x", v2 = "y", v3 = "z"; ss_map.put( k1, v1 ); ss_map.put( k2, v1 ); ss_map.put( k3, v2 ); ss_map.put( k4, v3 ); ss_map.put( k5, v2 ); Collection vals = ss_map.values(); assertEquals( "size was not 5", 5, vals.size() ); vals.remove( "z" ); assertEquals( "size was not 4", 4, vals.size() ); vals.remove( "y" ); assertEquals( "size was not 3", 3, vals.size() ); vals.remove( "y" ); assertEquals( "size was not 2", 2, vals.size() ); assertEquals( "map did not diminish to 2 entries", 2, ss_map.size() ); } @SuppressWarnings({"WhileLoopReplaceableByForEach"}) public void testKeySet() throws Exception { String key1 = "hi", key2 = "bye", key3 = "whatever"; String val = "x"; ss_map.put( key1, val ); ss_map.put( key2, val ); ss_map.put( key3, val ); Set keys = ss_map.keySet(); assertTrue( "keyset did not match expected set", keys.containsAll( Arrays.asList( key1, key2, key3 ) ) ); assertEquals( 3, ss_map.size() ); int count = 0; Iterator it = keys.iterator(); while ( it.hasNext() ) { count++; it.next(); } assertEquals( ss_map.size(), count ); for ( Iterator i = keys.iterator(); i.hasNext(); ) { Object o = i.next(); if ( o.equals( key2 ) ) { i.remove(); } } assertTrue( "keyset did not match expected set", keys.containsAll( Arrays.asList( key1, key3 ) ) ); } public void testForEachKey() throws Exception { THashMap map = new THashMap(); String[] vals = {"one", "two", "three", "four"}; Integer[] keys = {new Integer( 1 ), new Integer( 2 ), new Integer( 3 ), new Integer( 4 ) }; for ( int i = 0; i < keys.length; i++ ) { map.put( keys[i], vals[i] ); } TObjectProcedure proc = new TObjectProcedure() { public boolean execute( Integer value ) { count += value; return true; } }; assertTrue( "should complete successfully", map.forEachKey( proc ) ); assertEquals( 10, count ); } public void testForEachKeyFalse() throws Exception { THashMap map = new THashMap(); String[] vals = {"one", "two", "three", "four"}; Integer[] keys = {new Integer( 1 ), new Integer( 2 ), new Integer( 3 ), new Integer( 4 ) }; for ( int i = 0; i < keys.length; i++ ) { map.put( keys[i], vals[i] ); } TObjectProcedure proc = new TObjectProcedure() { public boolean execute( Integer value ) { count++; return false; } }; assertFalse( "should Break after first iteration", map.forEachKey( proc ) ); assertEquals( 1, count ); } public void testForEachValue() throws Exception { String[] keys = {"one", "two", "three", "four"}; Integer[] vals = {new Integer( 1 ), new Integer( 2 ), new Integer( 3 ), new Integer( 4 ) }; for ( int i = 0; i < keys.length; i++ ) { si_map.put( keys[i], vals[i] ); } TObjectProcedure proc = new TObjectProcedure() { public boolean execute( Integer value ) { count += value; return true; } }; si_map.forEachValue( proc ); assertEquals( 10, count ); } public void testForEachValueFalse() throws Exception { String[] keys = {"one", "two", "three", "four"}; Integer[] vals = {new Integer( 1 ), new Integer( 2 ), new Integer( 3 ), new Integer( 4 ) }; for ( int i = 0; i < keys.length; i++ ) { si_map.put( keys[i], vals[i] ); } TObjectProcedure proc = new TObjectProcedure() { public boolean execute( Integer value ) { count++; return false; } }; assertFalse( "should Break after first iteration", si_map.forEachValue( proc ) ); assertEquals( 1, count ); } public void testForEachEntry() throws Exception { String[] keys = {"one", "two", "three", "four"}; Integer[] vals = {new Integer( 1 ), new Integer( 2 ), new Integer( 3 ), new Integer( 4 ) }; for ( int i = 0; i < keys.length; i++ ) { si_map.put( keys[i], vals[i] ); } TObjectObjectProcedure proc = new TObjectObjectProcedure() { public boolean execute( String key, Integer value ) { count += value; return true; } }; si_map.forEachEntry( proc ); assertEquals( 10, count ); } public void testForEachEntryInterrupt() throws Exception { String[] keys = {"one", "two", "three", "four"}; Integer[] vals = {new Integer( 1 ), new Integer( 2 ), new Integer( 3 ), new Integer( 4 ) }; for ( int i = 0; i < keys.length; i++ ) { si_map.put( keys[i], vals[i] ); } TObjectObjectProcedure proc = new TObjectObjectProcedure() { public boolean execute( String key, Integer value ) { count += value; return count < 6; } }; si_map.forEachEntry( proc ); assertTrue( count < 10 ); } public void testTransformValues() throws Exception { String[] keys = {"one", "two", "three", "four"}; Integer[] vals = {new Integer( 1 ), new Integer( 2 ), new Integer( 3 ), new Integer( 4 ) }; for ( int i = 0; i < keys.length; i++ ) { si_map.put( keys[i], vals[i] ); } TObjectFunction func = new TObjectFunction() { public Integer execute( Integer value ) { return new Integer( value << 1 ); } }; si_map.transformValues( func ); assertEquals( new Integer( 2 ), si_map.get( "one" ) ); assertEquals( new Integer( 4 ), si_map.get( "two" ) ); assertEquals( new Integer( 6 ), si_map.get( "three" ) ); assertEquals( new Integer( 8 ), si_map.get( "four" ) ); } @SuppressWarnings({"ForLoopReplaceableByForEach"}) public void testKeyIterator() throws Exception { String[] keys = {"one", "two", "three", "four"}; Integer[] vals = {new Integer( 1 ), new Integer( 2 ), new Integer( 3 ), new Integer( 4 ) }; for ( int i = 0; i < keys.length; i++ ) { si_map.put( keys[i], vals[i] ); } int count = 0; for ( Iterator i = si_map.keySet().iterator(); i.hasNext(); ) { i.next(); count++; } assertEquals( 4, count ); } public void testContainsNullValue() throws Exception { si_map.put( "a", null ); assertTrue( si_map.containsValue( null ) ); } public void testEntrySetContainsEntryWithNullValue() throws Exception { si_map.put( "0", null ); Map.Entry ee = si_map.entrySet().iterator().next(); assertTrue( si_map.entrySet().contains( ee ) ); } public void testValueSetRemoveNullValue() throws Exception { si_map.put( "0", null ); assertTrue( si_map.values().remove( null ) ); } public void testSizeAfterEntrySetRemove() throws Exception { si_map.put( "0", null ); Map.Entry ee = si_map.entrySet().iterator().next(); assertTrue( ee.getKey().equals( "0" ) ); assertNull( ee.getValue() ); assertTrue( "remove on entrySet() returned false", si_map.entrySet().remove( ee ) ); assertEquals( 0, si_map.size() ); } @SuppressWarnings({"SuspiciousMethodCalls"}) public void testEntrySetRemoveSameKeyDifferentValues() throws Exception { ss_map.put( "0", "abc" ); si_map.put( "0", Integer.valueOf( 123 ) ); Map.Entry ee = ss_map.entrySet().iterator().next(); assertEquals( 1, si_map.size() ); assertTrue( !si_map.entrySet().contains( ee ) ); assertTrue( !si_map.entrySet().remove( ee ) ); } public void testSizeAfterMultipleReplacingPuts() throws Exception { ss_map.put( "key", "a" ); assertEquals( 1, ss_map.size() ); ss_map.put( "key", "b" ); assertEquals( 1, ss_map.size() ); } @SuppressWarnings({"unchecked"}) public void testSerializable() throws Exception { // Use a non-standard load factor to more fully test serialization THashMap map = new THashMap( 100, 0.75f ); map.put( "a", "b" ); map.put( "b", "c" ); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream( baos ); oos.writeObject( map ); ByteArrayInputStream bais = new ByteArrayInputStream( baos.toByteArray() ); ObjectInputStream ois = new ObjectInputStream( bais ); THashMap deserialized = (THashMap) ois.readObject(); assertEquals( map, deserialized ); } public void testRetainEntries() throws Exception { ss_map.put( "a", "b" ); ss_map.put( "c", "b" ); ss_map.put( "d", "b" ); ss_map.retainEntries( new TObjectObjectProcedure() { public boolean execute( String key, String val ) { return key.equals( "c" ); } } ); assertEquals( 1, ss_map.size() ); assertTrue( ss_map.containsKey( "c" ) ); assertEquals( "b", ss_map.get( "c" ) ); } public void testPutAll() throws Exception { HashMap map = new HashMap(); map.put( "one", "two" ); map.put( "two", "four" ); map.put( "three", "six" ); ss_map.putAll( map ); } @SuppressWarnings({"RedundantStringConstructorCall"}) public void testHashCode() throws Exception { THashMap ss_map2 = new THashMap(); ss_map.put( new String( "foo" ), new String( "bar" ) ); ss_map2.put( new String( "foo" ), new String( "bar" ) ); assertEquals( ss_map.hashCode(), ss_map2.hashCode() ); assertEquals( ss_map, ss_map2 ); ss_map2.put( new String( "cruft" ), new String( "bar" ) ); assertTrue( ss_map.hashCode() != ss_map2.hashCode() ); assertTrue( !ss_map.equals( ss_map2 ) ); } @SuppressWarnings({"MismatchedQueryAndUpdateOfCollection"}) public void testBadlyWrittenKey() { THashMap map = new THashMap(); boolean didThrow = false; try { for ( int i = 0; i < 1000; i++ ) { // enough to trigger a rehash map.put( new THashSetTest.Crap(), new Integer( i ) ); } } catch ( IllegalArgumentException e ) { didThrow = true; } assertTrue( "expected THashMap to throw an IllegalArgumentException", didThrow ); } public void testKeySetEqualsEquivalentSet() { Set set = new HashSet(); set.add( "foo" ); set.add( "doh" ); set.add( "hal" ); THashMap tv1 = new THashMap(); tv1.put( "doh", "blah" ); tv1.put( "foo", "blah" ); tv1.put( "hal", "notblah" ); assertTrue( tv1.keySet().equals( set ) ); } @SuppressWarnings({"unchecked"}) public void testNullValue() { ss_map.put( "foo", null ); ss_map.put( "bar", null ); ss_map.put( "baz", null ); assertEquals( Arrays.asList( null, null, null ), new ArrayList( ss_map.values() ) ); } public void testNullValueSize() { ss_map.put( "narf", null ); ss_map.put( "narf", null ); assertEquals( 1, ss_map.size() ); } public void testNullKey() { ss_map.put( null, "null" ); assertEquals( null, ss_map.keySet().iterator().next() ); ss_map.put( "one", "1" ); ss_map.put( "two", "2" ); ss_map.put( "three", "3" ); assertEquals( "null", ss_map.get( null ) ); assertEquals( "1", ss_map.get( "one" ) ); assertEquals( "2", ss_map.get( "two" ) ); assertEquals( "3", ss_map.get( "three" ) ); String old_value = ss_map.put( null, "null_new" ); assertEquals( "null", old_value ); assertEquals( "null_new", ss_map.get( null ) ); } public void testRetainEntrySet() { ss_map.put( "one", "frodo" ); ss_map.put( "two", "bilbo" ); ss_map.put( "three", "samwise" ); Map subset = new HashMap(); subset.put( "two", "bilbo" ); assertTrue( ss_map.entrySet().retainAll( subset.entrySet() ) ); assertEquals( subset, ss_map ); } @SuppressWarnings({"MismatchedQueryAndUpdateOfCollection"}) public void testMapEntrySetHashCode() { ss_map.put( "one", "foo" ); Map m2 = new THashMap(); m2.put( "one", "foo" ); Object o1 = ss_map.entrySet().iterator().next(); Object o2 = ss_map.entrySet().iterator().next(); assertTrue( o1 != o2 ); assertTrue( o1.equals( o2 ) ); assertEquals( o1.hashCode(), o2.hashCode() ); } public void testEqualsAndHashCode() { THashMap map1 = new THashMap(); map1.put( "Key1", null ); THashMap map2 = new THashMap(); map2.put( "Key2", "Value2" ); assertFalse( "map1.equals( map2 )", map1.equals( map2 ) ); assertFalse( "map2.equals( map1 )", map2.equals( map1 ) ); THashMap clone_map1 = new THashMap( map1 ); THashMap clone_map2 = new THashMap( map2 ); assertEquals( map1, clone_map1 ); assertEquals( map1.hashCode(), clone_map1.hashCode() ); assertEquals( map2, clone_map2 ); assertEquals( map2.hashCode(), clone_map2.hashCode() ); } /** * Test case for bug #1428614. * http://sourceforge.net/tracker/index.php?func=detail&aid=1428614&group_id=39235&atid=424682 */ public void testRemoveValue() { ss_map.put( "one", "a" ); ss_map.put( "two", "a" ); ss_map.put( "three", "b" ); assertEquals( 3, ss_map.size() ); ss_map.values().remove( "a" ); assertEquals( 2, ss_map.size() ); assertFalse( ss_map.values().remove( "non-existant" ) ); } /** * This test case arose out of a problem that was ultimately caused by the * implementation if THashMap.removeAt(int) being incorrect (the super implementation * was being called before the local implementation which caused problems when * auto-compaction occurred). So, it's a little wiggy, but since the case was useful * once, I figure I'll leave it in. - RDE */ @SuppressWarnings({"ForLoopReplaceableByForEach", "MismatchedQueryAndUpdateOfCollection"}) public void testProblematicRemove() { int[] to_add = new int[]{ 9707851, 1432929, 7941420, 8698105, 9178562, 14368620, 2165498, 5759024, 4160722, 1835074, 5570057, 15866937, 1774305, 7645103, 11340758, 14962053, 10326974, 5153366, 8644308, 10981652, 2484113, 8790215, 13765491, 15579334, 16644662, 3538325, 10183070, 2491991, 6963721, 1406388, 14845099, 7614579, 1630785, 11417789, 988981, 12372702, 11197485, 6115155, 185310, 10733210, 4444363, 4256211, 12877269, 2178642, 8551718, 15095256, 922983, 10434400, 15511986, 8792944, 9301853, 6147907, 13778707, 2822511, 8760514, 1112301, 4624291, 8406178, 1708017, 834479, 16113199, 13501060, 477791, 10737091, 2568325, 14839924, 4523777, 13566852, 15722007, 15406704, 932352, 127549, 13010531, 10540591, 5100961, 288048, 9396085, 12844726, 8887992, 12932686, 10827776, 16751176, 15337379, 10192984, 1341540, 15470105, 9555179, 2394843, 1595902, 12345969, 14884594, 313940, 8348091, 15293845, 16706146, 13500767, 12331344, 3959435, 7796580, 7077998, 9458485, 4648605, 14396291, 14246507, 13404097, 14988605, 3600161, 9280290, 12842832, 10606027, 14355582, 1136752, 12921165, 1749219, 5457859, 9197696, 421256, 73503, 10633537, 6952660, 58264, 6164651, 9993341, 1386282, 12470635, 12982240, 4816459, 159250, 8949093, 16447937, 2290043, 1828537, 13148199, 9084516, 10802630, 13549340, 6609445, 2995162, 8040282, 9333002, 9580969, 16406600, 12194236, 14835440, 13041360, 8604473, 12565810, 1988729, 4355359, 1535580, 5149176, 5324752, 3438993, 1660570, 8691895, 5474195, 15334260, 8105437, 13879037, 11351030, 3039475, 14625682, 10849417, 11379670, 14640675, 11176427, 4513965, 16428465, 10578701, 8072595, 15538803, 6526027, 10283251, 8507206, 5188636, 14223982, 3920972, 15659969, 12922874, 13689914, 3658005, 8379437, 5247277, 9938991, 10659712, 10678905, 14485926, 10786998, 2488171, 9881794, 5651833, 14538812, 10444169, 11922157, 5403811, 6785775, 13794224, 11958753, 16494451, 12313218, 1297763, 1126021, 345418, 528188, 2114627, 6400133, 8307281, 490653, 8793363, 16336633, 10653219, 2214875, 13551003, 1001246, 397033, 12381376, 5991449, 1443593, 2622811, 7847125, 944151, 13889218, 14686341, 6939782, 1712728, 12902341, 4138467, 13656813, 973555, 4767079, 9100632, 13222220, 11641873, 9082629, 12639233, 11258141, 2146301, 1867442, 12719413, 16679909, 8734589, 1606713, 9501535, 6761395, 6693929, 13647363, 9914313, 15335895, 2021653, 4068909, 2228794, 12603329, 11807792, 12665538, 395494, 3299447, 5119086, 2917420, 10055436, 4831656, 3927888, 14447609, 4329094, 13077467, 11461522, 14594477, 6481991, 8367571, 7156844, 9223013, 6482120, 10542896, 10286402, 11125093, 14144872, 16495825, 1844776, 860068, 9980169, 14877755, 2804551, 8894974, 12849678, 8215338, 15490728, 3843485, 5184218, 7071904, 7703600, 4633458, 11481528, 15295069, 3736219, 14297843, 3787634, 6015173, 14290065, 7290758, 11764335, 3688927, 7991532, 12075598, 606202, 4674522, 13772937, 6515326, 14974617, 3385263, 4587760, 15178512, 7689244, 15015527, 3087738, 3683764, 5107535, 10120404, 6225460, 8588999, 4151219, 9885848, 6691152, 518908, 13918089, 13393004, 13093729, 16338349, 5945377, 15632500, 4230314, 13832167, 12139768, 5361165, 11457892, 3916190, 2387780, 325816, 6621694, 7540927, 5271271, 10565439, 3281837, 11138623, 6663214, 737100, 6864802, 16592415, 14615312, 4342441, 2525512, 16706191, 14258395, 11878990, 1320531, 14696398, 8201398, 16077183, 12155328, 15225360, 6533378, 16390602, 11750387, 4144864, 3744598, 4136761, 1775074, 3787875, 10061327, 3165792, 6921717, 84292, 7420530, 11805441, 6704350, 4234280, 13377633, 6417611, 81563, 11879309, 6692731, 10285066, 5452490, 2848306, 6094584, 6772150, 2899899, 805004, 7273360, 4566720, 13878010, 10871921, 3724097, 11896809, 15586671, 5744620, 13731591, 16250661, 8560290, 8169917, 7059338, 14615241, 3149669, 4383295, 1292178, 7919990, 846550, 896930, 8769114, 11437924, 3854132, 16345157, 2929809, 186157, 8183120, 10860321, 10092509, 7157818, 8817522, 2944051, 4664124, 6791689, 12517547, 12905829, 12435281, 5992485, 2074096, 13062653, 14148480, 10024647, 7455154, 6534752, 5933059, 9930860, 8221561, 2639915, 10098755, 11468155, 8638604, 15770467, 7790866, 11694410, 2868248, 5710862, 15709, 12374346, 5274287, 10913198, 9607083, 2330533, 11262155, 2500209, 10878393, 11834918, 15572289, 15669880, 11713730, 8818293, 15907500, 12427744, 13540318, 5978200, 13640927, 2411696, 16408949, 1331989, 5941655, 3414928, 16619879, 6441500, 15706705, 9881210, 12620326, 12259629, 6605901, 10543825, 9125515, 12001189, 8309409, 2696396, 3070853, 5120614, 11830622, 10490623, 4149060, 7141756, 7297762, 12039919, 4930206, 16095035, 10203610, 12162006, 10028034, 14040149, 1250372, 9943013, 11150309, 1752285, 6641241, 532227, 2891993, 2146459, 4523080, 1843838, 1876388, 12071882, 5253689, 266407, 14770216, 7346541, 9785383, 12662763, 4087061, 5312086, 8667965, 5935475, 214509, 14935237, 12603345, 12069351, 13056011, 3177187, 13886924, 9688141, 5714168, 5238287, 9839924, 6586077, 12908278, 3257673, 7665358, 16208962, 12373914, 14796394, 11098653, 5975276, 14839805, 2522300, 13055068, 4113411, 11984808, 1418893, 6924381, 11314606, 11633137, 13235995, 8277143, 14057346, 5064134, 2097065, 13223254, 12242045, 13059400, 9799866, 4430809, 11327935, 769464, 13938921, 11178479, 5438437, 1550013, 12839250, 727385, 11354068, 3772220, 15394227, 9336140, 11988768, 860366, 14994301, 15440057, 7845075, 46465, 9200550, 14833083, 6980643, 604527, 10080643, 9045195, 4244693, 3844932, 12717539, 1960282, 12786813, 8615113, 6833198, 5522541, 5791657, 15755268, 3994917, 158446, 12203633, 5002730, 10253904, 1809471, 11479213, 9928035, 11072909, 9512807, 11660261, 16127120, 12596061, 7086362, 15820414, 8387982, 14653636, 10912742, 1941253, 11740079, 15457795, 3976572, 10595620, 7217556, 6197451, 7618490, 258825, 4780842, 5534349, 2921202, 6513404, 16229803, 10332843, 3138363, 15681804, 10802604, 13113540, 13757900, 5443555, 3681765, 5063855, 14185653, 14039650, 9644178, 5024611, 8918836, 11231866, 13523137, 2425209, 8636320, 10944802, 3891863, 12961644, 10984042, 9100512, 11218774, 11581954, 8646320, 11234763, 11887145, 4171898, 5109569, 10742219, 4859349, 16381539, 10419813, 5223261, 8955000, 15061357, 1607571, 7136846, 8670269, 11099382, 1451676, 4261185, 12586581, 15531576, 2504976, 7105767, 6413040, 7144290, 16334106, 1741877, 16270583, 7852246, 3119103, 10743199, 4558377, 7878745, 12289371, 3163084, 11735282, 1935864, 5055074, 820851, 5185654, 14442671, 5212885, 2344949, 1892708, 1153520, 9541794, 12306031, 14732248, 6743381, 5920025, 8969603, 8847687, 6622806, 9462942, 12451035, 2336870, 327996, 9713350, 9963027, 11991923, 3562944, 4520396, 7065629, 2905597, 12675100, 10094378, 5011336, 3908274, 3572588, 15618069, 13341879, 9470980, 13327842, 8432408, 6344466, 12241360, 1543979, 12081229, 11363884, 983612, 6025413, 1848571, 14318469, 14906334, 13381442, 3327004, 15286722, 14443922, 9462145, 15828870, 16292084, 128023, 4199307, 12797648, 6169450, 6767468, 8100201, 9756312, 10612295, 2273164, 3350998, 15889011, 3661060, 9395406, 1435793, 5752767, 16441805, 16677778, 6475274, 12909030, 15902971, 3415473, 9004053, 645884, 515610, 8824322, 16574526, 15956463, 13265827, 6333169, 6924814, 1812983, 3392856, 14761092, 4985619, 7893816, 13931135, 14548854, 11444226, 9118923, 1875105, 7285192, 2101733, 7801836, 11517693, 2349183, 5939167, 11937456, 10886500, 13866155, 12947589, 9640186, 5047153, 1901666, 715551, 13790692, 2933460, 11212664, 9563015, 16642428, 16334427, 7140601, 4655671, 15711153, 750565, 15067249, 16737043, 12684416, 15673315, 2341376, 8935324, 3134061, 10483409, 337177, 13018877, 16599994, 7782302, 1977121, 10593779, 9842381, 14330646, 1456639, 3774065, 12844377, 3016177, 8933870, 12263851, 10455534, 1612109, 16302350, 4895080, 12932155, 1905228, 10253063, 4458040, 16024500, 15902756, 16584305, 12528008, 4171461, 14536742, 9219403, 12927168, 1979395, 15257546, 10619265, 1967594, 1467515, 2028519, 2032612, 3707709, 4887462, 2337860, 183801, 2152077, 15066473, 3694942, 8424967, 15508266, 13386596, 6059869, 10531128, 13828874, 7119662, 5064756, 12552069, 5922533, 802911, 5645620, 10781530, 11246590, 9323418, 16275234, 2144845, 10962831, 4925357, 1704524, 9227431, 13641289, 8489002, 1225340, 8659144, 8671408, 13461400, 4992933, 13370774, 8568931, 2412794, 1312411, 12429994, 1025208, 478829, 11399895, 2242158, 2332498, 10717459, 8151843, 5288043, 7235700, 9162569, 14017735, 10412273, 12712138, 11844638, 11163643, 7756823, 9956164, 14078510, 8442139, 2116890, 10881649, 16223710, 8592664, 15408035, 6522496, 1261635, 14685232, 5071601, 10144049, 967751, 7873356, 5595700, 10647000, 15126220, 1237821, 321796, 6173902, 14476409, 1830511, 12766190, 14322080, 8483740, 13438254, 1854079, 6215655, 11575352, 15129118, 16393883, 16560142, 9079559, 11379168, 6198702, 11864074, 2282933, 16547051, 7156233, 15740343, 4809601, 2344447, 10219155, 4977972, 13592880, 184650, 16420038, 3165940, 9418081, 13446140, 179241, 9394692, 6213074, 1752099, 3516715, 16081239, 13222615, 1499877, 9066661, 12702088, 10706447, 7629231, 13016955, 1069166, 1089471, 6809842, 15634321, 1288782, 1183469, 9576844, 14191973, 2814257, 4260748, 5239952, 4277681, 4629271, 8220928, 8766876, 7388663, 13090704, 15838538, 11015909, 7814987, 14448125, 13000849, 15596437, 2104764, 8398024, 15653431, 3695833, 6613072, 13626967, 2665818, 9249819, 4040305, 8029033, 4822667, 3844052, 14708928, 690088 }; THashMap map = new THashMap(); int[] to_remove = new int[]{ 9707851, 7941420, 9178562, 2165498, 4160722, 5570057, 1774305, 11340758, 10326974, 8644308 }; for ( int i = 0; i < to_add.length; i++ ) { Integer obj = new Integer( to_add[i] ); map.put( obj, obj ); } for ( int i = 0; i < to_remove.length; i++ ) { Integer obj = new Integer( to_remove[i] ); map.remove( obj ); } } public void testIterable() { Map m = new THashMap(); m.put( "One", Integer.valueOf( 1 ) ); m.put( "Two", Integer.valueOf( 2 ) ); for ( String s : m.keySet() ) { assertTrue( s.equals( "One" ) || s.equals( "Two" ) ); } for ( Integer i : m.values() ) { assertTrue( i.intValue() == 1 || i.intValue() == 2 ); } } public void testKeysFunctions() { int element_count = 10; String[] keys = new String[element_count]; String[] vals = new String[element_count]; for ( int i = 0; i < element_count; i++ ) { keys[i] = "Key" + i; vals[i] = "Vals" + i; ss_map.put( keys[i], vals[i] ); } assertEquals( element_count, ss_map.size() ); Collection keys_set = ss_map.keySet(); assertTrue( "should contain " + keys[5] + ", " + ss_map, keys_set.contains( keys[5] ) ); assertFalse( "invalid remove succeeded " + keys_set, keys_set.remove( "non-existant" ) ); assertTrue( "remove failed: " + keys_set, keys_set.remove( keys[5] ) ); assertFalse( "key set contains removed item", keys_set.contains( keys[5] ) ); assertFalse( "map contains removed item" + ss_map, ss_map.contains( keys[5] ) ); assertFalse( "map contains removed item" + ss_map, ss_map.containsKey( keys[5] ) ); assertFalse( "cannot remove item not in set", keys_set.remove( "non-existant" ) ); } public void testValuesFunctions() { int element_count = 10; String[] vals = new String[element_count]; for ( int i = 0; i < element_count; i++ ) { vals[i] = "Val" + i; ss_map.put( "Key" + i, vals[i] ); } assertEquals( element_count, ss_map.size() ); Collection values_set = ss_map.values(); assertTrue( "should contain " + vals[5] + ", " + ss_map, values_set.contains( vals[5] ) ); Set set = new HashSet(); for ( int i = 0; i < element_count; i++ ) { vals[i] = "Val" + i; set.add( vals[i] ); } assertTrue( "should contain all: " + values_set + ", " + set, values_set.containsAll( set ) ); set.add( "cause failure" ); assertFalse( "shouldn't contain all: " + values_set, values_set.containsAll( set ) ); values_set.clear(); assertEquals( "values set size should be 0", 0, values_set.size() ); assertEquals( "map size should be 0", 0, ss_map.size() ); assertTrue( values_set.isEmpty() ); try { values_set.add( "fail" ); fail( "Expected UnsupportedOperationException" ); } catch ( UnsupportedOperationException ex ) { // Expected } try { values_set.addAll( Arrays.asList( "fail" ) ); fail( "Expected UnsupportedOperationException" ); } catch ( UnsupportedOperationException ex ) { // Expected } } @SuppressWarnings({"ToArrayCallWithZeroLengthArrayArgument"}) public void testValuesToArray() { int element_count = 10; String[] vals = new String[element_count]; for ( int i = 0; i < element_count; i++ ) { vals[i] = "Val" + i; ss_map.put( "Key" + i, vals[i] ); } Collection values_set = ss_map.values(); String[] toarray = values_set.toArray( new String[0] ); Arrays.sort( toarray ); assertEquals( Arrays.asList( vals ), Arrays.asList( toarray ) ); toarray = values_set.toArray( new String[element_count] ); Arrays.sort( toarray ); assertEquals( Arrays.asList( vals ), Arrays.asList( toarray ) ); toarray = values_set.toArray( new String[element_count + 1] ); assertEquals( null, toarray[element_count] ); Arrays.sort( toarray, 0, element_count ); for ( int i = 0; i < element_count; i++ ) { assertEquals( vals[i], toarray[i] ); } } public void testIteratorFunctions() throws Exception { int element_count = 10; String[] keys = new String[element_count]; String[] vals = new String[element_count]; for ( int i = 0; i < element_count; i++ ) { keys[i] = "Key" + i; vals[i] = "Val" + i; ss_map.put( keys[i], vals[i] ); } Iterator> iter = ss_map.entrySet().iterator(); while ( iter.hasNext() ) { Map.Entry ee = iter.next(); assertTrue( Arrays.asList( keys ).contains( ee.getKey() ) ); assertTrue( Arrays.asList( vals ).contains( ee.getValue() ) ); count++; } iter = ss_map.entrySet().iterator(); assertTrue( iter.hasNext() ); Map.Entry ee = iter.next(); assertTrue( "remove on entrySet() returned false", ss_map.entrySet().remove( ee ) ); assertEquals( element_count - 1, ss_map.size() ); } @SuppressWarnings({"unchecked"}) public void testEntrySetFunctions() { int element_count = 10; String[] keys = new String[element_count]; String[] vals = new String[element_count]; for ( int i = 0; i < element_count; i++ ) { keys[i] = "Key" + i; vals[i] = "Val" + i; ss_map.put( keys[i], vals[i] ); } Iterator> iter = ss_map.entrySet().iterator(); assertTrue( iter.hasNext() ); Map.Entry ee = iter.next(); assertNotNull( ee.getKey() ); assertNotNull( ee.getValue() ); assertNotNull( ee.getValue() ); assertNotNull( ee.getValue() ); String new_value = "New Value"; String old_value = ee.getValue(); assertEquals( old_value, ee.setValue( new_value ) ); assertFalse( old_value.equals( ee.getValue() ) ); assertFalse( ss_map.values().contains( old_value ) ); assertTrue( ss_map.values().contains( new_value ) ); assertTrue( ss_map.containsValue( new_value ) ); assertFalse( "equal vs. random object incorrect", ee.equals( new Object() ) ); } // public void testGetOverRemovedObjectBug() { // Map m = new THashMap( // new TObjectHashingStrategy() { // public int computeHashCode(BadHashInteger object) { // return object.hashCode(); // } // // public boolean equals(BadHashInteger o1, BadHashInteger o2) { // return o1.value == o2.value; // } // } ); // // // m.put( new BadHashInteger( 1 ), "one" ); // m.put( new BadHashInteger( 2 ), "two" ); // // m.remove( new BadHashInteger( 1 ) ); // // assertEquals( 1, m.size() ); // // // Blow up here? // assertEquals( "two", m.get( new BadHashInteger( 2 ) ) ); // } // // public void testReaddBug() { // Map m = new THashMap( // new TObjectHashingStrategy() { // public int computeHashCode(Integer object) { // return object.intValue(); // } // // public boolean equals(Integer o1, Integer o2) { // return o1.intValue() == o2.intValue(); // } // } ); // // m.put( new Integer( 1 ), "one" ); // assertEquals(1, m.size()); // // m.remove( new Integer( 1 ) ); // assertEquals(0, m.size()); // // m.put( new Integer( 1 ), "one" ); // assertEquals(1, m.size()); // } public void testToString() { ss_map.put( "One", "1" ); ss_map.put( "Two", "2" ); String to_string = ss_map.toString(); assertTrue( to_string, to_string.equals( "{One=1, Two=2}" ) || to_string.equals( "{Two=2, One=1}" ) ); } public void testEntrySetToString() { Map map = new THashMap(); map.put( "One", "1" ); map.put( "Two", "2" ); String to_string = map.entrySet().toString(); assertTrue( to_string, to_string.equals( "{One=1, Two=2}" ) || to_string.equals( "{Two=2, One=1}" ) ); } public void testKeySetToString() { Map map = new THashMap(); map.put( "One", "1" ); map.put( "Two", "2" ); String to_string = map.keySet().toString(); assertTrue( to_string, to_string.equals( "{One, Two}" ) || to_string.equals( "{Two, One}" ) ); } public void testValuesToString() { Map map = new THashMap(); map.put( "One", "1" ); map.put( "Two", "2" ); String to_string = map.values().toString(); assertTrue( to_string, to_string.equals( "{1, 2}" ) || to_string.equals( "{2, 1}" ) ); } /** * Make sure that REMOVED entries are pruned when doing compaction. */ public void testRemovedSlotPruning() { THashMap map = new THashMap(); map.put( "ONE", "1" ); map.put( "TWO", "2" ); map.put( "THREE", "3" ); // Compact to make sure we're at the internal capacity we want to ultimate be at map.compact(); // Make sure there are no REMOVED slots initially for( Object set_entry : map._set ) { if ( set_entry == TObjectHash.REMOVED ) fail( "Found a REMOVED entry" ); } map.remove( "TWO" ); map.put( "FOUR", "4" ); // Make sure there is 1 REMOVED slot int count = 0; for( Object set_entry : map._set ) { if ( set_entry == TObjectHash.REMOVED ) count++; } assertEquals( 1, count ); map.compact(); // Make sure there are no REMOVED slots for( Object set_entry : map._set ) { if ( set_entry == TObjectHash.REMOVED ) { fail( "Found a REMOVED entry after compaction" ); } } } /** * Make sure that REMOVED entries are pruned when doing compaction. */ public void testFreeSlotCounterConsistency() { THashMap map = new THashMap(); HashTestKit.checkFreeSlotCount( map, map._set, TObjectHash.FREE ); map.put( "ONE", "1" ); map.put( "TWO", "2" ); map.put( "THREE", "3" ); HashTestKit.checkFreeSlotCount( map, map._set, TObjectHash.FREE ); // Compact to make sure we're at the internal capacity we want to ultimate be at map.compact(); HashTestKit.checkFreeSlotCount( map, map._set, TObjectHash.FREE ); map.remove( "TWO" ); map.put( "FOUR", "4" ); HashTestKit.checkFreeSlotCount( map, map._set, TObjectHash.FREE ); map.compact(); HashTestKit.checkFreeSlotCount( map, map._set, TObjectHash.FREE ); } // Test for issue 3159432 public void testEntrySetRemove() { THashMap map = new THashMap(); map.put( "ONE", "1" ); map.put( "TWO", "2" ); map.put( "THREE", "3" ); Set> set = map.entrySet(); set.remove( null ); //noinspection SuspiciousMethodCalls set.remove( "Blargh" ); } public void testNullKeyHandling() { THashMap map = new THashMap(); map.put( null, "My null key" ); for( int i = 0; i < 100; i++ ) { map.put( String.valueOf( i ), String.valueOf( i ) ); } assertEquals( "My null key", map.get( null ) ); map.put( null, "My new null key" ); map.compact(); for( int i = 100; i < 200; i++ ) { map.put( String.valueOf( i ), String.valueOf( i ) ); } assertEquals( "My new null key", map.get( null ) ); for( int i = 0; i < 200; i++ ) { assertEquals( String.valueOf( i ), map.get( String.valueOf( i ) ) ); } } } // THashMapTests trove-3.0.3/test/gnu/trove/TDecoratorsTest.java0000644000175000017500000001024611763017634020500 0ustar ericherich// //////////////////////////////////////////////////////////////////////////// // Copyright (c) 2009, Rob Eden All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // //////////////////////////////////////////////////////////////////////////// package gnu.trove; import gnu.trove.list.TIntList; import gnu.trove.list.array.TIntArrayList; import junit.framework.TestCase; import java.util.Iterator; import java.util.List; /** * */ public class TDecoratorsTest extends TestCase { public void testIntListDecorator() { TIntList list = new TIntArrayList(); list.add( 2 ); list.add( 3 ); list.add( 4 ); list.add( 5 ); list.add( 6 ); List wrapped_list = TDecorators.wrap( list ); assertEquals( 5, wrapped_list.size() ); assertEquals( Integer.valueOf( 2 ), wrapped_list.get( 0 ) ); assertEquals( Integer.valueOf( 3 ), wrapped_list.get( 1 ) ); assertEquals( Integer.valueOf( 4 ), wrapped_list.get( 2 ) ); assertEquals( Integer.valueOf( 5 ), wrapped_list.get( 3 ) ); assertEquals( Integer.valueOf( 6 ), wrapped_list.get( 4 ) ); list.removeAt( 1 ); assertEquals( 4, list.size() ); assertEquals( Integer.valueOf( 2 ), wrapped_list.get( 0 ) ); assertEquals( Integer.valueOf( 4 ), wrapped_list.get( 1 ) ); assertEquals( Integer.valueOf( 5 ), wrapped_list.get( 2 ) ); assertEquals( Integer.valueOf( 6 ), wrapped_list.get( 3 ) ); wrapped_list.remove( 1 ); assertEquals( 3, list.size() ); assertEquals( 2, list.get( 0 ) ); assertEquals( 5, list.get( 1 ) ); assertEquals( 6, list.get( 2 ) ); list.clear(); assertTrue( wrapped_list.isEmpty() ); wrapped_list.add( Integer.valueOf( 7 ) ); assertEquals( 1, list.size() ); assertEquals( 7, list.get( 0 ) ); wrapped_list.clear(); assertTrue( list.isEmpty() ); list.add( 8 ); list.add( 9 ); list.add( 10 ); Iterator wrapper_list_it = wrapped_list.iterator(); assertTrue( wrapper_list_it.hasNext() ); assertEquals( Integer.valueOf( 8 ), wrapper_list_it.next() ); assertTrue( wrapper_list_it.hasNext() ); assertEquals( Integer.valueOf( 9 ), wrapper_list_it.next() ); assertTrue( wrapper_list_it.hasNext() ); assertEquals( Integer.valueOf( 10 ), wrapper_list_it.next() ); assertFalse( wrapper_list_it.hasNext() ); wrapper_list_it = wrapped_list.iterator(); assertTrue( wrapper_list_it.hasNext() ); assertEquals( Integer.valueOf( 8 ), wrapper_list_it.next() ); wrapper_list_it.remove(); assertTrue( wrapper_list_it.hasNext() ); assertEquals( Integer.valueOf( 9 ), wrapper_list_it.next() ); assertTrue( wrapper_list_it.hasNext() ); assertEquals( Integer.valueOf( 10 ), wrapper_list_it.next() ); assertFalse( wrapper_list_it.hasNext() ); assertEquals( 2, list.size() ); assertEquals( 9, list.get( 0 ) ); assertEquals( 10, list.get( 1 ) ); } public void testIntListDecoratorSubList() { TIntList list = new TIntArrayList(); list.add( 2 ); list.add( 3 ); list.add( 4 ); list.add( 5 ); list.add( 6 ); List wrapped_list = TDecorators.wrap( list ); List sublist = wrapped_list.subList( 1, 4 ); assertEquals( 3, sublist.size() ); assertEquals( Integer.valueOf( 3 ), sublist.get( 0 ) ); assertEquals( Integer.valueOf( 4 ), sublist.get( 1 ) ); assertEquals( Integer.valueOf( 5 ), sublist.get( 2 ) ); sublist.clear(); assertEquals( 2, list.size() ); assertEquals( 2, list.get( 0 ) ); assertEquals( 6, list.get( 1 ) ); } } trove-3.0.3/test/gnu/trove/decorator/0000755000175000017500000000000012000515265016507 5ustar ericherichtrove-3.0.3/test/gnu/trove/decorator/TObjectPrimitiveMapDecoratorTest.java0000644000175000017500000011234711763017634025762 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2002, Eric D. Friedman All Rights Reserved. // Copyright (c) 2009, Robert D. Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.decorator; import junit.framework.TestCase; import gnu.trove.map.TObjectIntMap; import gnu.trove.map.hash.TObjectIntHashMap; import gnu.trove.TDecorators; import java.util.*; import java.io.ByteArrayOutputStream; import java.io.ObjectOutputStream; import java.io.ByteArrayInputStream; import java.io.ObjectInputStream; /** * Test the Object key/primitive value map decorators * * @author Eric D. Friedman * @author Robert D. Eden * @author Jeff Randall */ public class TObjectPrimitiveMapDecoratorTest extends TestCase { public TObjectPrimitiveMapDecoratorTest( String name ) { super( name ); } public void testConstructors() { int element_count = 20; String[] keys = new String[element_count]; int[] vals = new int[element_count]; TObjectIntMap raw_map = new TObjectIntHashMap(); for ( int i = 0; i < element_count; i++ ) { keys[i] = Integer.toString( i + 1 ); vals[i] = i + 1; raw_map.put( keys[i], vals[i] ); } Map map = TDecorators.wrap( raw_map ); TObjectIntHashMap raw_capacity = new TObjectIntHashMap( 20 ); for ( int i = 0; i < element_count; i++ ) { raw_capacity.put( keys[i], vals[i] ); } Map capacity = TDecorators.wrap( raw_capacity ); assertEquals( raw_map, raw_capacity ); assertEquals( map, capacity ); TObjectIntHashMap raw_cap_and_factor = new TObjectIntHashMap( 20, 0.75f ); for ( int i = 0; i < element_count; i++ ) { raw_cap_and_factor.put( keys[i], vals[i] ); } Map cap_and_factor = TDecorators.wrap( raw_cap_and_factor ); assertEquals( raw_map, raw_cap_and_factor ); assertEquals( map, cap_and_factor ); TObjectIntHashMap raw_fully_specified = new TObjectIntHashMap( 20, 0.75f, Integer.MIN_VALUE ); Map fully_specified = TDecorators.wrap( raw_fully_specified ); for ( int i = 0; i < element_count; i++ ) { fully_specified.put( keys[i], vals[i] ); } assertEquals( map, fully_specified ); TObjectIntHashMap raw_copy = new TObjectIntHashMap( raw_map ); Map copy = TDecorators.wrap( raw_copy ); assertEquals( raw_map, raw_copy ); assertEquals( map, copy ); } public void testGetMap() { int element_count = 20; String[] keys = new String[element_count]; int[] vals = new int[element_count]; TObjectIntMap raw_map = new TObjectIntHashMap(); for ( int i = 0; i < element_count; i++ ) { keys[i] = Integer.toString( i + 1 ); vals[i] = i + 1; raw_map.put( keys[i], vals[i] ); } //noinspection MismatchedQueryAndUpdateOfCollection TObjectIntMapDecorator map = new TObjectIntMapDecorator( raw_map ); assertEquals( raw_map, map.getMap() ); } public void testContainsKey() { int element_count = 20; String[] keys = new String[element_count]; int[] vals = new int[element_count]; TObjectIntMap map = new TObjectIntHashMap(); for ( int i = 0; i < element_count; i++ ) { keys[i] = Integer.toString( i + 1 ); vals[i] = i + 1; map.put( keys[i], vals[i] ); } for ( int i = 0; i < element_count; i++ ) { assertTrue( "Key should be present: " + keys[i] + ", map: " + map, map.containsKey( keys[i] ) ); } String key = "1138"; assertFalse( "Key should not be present: " + key + ", map: " + map, map.containsKey( key ) ); assertFalse( "Random object should not be present in map: " + map, map.containsKey( new Object() ) ); } public void testContainsValue() { int element_count = 20; String[] keys = new String[element_count]; int[] vals = new int[element_count]; TObjectIntMap map = new TObjectIntHashMap(); for ( int i = 0; i < element_count; i++ ) { keys[i] = Integer.toString( i + 1 ); vals[i] = i + 1; map.put( keys[i], vals[i] ); } for ( int i = 0; i < element_count; i++ ) { assertTrue( "Value should be present: " + vals[i] + ", map: " + map, map.containsValue( vals[i] ) ); } int val = 1138; assertFalse( "Key should not be present: " + val + ", map: " + map, map.containsValue( val ) ); } public void testPutIfAbsent() { TObjectIntHashMap map = new TObjectIntHashMap(); map.put( "One", 1 ); map.put( "Two", 2 ); map.put( "Three", 3 ); assertEquals( 1, map.putIfAbsent( "One", 2 ) ); assertEquals( 1, map.get( "One" ) ); assertEquals( 0, map.putIfAbsent( "Nine", 9 ) ); assertEquals( 9, map.get( "Nine" ) ); } public void testRemove() { int element_count = 20; String[] keys = new String[element_count]; Integer[] vals = new Integer[element_count]; TObjectIntMap raw_map = new TObjectIntHashMap(); Map map = TDecorators.wrap( raw_map ); for ( int i = 0; i < element_count; i++ ) { keys[i] = Integer.toString( i + 1 ); vals[i] = i + 1; map.put( keys[i], vals[i] ); } for ( int i = 0; i < element_count; i++ ) { if ( i % 2 == 1 ) { assertEquals( "Remove should have modified map: " + keys[i] + ", map: " + map, vals[i], map.remove( keys[i] ) ); } } for ( int i = 0; i < element_count; i++ ) { if ( i % 2 == 1 ) { assertNull( "Removed key still in map: " + keys[i] + ", map: " + map, map.get( keys[i] ) ); } else { assertEquals( "Key should still be in map: " + keys[i] + ", map: " + map, vals[i], map.get( keys[i] ) ); } } assertNull( map.get( "1138" ) ); //noinspection SuspiciousMethodCalls assertNull( map.get( Integer.valueOf( 1138 ) ) ); assertNull( map.get( null ) ); map.put( "null-value", null ); assertEquals( raw_map.getNoEntryValue(), raw_map.get( "null-value" ) ); assertTrue( map.containsKey( "null-value" ) ); Integer value = map.get( "null-value" ); assertNull( "value: " + value, value ); assertNull( map.remove( "null-value" ) ); } public void testPutAllMap() { int element_count = 20; String[] keys = new String[element_count]; int[] vals = new int[element_count]; TObjectIntMap control = new TObjectIntHashMap(); for ( int i = 0; i < element_count; i++ ) { keys[i] = Integer.toString( i + 1 ); vals[i] = i + 1; control.put( keys[i], vals[i] ); } TObjectIntMap raw_map = new TObjectIntHashMap(); Map map = TDecorators.wrap( raw_map ); Map source = new HashMap(); for ( int i = 0; i < element_count; i++ ) { source.put( keys[i], vals[i] ); } map.putAll( source ); assertEquals( source, map ); assertEquals( control, raw_map ); } public void testClear() { int element_count = 20; String[] keys = new String[element_count]; int[] vals = new int[element_count]; TObjectIntMap raw_map = new TObjectIntHashMap(); Map map = TDecorators.wrap( raw_map ); for ( int i = 0; i < element_count; i++ ) { keys[i] = Integer.toString( i + 1 ); vals[i] = i + 1; map.put( keys[i], vals[i] ); } assertEquals( element_count, raw_map.size() ); map.clear(); assertTrue( map.isEmpty() ); assertEquals( 0, map.size() ); assertNull( map.get( keys[5] ) ); } public void testKeySet() { int element_count = 20; String[] keys = new String[element_count]; int[] vals = new int[element_count]; TObjectIntMap raw_map = new TObjectIntHashMap(); Map map = TDecorators.wrap( raw_map ); for ( int i = 0; i < element_count; i++ ) { keys[i] = Integer.toString( i + 1 ); vals[i] = i + 1; map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); Set keyset = map.keySet(); for ( int i = 0; i < keyset.size(); i++ ) { assertTrue( keyset.contains( keys[i] ) ); } assertFalse( keyset.isEmpty() ); Object[] keys_obj_array = keyset.toArray(); int count = 0; Iterator iter = keyset.iterator(); while ( iter.hasNext() ) { String key = iter.next(); assertTrue( keyset.contains( key ) ); assertEquals( keys_obj_array[count], key ); count++; } //noinspection ToArrayCallWithZeroLengthArrayArgument String[] keys_array = keyset.toArray( new String[0] ); count = 0; iter = keyset.iterator(); while ( iter.hasNext() ) { String key = iter.next(); assertTrue( keyset.contains( key ) ); assertEquals( keys_array[count], key ); count++; } keys_array = keyset.toArray( new String[keyset.size()] ); count = 0; iter = keyset.iterator(); while ( iter.hasNext() ) { String key = iter.next(); assertTrue( keyset.contains( key ) ); assertEquals( keys_array[count], key ); count++; } keys_array = keyset.toArray( new String[keyset.size() * 2] ); count = 0; iter = keyset.iterator(); while ( iter.hasNext() ) { String key = iter.next(); assertTrue( keyset.contains( key ) ); assertEquals( keys_array[count], key ); count++; } assertNull( keys_array[keyset.size()] ); Set other = new HashSet( keyset ); assertFalse( keyset.retainAll( other ) ); other.remove( keys[5] ); assertTrue( keyset.retainAll( other ) ); assertFalse( keyset.contains( keys[5] ) ); assertFalse( map.containsKey( keys[5] ) ); keyset.clear(); assertTrue( keyset.isEmpty() ); } public void testKeySetAdds() { int element_count = 20; String[] keys = new String[element_count]; int[] vals = new int[element_count]; TObjectIntMap raw_map = new TObjectIntHashMap(); Map map = TDecorators.wrap( raw_map ); for ( int i = 0; i < element_count; i++ ) { keys[i] = Integer.toString( i + 1 ); vals[i] = i + 1; map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); Set keyset = map.keySet(); for ( int i = 0; i < keyset.size(); i++ ) { assertTrue( keyset.contains( keys[i] ) ); } assertFalse( keyset.isEmpty() ); try { keyset.add( "explosions!" ); fail( "Expected UnsupportedOperationException" ); } catch ( UnsupportedOperationException ex ) { // Expected } try { Set test = new HashSet(); test.add( "explosions!" ); keyset.addAll( test ); fail( "Expected UnsupportedOperationException" ); } catch ( UnsupportedOperationException ex ) { // Expected } } public void testKeys() { int element_count = 20; String[] keys = new String[element_count]; int[] vals = new int[element_count]; TObjectIntMap raw_map = new TObjectIntHashMap(); Map map = TDecorators.wrap( raw_map ); for ( int i = 0; i < element_count; i++ ) { keys[i] = Integer.toString( i + 1 ); vals[i] = i + 1; map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); // No argument Object[] keys_object_array = map.keySet().toArray(); assertEquals( element_count, keys_object_array.length ); List keys_object_list = Arrays.asList( keys_object_array ); for ( int i = 0; i < element_count; i++ ) { assertTrue( keys_object_list.contains( keys[i] ) ); } // Zero length array //noinspection ToArrayCallWithZeroLengthArrayArgument String[] keys_string_array = map.keySet().toArray( new String[0] ); assertEquals( element_count, keys_string_array.length ); List keys_string_list = Arrays.asList( keys_string_array ); for ( int i = 0; i < element_count; i++ ) { assertTrue( keys_string_list.contains( keys[i] ) ); } // appropriate length array keys_string_array = map.keySet().toArray( new String[map.size()] ); assertEquals( element_count, keys_string_array.length ); keys_string_list = Arrays.asList( keys_string_array ); for ( int i = 0; i < element_count; i++ ) { assertTrue( keys_string_list.contains( keys[i] ) ); } // longer array keys_string_array = map.keySet().toArray( new String[element_count * 2] ); assertEquals( element_count * 2, keys_string_array.length ); keys_string_list = Arrays.asList( keys_string_array ); for ( int i = 0; i < element_count; i++ ) { assertTrue( keys_string_list.contains( keys[i] ) ); } assertNull( keys_string_array[element_count] ); } public void testValueCollectionToArray() { int element_count = 20; String[] keys = new String[element_count]; int[] vals = new int[element_count]; TObjectIntMap raw_map = new TObjectIntHashMap( element_count, 0.5f, Integer.MIN_VALUE ); Map map = TDecorators.wrap( raw_map ); for ( int i = 0; i < element_count; i++ ) { keys[i] = Integer.toString( i + 1 ); vals[i] = i + 1; map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); Collection collection = map.values(); for ( int i = 0; i < collection.size(); i++ ) { assertTrue( collection.contains( vals[i] ) ); } assertFalse( collection.isEmpty() ); Object[] values_array = collection.toArray(); int count = 0; Iterator iter = collection.iterator(); while ( iter.hasNext() ) { int value = iter.next(); assertTrue( collection.contains( value ) ); assertEquals( values_array[count], value ); count++; } //noinspection ToArrayCallWithZeroLengthArrayArgument values_array = collection.toArray( new Integer[0] ); count = 0; iter = collection.iterator(); while ( iter.hasNext() ) { int value = iter.next(); assertTrue( collection.contains( value ) ); assertEquals( values_array[count], value ); count++; } values_array = collection.toArray( new Integer[collection.size()] ); count = 0; iter = collection.iterator(); while ( iter.hasNext() ) { int value = iter.next(); assertTrue( collection.contains( value ) ); assertEquals( values_array[count], value ); count++; } values_array = collection.toArray( new Integer[collection.size() * 2] ); count = 0; iter = collection.iterator(); while ( iter.hasNext() ) { int value = iter.next(); assertTrue( collection.contains( value ) ); assertEquals( values_array[count], value ); count++; } assertNull( values_array[collection.size()] ); assertNull( values_array[collection.size()] ); Collection other = new ArrayList( collection ); assertFalse( collection.retainAll( other ) ); other.remove( vals[5] ); assertTrue( collection.retainAll( other ) ); assertFalse( collection.contains( vals[5] ) ); assertFalse( map.containsKey( keys[5] ) ); collection.clear(); assertTrue( collection.isEmpty() ); } public void testValueCollectionAdds() { int element_count = 20; String[] keys = new String[element_count]; int[] vals = new int[element_count]; TObjectIntMap raw_map = new TObjectIntHashMap(); Map map = TDecorators.wrap( raw_map ); for ( int i = 0; i < element_count; i++ ) { keys[i] = Integer.toString( i + 1 ); vals[i] = i + 1; map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); Collection collection = map.values(); for ( int i = 0; i < collection.size(); i++ ) { assertTrue( collection.contains( vals[i] ) ); } assertFalse( collection.isEmpty() ); try { collection.add( 1138 ); fail( "Expected UnsupportedOperationException" ); } catch ( UnsupportedOperationException ex ) { // Expected } try { Set test = new HashSet(); test.add( Integer.valueOf( 1138 ) ); collection.addAll( test ); fail( "Expected UnsupportedOperationException" ); } catch ( UnsupportedOperationException ex ) { // Expected } try { Collection test = new ArrayList(); test.add( 1138 ); collection.addAll( test ); fail( "Expected UnsupportedOperationException" ); } catch ( UnsupportedOperationException ex ) { // Expected } try { Integer[] integer_vals = new Integer[vals.length]; for ( int i = 0; i < vals.length; i++ ) { integer_vals[i] = Integer.valueOf( vals[i] ); } collection.addAll( Arrays.asList( integer_vals ) ); fail( "Expected UnsupportedOperationException" ); } catch ( UnsupportedOperationException ex ) { // Expected } } public void testValueCollectionContainsAll() { int element_count = 20; String[] keys = new String[element_count]; int[] vals = new int[element_count]; TObjectIntMap raw_map = new TObjectIntHashMap(); Map map = TDecorators.wrap( raw_map ); for ( int i = 0; i < element_count; i++ ) { keys[i] = Integer.toString( i + 1 ); vals[i] = i + 1; map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); Collection collection = map.values(); for ( int i = 0; i < collection.size(); i++ ) { assertTrue( collection.contains( vals[i] ) ); } assertFalse( collection.isEmpty() ); List java_list = new ArrayList(); for ( int value : vals ) { java_list.add( value ); } assertTrue( "collection: " + collection + ", should contain all in list: " + java_list, collection.containsAll( java_list ) ); java_list.add( Integer.valueOf( 1138 ) ); assertFalse( "collection: " + collection + ", should not contain all in list: " + java_list, collection.containsAll( java_list ) ); List number_list = new ArrayList(); for ( int value : vals ) { if ( value == 5 ) { number_list.add( Long.valueOf( value ) ); } else { number_list.add( Integer.valueOf( value ) ); } } assertFalse( "collection: " + collection + ", should not contain all in list: " + java_list, collection.containsAll( number_list ) ); Collection other = new ArrayList( collection ); assertTrue( "collection: " + collection + ", should contain all in other: " + other, collection.containsAll( other ) ); other.add( 1138 ); assertFalse( "collection: " + collection + ", should not contain all in other: " + other, collection.containsAll( other ) ); } public void testValueCollectionRetainAllCollection() { int element_count = 20; String[] keys = new String[element_count]; int[] vals = new int[element_count]; TObjectIntMap raw_map = new TObjectIntHashMap(); Map map = TDecorators.wrap( raw_map ); for ( int i = 0; i < element_count; i++ ) { keys[i] = Integer.toString( i + 1 ); vals[i] = i + 1; map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); Collection collection = map.values(); for ( int i = 0; i < collection.size(); i++ ) { assertTrue( collection.contains( vals[i] ) ); } assertFalse( collection.isEmpty() ); List java_list = new ArrayList(); for ( int value : vals ) { java_list.add( value ); } assertFalse( "collection: " + collection + ", should contain all in list: " + java_list, collection.retainAll( java_list ) ); java_list.remove( 5 ); assertTrue( "collection: " + collection + ", should contain all in list: " + java_list, collection.retainAll( java_list ) ); assertFalse( collection.contains( vals[5] ) ); assertFalse( map.containsKey( keys[5] ) ); assertFalse( map.containsValue( vals[5] ) ); assertTrue( "collection: " + collection + ", should contain all in list: " + java_list, collection.containsAll( java_list ) ); } public void testValueCollectionRetainAllTCollection() { int element_count = 20; String[] keys = new String[element_count]; int[] vals = new int[element_count]; TObjectIntMap raw_map = new TObjectIntHashMap(); Map map = TDecorators.wrap( raw_map ); for ( int i = 0; i < element_count; i++ ) { keys[i] = Integer.toString( i + 1 ); vals[i] = i + 1; map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); Collection collection = map.values(); for ( int i = 0; i < collection.size(); i++ ) { assertTrue( collection.contains( vals[i] ) ); } assertFalse( collection.isEmpty() ); assertFalse( "collection: " + collection + ", should be unmodified.", collection.retainAll( collection ) ); Collection other = new ArrayList( collection ); assertFalse( "collection: " + collection + ", should be unmodified. other: " + other, collection.retainAll( other ) ); other.remove( vals[5] ); assertTrue( "collection: " + collection + ", should be modified. other: " + other, collection.retainAll( other ) ); assertFalse( collection.contains( vals[5] ) ); assertFalse( map.containsKey( keys[5] ) ); assertFalse( map.containsValue( vals[5] ) ); assertTrue( "collection: " + collection + ", should contain all in other: " + other, collection.containsAll( other ) ); } public void testValueCollectionRemoveAllCollection() { int element_count = 20; String[] keys = new String[element_count]; int[] vals = new int[element_count]; TObjectIntMap raw_map = new TObjectIntHashMap(); Map map = TDecorators.wrap( raw_map ); for ( int i = 0; i < element_count; i++ ) { keys[i] = Integer.toString( i + 1 ); vals[i] = i + 1; map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); Collection collection = map.values(); for ( int i = 0; i < collection.size(); i++ ) { assertTrue( collection.contains( vals[i] ) ); } assertFalse( collection.isEmpty() ); List java_list = new ArrayList(); assertFalse( "collection: " + collection + ", should contain all in list: " + java_list, collection.removeAll( java_list ) ); java_list.add( vals[5] ); assertTrue( "collection: " + collection + ", should contain all in list: " + java_list, collection.removeAll( java_list ) ); assertFalse( collection.contains( vals[5] ) ); assertFalse( map.containsKey( keys[5] ) ); assertFalse( map.containsValue( vals[5] ) ); java_list = new ArrayList(); for ( int value : vals ) { java_list.add( value ); } assertTrue( "collection: " + collection + ", should contain all in list: " + java_list, collection.removeAll( java_list ) ); assertTrue( collection.isEmpty() ); } public void testValueCollectionRemoveAllTCollection() { int element_count = 20; String[] keys = new String[element_count]; int[] vals = new int[element_count]; TObjectIntMap raw_map = new TObjectIntHashMap(); Map map = TDecorators.wrap( raw_map ); for ( int i = 0; i < element_count; i++ ) { keys[i] = Integer.toString( i + 1 ); vals[i] = i + 1; map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); Collection collection = map.values(); for ( int i = 0; i < collection.size(); i++ ) { assertTrue( collection.contains( vals[i] ) ); } assertFalse( collection.isEmpty() ); Collection other = new ArrayList(); assertFalse( "collection: " + collection + ", should be unmodified.", collection.removeAll( other ) ); other = new ArrayList( collection ); other.remove( vals[5] ); assertTrue( "collection: " + collection + ", should be modified. other: " + other, collection.removeAll( other ) ); assertEquals( 1, collection.size() ); for ( int i = 0; i < element_count; i++ ) { if ( i == 5 ) { assertTrue( collection.contains( vals[i] ) ); assertTrue( map.containsKey( keys[i] ) ); assertTrue( map.containsValue( vals[i] ) ); } else { assertFalse( collection.contains( vals[i] ) ); assertFalse( map.containsKey( keys[i] ) ); assertFalse( map.containsValue( vals[i] ) ); } } assertFalse( "collection: " + collection + ", should be unmodified. other: " + other, collection.removeAll( other ) ); assertTrue( "collection: " + collection + ", should be modified. other: " + other, collection.removeAll( collection ) ); assertTrue( collection.isEmpty() ); } public void testValueCollectionHashCode() { int element_count = 20; String[] keys = new String[element_count]; int[] vals = new int[element_count]; TObjectIntMap raw_map = new TObjectIntHashMap(); Map map = TDecorators.wrap( raw_map ); TObjectIntMap raw_map2 = new TObjectIntHashMap(); Map map2 = TDecorators.wrap( raw_map2 ); for ( int i = 0; i < element_count; i++ ) { keys[i] = Integer.toString( i + 1 ); vals[i] = i + 1; map.put( keys[i], vals[i] ); map2.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); Collection values = map.values(); Collection other = map2.values(); assertTrue( values.hashCode() == values.hashCode() ); assertTrue( other.hashCode() == other.hashCode() ); map2.put( String.valueOf( 1138 ), 1138 ); assertFalse( values.hashCode() == other.hashCode() ); } public void testValues() { int element_count = 20; String[] keys = new String[element_count]; Integer[] vals = new Integer[element_count]; TObjectIntMap raw_map = new TObjectIntHashMap( element_count, 0.5f, Integer.MIN_VALUE ); Map map = TDecorators.wrap( raw_map ); for ( int i = 0; i < element_count; i++ ) { keys[i] = Integer.toString( i + 1 ); vals[i] = Integer.valueOf( i + 1 ); map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); // No argument Collection values_collection = map.values(); assertEquals( element_count, values_collection.size() ); List values_list = new ArrayList( values_collection ); for ( int i = 0; i < element_count; i++ ) { assertTrue( values_list.contains( vals[i] ) ); } } public void testEntrySet() { int element_count = 20; String[] keys = new String[element_count]; Integer[] vals = new Integer[element_count]; TObjectIntMap raw_map = new TObjectIntHashMap( element_count, 0.5f, Integer.MIN_VALUE ); Map map = TDecorators.wrap( raw_map ); for ( int i = 0; i < element_count; i++ ) { keys[i] = Integer.toString( i + 1 ); vals[i] = Integer.valueOf( i + 1 ); map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); Set> entries = map.entrySet(); assertEquals( element_count, entries.size() ); assertFalse( entries.isEmpty() ); //noinspection unchecked Map.Entry[] array = entries.toArray( new Map.Entry[entries.size()] ); for ( Map.Entry entry : array ) { assertTrue( entries.contains( entry ) ); } assertFalse( entries.contains( null ) ); assertEquals( array[0].hashCode(), array[0].hashCode() ); assertTrue( array[0].hashCode() != array[1].hashCode() ); assertTrue( array[0].equals( array[0] ) ); assertFalse( array[0].equals( array[1] ) ); String key = array[0].getKey(); Integer old_value = array[0].getValue(); assertEquals( old_value, array[0].setValue( old_value * 2 ) ); assertEquals( Integer.valueOf( old_value * 2 ), map.get( key ) ); assertEquals( Integer.valueOf( old_value * 2 ), array[0].getValue() ); // Adds are not allowed Map.Entry invalid_entry = new Map.Entry() { public String getKey() { return null; } public Integer getValue() { return null; } public Integer setValue( Integer value ) { return null; } }; List> invalid_entry_list = new ArrayList>(); invalid_entry_list.add( invalid_entry ); try { entries.add( invalid_entry ); fail( "Expected OperationUnsupportedException" ); } catch ( UnsupportedOperationException ex ) { // Expected } try { entries.addAll( invalid_entry_list ); fail( "Expected OperationUnsupportedException" ); } catch ( UnsupportedOperationException ex ) { // Expected } assertFalse( entries.containsAll( invalid_entry_list ) ); assertFalse( entries.removeAll( invalid_entry_list ) ); List> partial_list = new ArrayList>(); partial_list.add( array[3] ); partial_list.add( array[4] ); assertTrue( entries.removeAll( partial_list ) ); assertEquals( element_count - 2, entries.size() ); assertEquals( element_count - 2, map.size() ); entries.clear(); assertTrue( entries.isEmpty() ); assertTrue( map.isEmpty() ); } public void testEquals() { int element_count = 20; String[] keys = new String[element_count]; int[] vals = new int[element_count]; TObjectIntMap raw_map = new TObjectIntHashMap( element_count, 0.5f, Integer.MIN_VALUE ); Map map = TDecorators.wrap( raw_map ); for ( int i = 0; i < element_count; i++ ) { keys[i] = Integer.toString( i + 1 ); vals[i] = i + 1; map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); TObjectIntHashMap raw_fully_specified = new TObjectIntHashMap( 20, 0.75f, Integer.MIN_VALUE ); Map fully_specified = TDecorators.wrap( raw_fully_specified ); for ( int i = 0; i < element_count; i++ ) { fully_specified.put( keys[i], vals[i] ); } assertEquals( map, fully_specified ); assertFalse( "shouldn't equal random object", map.equals( new Object() ) ); //noinspection ObjectEqualsNull assertFalse( "shouldn't equal null", map.equals( null ) ); } @SuppressWarnings({"unchecked"}) public void testSerialize() throws Exception { Integer[] vals = {1138, 42, 86, 99, 101, 727, 117}; String[] keys = new String[vals.length]; TObjectIntMap raw_map = new TObjectIntHashMap(); Map map = TDecorators.wrap( raw_map ); for ( int i = 0; i < keys.length; i++ ) { keys[i] = Integer.toString( vals[i] * 2 ); map.put( keys[i], vals[i] ); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream( baos ); oos.writeObject( map ); ByteArrayInputStream bias = new ByteArrayInputStream( baos.toByteArray() ); ObjectInputStream ois = new ObjectInputStream( bias ); Map deserialized = ( Map ) ois.readObject(); assertEquals( map, deserialized ); } public void testToString() { TObjectIntHashMap m = new TObjectIntHashMap(); m.put( "One", 11 ); m.put( "Two", 22 ); String to_string = m.toString(); assertTrue( to_string, to_string.equals( "{One=11,Two=22}" ) || to_string.equals( "{Two=22,One=11}" ) ); } } trove-3.0.3/test/gnu/trove/decorator/TPrimitiveSetDecoratorTest.java0000644000175000017500000005024011763017634024642 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2002, Eric D. Friedman All Rights Reserved. // Copyright (c) 2009, Robert D. Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.decorator; import junit.framework.TestCase; import gnu.trove.set.TIntSet; import gnu.trove.set.hash.TIntHashSet; import gnu.trove.TDecorators; import java.util.*; import java.io.ByteArrayOutputStream; import java.io.ObjectOutputStream; import java.io.ByteArrayInputStream; import java.io.ObjectInputStream; /** * @author Eric D. Friedman * @author Robert D. Eden * @author Jeff Randall */ public class TPrimitiveSetDecoratorTest extends TestCase { public TPrimitiveSetDecoratorTest( String name ) { super( name ); } public void setUp() throws Exception { super.setUp(); } public void tearDown() throws Exception { super.tearDown(); } public void testConstructors() throws Exception { TIntSet raw_set = new TIntHashSet(); Set set = TDecorators.wrap( raw_set ); assertNotNull( set ); Integer[] ints = {1138, 42, 86, 99, 101}; set.addAll( Arrays.asList( ints ) ); Set copy = new HashSet( set ); assertTrue( "set not a copy: " + set + ", " + copy, set.equals( copy ) ); TIntSet raw_another = new TIntHashSet( 20 ); Set another = TDecorators.wrap( raw_another ); another.addAll( Arrays.asList( ints ) ); assertTrue( "set not equal: " + set + ", " + copy, set.equals( another ) ); raw_another = new TIntHashSet( 2, 1.0f ); another = TDecorators.wrap( raw_another ); another.addAll( Arrays.asList( ints ) ); assertTrue( "set not equal: " + set + ", " + copy, set.equals( another ) ); raw_another = new TIntHashSet( Arrays.asList( ints ) ); another = TDecorators.wrap( raw_another ); assertTrue( "set not equal: " + set + ", " + copy, set.equals( another ) ); } public void testIsEmpty() throws Exception { TIntSet raw_set = new TIntHashSet(); Set set = TDecorators.wrap( raw_set ); assertTrue( "new set wasn't empty", set.isEmpty() ); set.add( 1 ); assertFalse( "set with element reports empty", set.isEmpty() ); set.clear(); assertTrue( "cleared set reports not-empty", set.isEmpty() ); } public void testContains() throws Exception { TIntSet raw_set = new TIntHashSet(); Set set = TDecorators.wrap( raw_set ); int i = 100; set.add( i ); assertTrue( "contains failed", set.contains( i ) ); assertFalse( "contains failed", set.contains( 1000 ) ); } @SuppressWarnings({"ForLoopReplaceableByForEach"}) public void testContainsAll() throws Exception { Integer[] ints = {1138, 42, 13, 86, 99}; TIntSet raw_set = new TIntHashSet(); Set set = TDecorators.wrap( raw_set ); set.addAll( Arrays.asList( ints ) ); TIntSet raw_other = new TIntHashSet(); Set other = TDecorators.wrap( raw_other ); other.addAll( Arrays.asList( ints ) ); List ints_list = new ArrayList(); ints_list.addAll( Arrays.asList( ints ) ); for ( int index = 0; index < ints.length; index++ ) { assertTrue( Integer.valueOf( ints[index] ).toString(), set.contains( ints[index] ) ); } assertTrue( "containsAll(Collection) failed: " + set, set.containsAll( ints_list ) ); assertTrue( "containsAll(TIntSet) failed (same set): " + set, set.containsAll( set ) ); assertTrue( "containsAll(TIntSet) failed (other set): " + set, set.containsAll( other ) ); Integer[] failed = {42, 86, 99, 123456}; TIntSet raw_failed_set = new TIntHashSet(); Set failed_set = TDecorators.wrap( raw_failed_set ); failed_set.addAll( Arrays.asList( failed ) ); List failed_list = new ArrayList(); failed_list.addAll( Arrays.asList( failed ) ); assertFalse( "containsAll(Collection) failed (false positive): " + set, set.containsAll( failed_list ) ); assertFalse( "containsAll(TIntSet) failed (false positive): " + set, set.containsAll( failed_set ) ); } public void testAddAll() throws Exception { Integer[] ints = {1138, 42, 13, 86, 99, 101}; TIntSet raw_set; List list = new ArrayList(); for ( int element : ints ) { list.add( Integer.valueOf( element ) ); } raw_set = new TIntHashSet(); Set set = TDecorators.wrap( raw_set ); assertTrue( "addAll(Collection) failed: " + set, set.addAll( list ) ); for ( int element : ints ) { assertTrue( "contains failed: ", set.contains( element ) ); } TIntSet raw_test_set = new TIntHashSet(); Set test_set = TDecorators.wrap( raw_test_set ); assertTrue( "addAll(TIntSet) failed: " + test_set, test_set.addAll( set ) ); for ( int element : ints ) { assertTrue( "contains failed: ", set.contains( element ) ); } } public void testRetainAll() throws Exception { Integer[] ints = {1138, 42, 13, 86, 99, 101}; TIntSet raw_set = new TIntHashSet(); Set set = TDecorators.wrap( raw_set ); set.addAll( Arrays.asList( ints ) ); TIntSet other = new TIntHashSet(); other.addAll( Arrays.asList( ints ) ); Integer[] to_retain = {13, 86, 99, 1138}; TIntSet raw_retain_set = new TIntHashSet(); Set retain_set = TDecorators.wrap( raw_retain_set ); retain_set.addAll( Arrays.asList( to_retain ) ); List retain_list = new ArrayList(); retain_list.addAll( Arrays.asList( to_retain ) ); assertFalse( "retainAll(Set) failed (same set): " + set, set.retainAll( set ) ); // Contains all the original elements assertTrue( set.toString(), set.containsAll( Arrays.asList( ints ) ) ); assertTrue( retain_set.toString(), retain_set.containsAll( Arrays.asList( to_retain ) ) ); assertTrue( "retainAll(Collection) failed: " + set, set.retainAll( retain_list ) ); // Contains just the expected elements assertFalse( set.toString(), set.containsAll( Arrays.asList( ints ) ) ); assertTrue( set.toString(), set.containsAll( Arrays.asList( to_retain ) ) ); assertTrue( retain_set.toString(), retain_set.containsAll( Arrays.asList( to_retain ) ) ); // reset the set. raw_set = new TIntHashSet(); set = TDecorators.wrap( raw_set ); set.addAll( Arrays.asList( ints ) ); assertTrue( "retainAll(TIntSet) failed: " + set, set.retainAll( retain_set ) ); // Contains just the expected elements assertFalse( set.toString(), set.containsAll( Arrays.asList( ints ) ) ); assertTrue( set.toString(), set.containsAll( Arrays.asList( to_retain ) ) ); assertTrue( retain_set.toString(), retain_set.containsAll( Arrays.asList( to_retain ) ) ); } public void testRemoveAll() throws Exception { Integer[] ints = {1138, 42, 13, 86, 99, 101}; TIntSet raw_set = new TIntHashSet(); Set set = TDecorators.wrap( raw_set ); set.addAll( Arrays.asList( ints ) ); TIntSet raw_other = new TIntHashSet(); Set other = TDecorators.wrap( raw_other ); other.addAll( Arrays.asList( ints ) ); Integer[] to_remove = {13, 86, 99, 1138}; TIntSet raw_remove_set = new TIntHashSet(); Set remove_set = TDecorators.wrap( raw_remove_set ); remove_set.addAll( Arrays.asList( to_remove ) ); List remove_list = new ArrayList(); remove_list.addAll( Arrays.asList( to_remove ) ); Integer[] remainder = {42, 101}; assertTrue( "removeAll(Collections) failed (same set): " + set, set.removeAll( set ) ); // reset the set. raw_set = new TIntHashSet(); set = TDecorators.wrap( raw_set ); set.addAll( Arrays.asList( ints ) ); assertTrue( "removeAll(Collection) failed: " + set, set.removeAll( remove_list ) ); // Contains just the expected elements assertTrue( set.toString(), set.containsAll( Arrays.asList( remainder ) ) ); assertFalse( set.toString(), set.containsAll( Arrays.asList( to_remove ) ) ); assertTrue( remove_set.toString(), remove_set.containsAll( Arrays.asList( to_remove ) ) ); // reset the set. raw_set = new TIntHashSet(); set = TDecorators.wrap( raw_set ); set.addAll( Arrays.asList( ints ) ); assertTrue( "removeAll(TIntSet) failed: " + set, set.removeAll( remove_set ) ); // Contains just the expected elements assertTrue( set.toString(), set.containsAll( Arrays.asList( remainder ) ) ); assertFalse( set.toString(), set.containsAll( Arrays.asList( to_remove ) ) ); assertTrue( remove_set.toString(), remove_set.containsAll( Arrays.asList( to_remove ) ) ); } public void testAdd() throws Exception { TIntSet raw_set = new TIntHashSet(); Set set = TDecorators.wrap( raw_set ); assertTrue( "add failed", set.add( 1 ) ); assertFalse( "duplicated add modified set", set.add( 1 ) ); } public void testRemove() throws Exception { TIntSet raw_set = new TIntHashSet(); Set set = TDecorators.wrap( raw_set ); set.add( 1 ); set.add( 2 ); assertTrue( "One was not added", set.contains( 1 ) ); assertTrue( "One was not removed", set.remove( 1 ) ); assertFalse( "One was not removed", set.contains( 1 ) ); assertTrue( "Two was also removed", set.contains( 2 ) ); } public void testRemoveNonExistant() throws Exception { TIntSet raw_set = new TIntHashSet(); Set set = TDecorators.wrap( raw_set ); set.add( 1 ); set.add( 2 ); assertTrue( "One was not added", set.contains( 1 ) ); assertTrue( "One was not removed", set.remove( 1 ) ); assertFalse( "One was not removed", set.contains( 1 ) ); assertTrue( "Two was also removed", set.contains( 2 ) ); assertFalse( "Three was removed (non-existant)", set.remove( 3 ) ); } public void testSize() throws Exception { TIntSet raw_set = new TIntHashSet(); Set set = TDecorators.wrap( raw_set ); assertEquals( "initial size was not 0", 0, set.size() ); for ( int i = 0; i < 99; i++ ) { set.add( i ); assertEquals( "size did not increase after add", i + 1, set.size() ); } } public void testClear() throws Exception { TIntSet raw_set = new TIntHashSet(); Set set = TDecorators.wrap( raw_set ); set.add( 1 ); set.add( 2 ); set.add( 3 ); assertEquals( "size was not 3", 3, set.size() ); set.clear(); assertEquals( "initial size was not 0", 0, set.size() ); } public void testSerialize() throws Exception { Integer[] ints = {1138, 42, 86, 99, 101}; TIntSet raw_set = new TIntHashSet(); Set set = TDecorators.wrap( raw_set ); set.addAll( Arrays.asList( ints ) ); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream( baos ); oos.writeObject( set ); ByteArrayInputStream bias = new ByteArrayInputStream( baos.toByteArray() ); ObjectInputStream ois = new ObjectInputStream( bias ); //noinspection unchecked Set deserialized = ( Set ) ois.readObject(); assertEquals( set, deserialized ); } public void testToArray() { TIntSet raw_set = new TIntHashSet(); Set set = TDecorators.wrap( raw_set ); Integer[] ints = {42, 1138, 13, 86, 99}; set.addAll( Arrays.asList( ints ) ); Object[] obj_res = set.toArray(); Arrays.sort( ints ); Arrays.sort( obj_res ); assertTrue( Arrays.equals( ints, obj_res ) ); Object[] res = set.toArray(); Arrays.sort( ints ); Arrays.sort( res ); assertTrue( Arrays.equals( ints, res ) ); res = set.toArray( new Integer[set.size()] ); Arrays.sort( ints ); Arrays.sort( res ); assertTrue( Arrays.equals( ints, res ) ); } public void testToArrayMatchesIteratorOrder() { TIntSet raw_set = new TIntHashSet(); Set set = TDecorators.wrap( raw_set ); Integer[] ints = {42, 1138, 13, 86, 99}; set.addAll( Arrays.asList( ints ) ); Integer[] toarray_ints = set.toArray( new Integer[ints.length] ); Integer[] iter_ints = new Integer[ints.length]; Iterator iter = set.iterator(); int index = 0; while ( iter.hasNext() ) { iter_ints[index++] = iter.next(); } assertTrue( Arrays.equals( iter_ints, toarray_ints ) ); } public void testToArrayWithParams() { int no_entry_value = Integer.MIN_VALUE; TIntSet raw_set = new TIntHashSet( 10, 0.5f, no_entry_value ); Set set = TDecorators.wrap( raw_set ); Integer[] ints = {42, 1138, 13, 86, 99}; set.addAll( Arrays.asList( ints ) ); Integer[] sink = new Integer[ints.length + 2]; sink[sink.length - 1] = -1; sink[sink.length - 2] = -2; Integer[] res = set.toArray( sink ); assertNull( res[set.size()] ); Set copy = new HashSet(); copy.addAll( Arrays.asList( sink ) ); Set bogey = new HashSet(); bogey.addAll( Arrays.asList( ints ) ); bogey.add( -1 ); bogey.add( null ); assertEquals( bogey, copy ); } public void testRehashing() throws Exception { int size = 10000; TIntSet set = new TIntHashSet( 10 ); for ( int i = 0; i < size; i++ ) { set.add( i ); } assertEquals( set.size(), size ); } public void testIterator() { TIntSet raw_set = new TIntHashSet(); Set set = TDecorators.wrap( raw_set ); set.add( 1 ); set.add( 2 ); set.add( 3 ); set.add( 4 ); Iterator iter = set.iterator(); assertTrue( "iterator should have a next item", iter.hasNext() ); int last = -1; while ( iter.hasNext() ) { int next = iter.next(); assertTrue( Integer.valueOf( next ).toString(), next >= 1 && next <= 4 ); assertTrue( Integer.valueOf( next ).toString(), next != last ); last = next; } assertFalse( "iterator should not have a next item", iter.hasNext() ); assertTrue( "set should contain 1", set.contains( 1 ) ); assertTrue( "set should contain 2", set.contains( 2 ) ); assertTrue( "set should contain 3", set.contains( 3 ) ); assertTrue( "set should contain 4", set.contains( 4 ) ); assertEquals( 4, set.size() ); } public void testIteratorRemove() { TIntSet raw_set = new TIntHashSet(); Set set = TDecorators.wrap( raw_set ); set.add( 1 ); set.add( 2 ); set.add( 3 ); set.add( 4 ); Iterator iter = set.iterator(); assertTrue( "iterator should have a next item", iter.hasNext() ); int last = -1; while ( iter.hasNext() ) { int next = iter.next(); assertTrue( next >= 1 && next <= 4 ); assertTrue( next != last ); last = next; if ( next == 3 ) { iter.remove(); } } assertFalse( "iterator should not have a next item", iter.hasNext() ); assertFalse( "set should not contain 3", set.contains( 3 ) ); assertTrue( "set should contain 1", set.contains( 1 ) ); assertTrue( "set should contain 2", set.contains( 2 ) ); assertTrue( "set should contain 4", set.contains( 4 ) ); assertEquals( 3, set.size() ); } public void testEquals() { Integer[] ints = {1138, 42, 86, 99, 101}; TIntSet raw_set = new TIntHashSet(); Set set = TDecorators.wrap( raw_set ); set.addAll( Arrays.asList( ints ) ); TIntSet raw_other = new TIntHashSet(); Set other = TDecorators.wrap( raw_other ); other.addAll( Arrays.asList( ints ) ); assertTrue( "sets incorrectly not equal: " + set + ", " + other, set.equals( other ) ); int[] mismatched = {72, 49, 53, 1024, 999}; TIntSet raw_unequal = new TIntHashSet(); raw_unequal.addAll( mismatched ); Set unequal = TDecorators.wrap( raw_unequal ); assertFalse( "sets incorrectly equal: " + set + ", " + unequal, set.equals( unequal ) ); // Change length, different code branch unequal.add( 1 ); assertFalse( "sets incorrectly equal: " + set + ", " + unequal, set.equals( unequal ) ); Set different_classes = new HashSet(); different_classes.addAll( Arrays.asList( ints ) ); different_classes.remove( Integer.valueOf( 86 ) ); different_classes.add( Long.valueOf( 86 ) ); assertFalse( "sets incorrectly equal: " + set + ", " + different_classes, set.equals( different_classes ) ); //noinspection ObjectEqualsNull assertFalse( set.equals( null ) ); // test against TIntSet assertTrue( set.equals( raw_other ) ); //noinspection MismatchedQueryAndUpdateOfCollection TIntSetDecorator decorated = new TIntSetDecorator( raw_other ); assertTrue( set.equals( decorated.getSet() ) ); } public void testHashcode() { int[] ints = {1138, 42, 86, 99, 101}; TIntSet raw_set = new TIntHashSet(); raw_set.addAll( ints ); Set set = TDecorators.wrap( raw_set ); TIntSet raw_other = new TIntHashSet(); raw_other.addAll( ints ); Set other = TDecorators.wrap( raw_other ); assertTrue( "hashcodes incorrectly not equal: " + set + ", " + other, set.hashCode() == other.hashCode() ); int[] mismatched = {72, 49, 53, 1024, 999}; TIntSet unequal = new TIntHashSet(); unequal.addAll( mismatched ); assertFalse( "hashcodes unlikely equal: " + set + ", " + unequal, set.hashCode() == unequal.hashCode() ); } } trove-3.0.3/test/gnu/trove/decorator/TPrimitivePrimitiveMapDecoratorTest.java0000644000175000017500000012746711763017634026535 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2002, Eric D. Friedman All Rights Reserved. // Copyright (c) 2009, Robert D. Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.decorator; import gnu.trove.TDecorators; import gnu.trove.map.TIntIntMap; import gnu.trove.map.TIntLongMap; import gnu.trove.map.hash.TIntIntHashMap; import gnu.trove.map.hash.TIntLongHashMap; import gnu.trove.map.hash.TIntObjectHashMap; import junit.framework.TestCase; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.*; /** * Test the primitive key/primitive value map decorators * * @author Eric D. Friedman * @author Robert D. Eden * @author Jeff Randall */ public class TPrimitivePrimitiveMapDecoratorTest extends TestCase { final int KEY_ONE = 100; final int KEY_TWO = 101; public TPrimitivePrimitiveMapDecoratorTest( String name ) { super( name ); } public void testConstructors() { int[] keys = {1138, 42, 86, 99, 101}; long[] vals = {1138, 42, 86, 99, 101}; TIntLongMap raw_map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { raw_map.put( keys[i], vals[i] ); } Map map = TDecorators.wrap( raw_map ); assertEquals( keys.length, map.size() ); TIntLongMap raw_capacity = new TIntLongHashMap( 20 ); for ( int i = 0; i < keys.length; i++ ) { raw_capacity.put( keys[i], vals[i] ); } Map capacity = TDecorators.wrap( raw_capacity ); assertEquals( keys.length, capacity.size() ); TIntLongMap raw_cap_and_factor = new TIntLongHashMap( 20, 0.75f ); for ( int i = 0; i < keys.length; i++ ) { raw_cap_and_factor.put( keys[i], vals[i] ); } Map cap_and_factor = TDecorators.wrap( raw_cap_and_factor ); assertEquals( keys.length, cap_and_factor.size() ); TIntLongMap raw_fully_specified = new TIntLongHashMap( 20, 0.5f, Integer.MIN_VALUE, Long.MIN_VALUE ); for ( int i = 0; i < keys.length; i++ ) { raw_fully_specified.put( keys[i], vals[i] ); } Map fully_specified = TDecorators.wrap( raw_fully_specified ); assertEquals( keys.length, fully_specified.size() ); TIntLongMap raw_copy = new TIntLongHashMap( raw_map ); Map copy = TDecorators.wrap( raw_copy ); assertEquals( keys.length, fully_specified.size() ); TIntLongMap raw_arrays = new TIntLongHashMap( keys, vals ); Map arrays = TDecorators.wrap( raw_arrays ); assertEquals( keys.length, arrays.size() ); // Equals in all combinations is paranoid.. but.. assertEquals( map, map ); assertEquals( map, capacity ); assertEquals( map, cap_and_factor ); assertEquals( map, fully_specified ); assertEquals( map, copy ); assertEquals( map, arrays ); assertEquals( capacity, map ); assertEquals( capacity, capacity ); assertEquals( capacity, cap_and_factor ); assertEquals( capacity, fully_specified ); assertEquals( capacity, copy ); assertEquals( capacity, arrays ); assertEquals( cap_and_factor, map ); assertEquals( cap_and_factor, capacity ); assertEquals( cap_and_factor, cap_and_factor ); assertEquals( cap_and_factor, fully_specified ); assertEquals( cap_and_factor, copy ); assertEquals( cap_and_factor, arrays ); assertEquals( fully_specified, map ); assertEquals( fully_specified, capacity ); assertEquals( fully_specified, cap_and_factor ); assertEquals( fully_specified, fully_specified ); assertEquals( fully_specified, copy ); assertEquals( fully_specified, arrays ); assertEquals( copy, map ); assertEquals( copy, capacity ); assertEquals( copy, cap_and_factor ); assertEquals( copy, fully_specified ); assertEquals( copy, copy ); assertEquals( copy, arrays ); assertEquals( arrays, map ); assertEquals( arrays, capacity ); assertEquals( arrays, cap_and_factor ); assertEquals( arrays, fully_specified ); assertEquals( arrays, copy ); assertEquals( arrays, arrays ); assertSame( raw_map, ( ( TIntLongMapDecorator ) map ).getMap() ); } public void testGet() { int element_count = 20; int[] keys = new int[element_count]; Long[] vals = new Long[element_count]; TIntLongMap raw_map = new TIntLongHashMap(); for ( int i = 0; i < element_count; i++ ) { keys[i] = i + 1; vals[i] = Long.valueOf( i + 1 ); raw_map.put( keys[i], vals[i] ); } Map map = TDecorators.wrap( raw_map ); assertEquals( vals[10], map.get( Integer.valueOf( keys[10] ) ) ); assertNull( map.get( Integer.valueOf( 1138 ) ) ); Integer key = Integer.valueOf( 1138 ); map.put( key, null ); assertTrue( map.containsKey( key ) ); assertNull( map.get( key ) ); Long long_key = Long.valueOf( 1138 ); //noinspection SuspiciousMethodCalls assertNull( map.get( long_key ) ); Long null_value = Long.valueOf( 747 ); map.put( null, null_value ); assertEquals( null_value, map.get( null ) ); } /** Be sure that size is large enough to force a resize or two. */ public void testRehash() { int size = 1000; int[] keys = new int[size]; long[] vals = new long[size]; for ( int i = 0; i < size; i++ ) { keys[i] = i + 1; vals[i] = keys[i] * 2; } TIntLongMap raw_map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { raw_map.put( keys[i], vals[i] ); } Map map = TDecorators.wrap( raw_map ); assertEquals( keys.length, map.size() ); for ( int i = 0; i < keys.length; i++ ) { Integer key = keys[i]; Long val = vals[i]; assertEquals( "got incorrect value for index " + i + ", map: " + map, val, map.get( key ) ); } } public void testPutAll() { int[] keys = {1138, 42, 86, 99, 101}; long[] vals = {1138, 42, 86, 99, 101}; TIntLongMap raw_map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { raw_map.put( keys[i], vals[i] * 2 ); } Map map = TDecorators.wrap( raw_map ); assertEquals( keys.length, map.size() ); TIntLongMap target = new TIntLongHashMap(); target.put( 1, 2 ); assertEquals( 1, target.size() ); target.putAll( map ); assertEquals( keys.length + 1, target.size() ); for ( int i = 0; i < keys.length; i++ ) { assertEquals( vals[i] * 2, target.get( keys[i] ) ); } assertEquals( 2, target.get( 1 ) ); // java.util.Map source Map java_map = new HashMap(); for ( int i = 0; i < keys.length; i++ ) { java_map.put( keys[i], vals[i] * 2 ); } // fresh TIntLongMap target = new TIntLongHashMap(); target.put( 1, 2 ); assertEquals( 1, target.size() ); target.putAll( java_map ); assertEquals( "map size is incorrect: " + keys.length + ", source: " + java_map + ", target: " + target, keys.length + 1, target.size() ); for ( int i = 0; i < keys.length; i++ ) { assertEquals( vals[i] * 2, target.get( keys[i] ) ); } assertEquals( 2, target.get( 1 ) ); } public void testClear() { int[] keys = {1138, 42, 86, 99, 101}; long[] vals = {1138, 42, 86, 99, 101}; TIntLongMap raw_map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { raw_map.put( keys[i], vals[i] * 2 ); } Map map = TDecorators.wrap( raw_map ); assertEquals( keys.length, map.size() ); map.clear(); assertEquals( 0, map.size() ); assertTrue( map.isEmpty() ); TIntLongMap raw_empty = new TIntLongHashMap(); Map empty = TDecorators.wrap( raw_empty ); assertEquals( empty, map ); } public void testRemove() { int[] keys = {1138, 42, 86, 99, 101, 727, 117}; Long[] vals = new Long[keys.length]; TIntLongMap raw_map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { vals[i] = Long.valueOf( keys[i] * 2 ); raw_map.put( keys[i], vals[i] ); } Map map = TDecorators.wrap( raw_map ); assertEquals( keys.length, map.size() ); for ( int i = 0; i < keys.length; i++ ) { assertEquals( vals[i], map.get( keys[i] ) ); } assertEquals( vals[0], map.remove( keys[0] ) ); assertEquals( vals[3], map.remove( keys[3] ) ); assertNull( map.remove( keys[0] ) ); assertEquals( vals[5], map.remove( keys[5] ) ); assertNull( map.remove( 11010110 ) ); assertNull( map.get( 1138 ) ); //noinspection SuspiciousMethodCalls assertNull( map.get( Integer.valueOf( 1138 ) ) ); assertNull( map.get( null ) ); Long null_value = Long.valueOf( 2112 ); map.put( null, null_value ); assertEquals( null_value.longValue(), raw_map.get( raw_map.getNoEntryKey() ) ); assertTrue( map.containsKey( null ) ); Long value = map.get( null ); assertEquals( "value: " + value, null_value, value ); assertEquals( null_value, map.remove( null ) ); assertFalse( map.containsKey( null ) ); //noinspection SuspiciousMethodCalls assertNull( map.remove( Long.valueOf( 1138 ) ) ); } public void testKeySetMisc() { int[] keys = {1138, 42, 86, 99, 101, 727, 117}; long[] vals = new long[keys.length]; TIntLongMap raw_map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { vals[i] = keys[i] * 2; raw_map.put( keys[i], vals[i] ); } Map map = TDecorators.wrap( raw_map ); Set set = map.keySet(); Integer[] sorted_keys = new Integer[keys.length]; for ( int i = 0; i < keys.length; i++ ) { sorted_keys[i] = keys[i]; } Arrays.sort( sorted_keys ); Integer[] setarray = set.toArray( new Integer[set.size()] ); Arrays.sort( setarray ); assertTrue( "expected: " + Arrays.toString( sorted_keys ) + ", was: " + Arrays.toString( setarray ), Arrays.equals( sorted_keys, setarray ) ); //noinspection ToArrayCallWithZeroLengthArrayArgument setarray = set.toArray( new Integer[0] ); Arrays.sort( setarray ); assertTrue( "expected: " + Arrays.toString( sorted_keys ) + ", was: " + Arrays.toString( setarray ), Arrays.equals( sorted_keys, setarray ) ); assertFalse( "remove of element not in set succeded: " + set, set.remove( 1 ) ); assertEquals( keys.length, set.size() ); assertEquals( keys.length, map.size() ); assertTrue( "remove of element in set failed: " + set, set.remove( 42 ) ); assertEquals( keys.length - 1, set.size() ); assertEquals( keys.length - 1, map.size() ); try { set.add( 42 ); fail( "Expected UnsupportedOperationException" ); } catch ( UnsupportedOperationException ex ) { // Expected } } public void testKeySetContainsAll() { int[] keys = {1138, 42, 86, 99, 101, 727, 117}; long[] vals = new long[keys.length]; TIntLongMap raw_map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { vals[i] = keys[i] * 2; raw_map.put( keys[i], vals[i] ); } Map map = TDecorators.wrap( raw_map ); Set set = map.keySet(); assertEquals( map.size(), set.size() ); assertFalse( set.isEmpty() ); // test with a java.util.Map Set java_set = new HashSet(); for ( int key : keys ) { java_set.add( Integer.valueOf( key ) ); } assertTrue( set.containsAll( java_set ) ); java_set.add( Integer.valueOf( 12 ) ); assertFalse( set.containsAll( java_set ) ); java_set.remove( Integer.valueOf( 12 ) ); assertTrue( set.containsAll( java_set ) ); java_set.add( Long.valueOf( 12 ) ); assertFalse( set.containsAll( java_set ) ); } public void testKeySetAddAll() { int[] keys = {1138, 42, 86, 99, 101, 727, 117}; long[] vals = new long[keys.length]; TIntLongMap raw_map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { vals[i] = keys[i] * 2; raw_map.put( keys[i], vals[i] ); } Map map = TDecorators.wrap( raw_map ); Set set = map.keySet(); assertEquals( map.size(), set.size() ); assertFalse( set.isEmpty() ); // test with a java.util.Map Set java_set = new HashSet(); for ( int key : keys ) { java_set.add( Integer.valueOf( key ) ); } try { set.addAll( java_set ); fail( "Expected UnsupportedOperationException" ); } catch ( UnsupportedOperationException ex ) { // Expected } try { set.addAll( set ); fail( "Expected UnsupportedOperationException" ); } catch ( UnsupportedOperationException ex ) { // Expected } } public void testKeySetRetainAllCollection() { int[] keys = {1138, 42, 86, 99, 101, 727, 117}; long[] vals = new long[keys.length]; TIntLongMap raw_map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { vals[i] = keys[i] * 2; raw_map.put( keys[i], vals[i] ); } Map map = TDecorators.wrap( raw_map ); Set set = map.keySet(); assertEquals( map.size(), set.size() ); assertFalse( set.isEmpty() ); // test with a java.util.Map Set java_set = new HashSet(); for ( int key : keys ) { java_set.add( Integer.valueOf( key ) ); } assertFalse( set.retainAll( java_set ) ); assertEquals( keys.length, set.size() ); assertEquals( keys.length, map.size() ); for ( int key : keys ) { assertTrue( set.contains( key ) ); assertTrue( map.containsKey( key ) ); } java_set.remove( 42 ); assertTrue( "set should have been modified: " + set + ", java: " + java_set, set.retainAll( java_set ) ); assertEquals( keys.length - 1, set.size() ); assertEquals( keys.length - 1, map.size() ); //noinspection ForLoopReplaceableByForEach for ( int i = 0; i < keys.length; i++ ) { if ( keys[i] != 42 ) { assertTrue( set.contains( keys[i] ) ); assertTrue( map.containsKey( keys[i] ) ); } else { assertFalse( set.contains( keys[i] ) ); assertFalse( map.containsKey( keys[i] ) ); } } } public void testKeySetRemoveAllCollection() { int[] keys = {1138, 42, 86, 99, 101, 727, 117}; long[] vals = new long[keys.length]; TIntLongMap raw_map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { vals[i] = keys[i] * 2; raw_map.put( keys[i], vals[i] ); } Map map = TDecorators.wrap( raw_map ); Set set = map.keySet(); assertEquals( map.size(), set.size() ); assertFalse( set.isEmpty() ); // test with a java.util.Map Set java_set = new HashSet(); assertFalse( set.removeAll( java_set ) ); assertEquals( keys.length, set.size() ); assertEquals( keys.length, map.size() ); for ( int key : keys ) { assertTrue( set.contains( key ) ); assertTrue( map.containsKey( key ) ); } for ( int key : keys ) { java_set.add( Integer.valueOf( key ) ); } java_set.remove( 42 ); assertTrue( "set should have been modified: " + set + ", java: " + java_set, set.removeAll( java_set ) ); assertEquals( "set: " + set, 1, set.size() ); assertEquals( "set: " + set, 1, map.size() ); //noinspection ForLoopReplaceableByForEach for ( int i = 0; i < keys.length; i++ ) { if ( keys[i] == 42 ) { assertTrue( set.contains( keys[i] ) ); assertTrue( map.containsKey( keys[i] ) ); } else { assertFalse( set.contains( keys[i] ) ); assertFalse( map.containsKey( keys[i] ) ); } } } public void testKeySetEquals() { int[] keys = {1138, 42, 86, 99, 101, 727, 117}; Integer[] integer_keys = new Integer[keys.length]; long[] vals = new long[keys.length]; TIntLongMap raw_map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { integer_keys[i] = Integer.valueOf( keys[i] ); vals[i] = keys[i] * 2; raw_map.put( keys[i], vals[i] ); } Map map = TDecorators.wrap( raw_map ); Set set = map.keySet(); assertEquals( map.size(), set.size() ); assertFalse( set.isEmpty() ); Set other = new HashSet(); other.addAll( Arrays.asList( integer_keys ) ); assertTrue( "sets incorrectly not equal: " + set + ", " + other, set.equals( other ) ); Integer[] mismatched = {72, 49, 53, 1024, 999}; Set unequal = new HashSet(); unequal.addAll( Arrays.asList( mismatched ) ); assertFalse( "sets incorrectly equal: " + set + ", " + unequal, set.equals( unequal ) ); // Change length, different code branch unequal.add( 1 ); assertFalse( "sets incorrectly equal: " + set + ", " + unequal, set.equals( unequal ) ); assertFalse( "set incorrectly equals a random object", set.equals( new Object() ) ); } public void testKeySetHashCode() { int[] keys = {1138, 42, 86, 99, 101, 727, 117}; Integer[] integer_keys = new Integer[keys.length]; long[] vals = new long[keys.length]; TIntLongMap raw_map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { integer_keys[i] = Integer.valueOf( keys[i] ); vals[i] = keys[i] * 2; raw_map.put( keys[i], vals[i] ); } Map map = TDecorators.wrap( raw_map ); Set set = map.keySet(); assertEquals( map.size(), set.size() ); assertFalse( set.isEmpty() ); Set other = new HashSet(); other.addAll( Arrays.asList( integer_keys ) ); assertTrue( "hashcodes incorrectly not equal: " + set + ", " + other, set.hashCode() == other.hashCode() ); } public void testKeySetIterator() { int[] keys = {1138, 42, 86, 99, 101, 727, 117}; Integer[] integer_keys = new Integer[keys.length]; long[] vals = new long[keys.length]; TIntLongMap raw_map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { integer_keys[i] = Integer.valueOf( keys[i] ); vals[i] = keys[i] * 2; raw_map.put( keys[i], vals[i] ); } Map map = TDecorators.wrap( raw_map ); List list = Arrays.asList( integer_keys ); Set set = map.keySet(); // test basic iterator function. Iterator iter = set.iterator(); while ( iter.hasNext() ) { int key = iter.next(); assertTrue( "key set should only contain keys: " + key + ", set; " + set, list.contains( key ) ); } assertFalse( iter.hasNext() ); try { iter.next(); fail( "Expect NoSuchElementException" ); } catch ( NoSuchElementException ex ) { // Expected. } // Start over with new iterator -- test iter.remove() iter = set.iterator(); while ( iter.hasNext() ) { int key = iter.next(); assertTrue( "key set should only contain keys: " + key + ", set; " + set, list.contains( key ) ); if ( key == keys[3] ) { iter.remove(); assertFalse( "set contains removed element: " + key + ", set: " + set, set.contains( key ) ); } } assertEquals( map.size(), set.size() ); assertEquals( keys.length - 1, map.size() ); assertNull( map.get( keys[3] ) ); } @SuppressWarnings({"ToArrayCallWithZeroLengthArrayArgument"}) public void testKeys() { TIntLongMap raw_map = new TIntLongHashMap(); Map map = TDecorators.wrap( raw_map ); map.put( KEY_ONE, Long.valueOf( 10 ) ); map.put( KEY_TWO, Long.valueOf( 20 ) ); assertEquals( 2, map.size() ); Integer[] keys = map.keySet().toArray( new Integer[map.size()] ); assertEquals( 2, keys.length ); List keys_list = Arrays.asList( keys ); assertTrue( keys_list.contains( KEY_ONE ) ); assertTrue( keys_list.contains( KEY_TWO ) ); //noinspection ToArrayCallWithZeroLengthArrayArgument Integer[] keys2 = map.keySet().toArray( new Integer[0] ); assertEquals( 2, keys2.length ); List keys_list2 = Arrays.asList( keys2 ); assertTrue( keys_list2.contains( KEY_ONE ) ); assertTrue( keys_list2.contains( KEY_TWO ) ); int element_count = 20; raw_map = new TIntLongHashMap( element_count, 0.5f, Integer.MIN_VALUE, Long.MIN_VALUE ); map = TDecorators.wrap( raw_map ); for ( int i = 0; i < element_count; i++ ) { map.put( Integer.valueOf( i ), Long.valueOf( i * i ) ); } assertEquals( element_count, map.size() ); keys = map.keySet().toArray( new Integer[0] ); Arrays.sort( keys ); assertEquals( element_count, keys.length ); for ( int i = 0; i < element_count; i++ ) { assertEquals( "expected: " + i + " got: " + keys[i] + ", i: " + i + ", keys: " + Arrays.toString( keys ), Integer.valueOf( i ), keys[i] ); assertEquals( Long.valueOf( i * i ), map.get( keys[i] ) ); } } public void testValueCollectionMisc() { int[] keys = {1138, 42, 86, 99, 101, 727, 117}; Long[] vals = new Long[keys.length]; TIntLongMap raw_map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { vals[i] = Long.valueOf( keys[i] * 2 ); raw_map.put( keys[i], vals[i] ); } Map map = TDecorators.wrap( raw_map ); Collection values = map.values(); Long[] sorted_values = new Long[keys.length]; for ( int i = 0; i < keys.length; i++ ) { sorted_values[i] = Long.valueOf( vals[i] ); } Arrays.sort( sorted_values ); Long[] setarray = values.toArray( new Long[values.size()] ); Arrays.sort( setarray ); assertTrue( "expected: " + Arrays.toString( sorted_values ) + ", was: " + Arrays.toString( setarray ), Arrays.equals( sorted_values, setarray ) ); setarray = values.toArray( new Long[values.size()] ); Arrays.sort( setarray ); assertTrue( "expected: " + Arrays.toString( sorted_values ) + ", was: " + Arrays.toString( setarray ), Arrays.equals( sorted_values, setarray ) ); assertFalse( "remove of element not in collection succeded: " + values, values.remove( Long.valueOf( 1 ) ) ); assertEquals( keys.length, values.size() ); assertEquals( keys.length, map.size() ); assertTrue( "remove of element in collection failed: " + values, values.remove( Long.valueOf( 42 * 2 ) ) ); assertEquals( keys.length - 1, values.size() ); assertEquals( keys.length - 1, map.size() ); try { values.add( Long.valueOf( 42 ) ); fail( "Expected UnsupportedOperationException" ); } catch ( UnsupportedOperationException ex ) { // Expected } } public void testValueCollectionContainsAll() { int[] keys = {1138, 42, 86, 99, 101, 727, 117}; long[] vals = new long[keys.length]; TIntLongMap raw_map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { vals[i] = keys[i] * 2; raw_map.put( keys[i], vals[i] ); } Map map = TDecorators.wrap( raw_map ); Collection values = map.values(); assertEquals( map.size(), values.size() ); assertFalse( values.isEmpty() ); // test with a java.util.Map Set java_set = new HashSet(); for ( long val : vals ) { java_set.add( Long.valueOf( val ) ); } assertTrue( values.containsAll( java_set ) ); java_set.add( Integer.valueOf( 12 ) ); assertFalse( values.containsAll( java_set ) ); java_set.remove( Integer.valueOf( 12 ) ); assertTrue( values.containsAll( java_set ) ); java_set.add( Long.valueOf( 12 ) ); assertFalse( values.containsAll( java_set ) ); } public void testValueCollectionAddAll() { int[] keys = {1138, 42, 86, 99, 101, 727, 117}; long[] vals = new long[keys.length]; TIntLongMap raw_map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { vals[i] = keys[i] * 2; raw_map.put( keys[i], vals[i] ); } Map map = TDecorators.wrap( raw_map ); Collection values = map.values(); assertEquals( map.size(), values.size() ); assertFalse( values.isEmpty() ); // test with a java.util.Map Set java_set = new HashSet(); for ( long val : vals ) { java_set.add( Long.valueOf( val ) ); } try { values.addAll( java_set ); fail( "Expected UnsupportedOperationException" ); } catch ( UnsupportedOperationException ex ) { // Expected } try { values.addAll( values ); fail( "Expected UnsupportedOperationException" ); } catch ( UnsupportedOperationException ex ) { // Expected } } public void testValueCollectionRetainAllCollection() { int[] keys = {1138, 42, 86, 99, 101, 727, 117}; long[] vals = new long[keys.length]; TIntLongMap raw_map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { vals[i] = keys[i] * 2; raw_map.put( keys[i], vals[i] ); } Map map = TDecorators.wrap( raw_map ); Collection values = map.values(); assertEquals( map.size(), values.size() ); assertFalse( values.isEmpty() ); // test with a java.util.Map Set java_set = new HashSet(); for ( long val : vals ) { java_set.add( Long.valueOf( val ) ); } assertFalse( values.retainAll( java_set ) ); assertEquals( keys.length, values.size() ); assertEquals( keys.length, map.size() ); for ( int i = 0; i < keys.length; i++ ) { assertTrue( values.contains( vals[i] ) ); assertTrue( map.containsValue( vals[i] ) ); } java_set.remove( Long.valueOf( 42 * 2 ) ); assertTrue( "collection should have been modified: " + values + "\njava: " + java_set, values.retainAll( java_set ) ); assertEquals( keys.length - 1, values.size() ); assertEquals( keys.length - 1, map.size() ); for ( int i = 0; i < keys.length; i++ ) { if ( keys[i] != 42 ) { assertTrue( values.contains( vals[i] ) ); assertTrue( map.containsValue( vals[i] ) ); } else { assertFalse( values.contains( vals[i] ) ); assertFalse( map.containsValue( vals[i] ) ); } } } public void testValueCollectionRemoveAllCollection() { int[] keys = {1138, 42, 86, 99, 101, 727, 117}; long[] vals = new long[keys.length]; TIntLongMap raw_map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { vals[i] = keys[i] * 2; raw_map.put( keys[i], vals[i] ); } Map map = TDecorators.wrap( raw_map ); Collection values = map.values(); assertEquals( map.size(), values.size() ); assertFalse( values.isEmpty() ); // test with a java.util.Map Set java_set = new HashSet(); assertFalse( values.removeAll( java_set ) ); assertEquals( vals.length, values.size() ); assertEquals( vals.length, map.size() ); for ( int i = 0; i < keys.length; i++ ) { assertTrue( values.contains( vals[i] ) ); assertTrue( map.containsValue( vals[i] ) ); } for ( long val : vals ) { java_set.add( Long.valueOf( val ) ); } java_set.remove( Long.valueOf( 42 * 2 ) ); assertTrue( "values should have been modified: " + values + ", java: " + java_set, values.removeAll( java_set ) ); assertEquals( "set: " + values, 1, values.size() ); assertEquals( "set: " + values, 1, map.size() ); //noinspection ForLoopReplaceableByForEach for ( int i = 0; i < vals.length; i++ ) { if ( vals[i] == 42 * 2 ) { assertTrue( values.contains( vals[i] ) ); assertTrue( map.containsValue( vals[i] ) ); } else { assertFalse( values.contains( vals[i] ) ); assertFalse( map.containsValue( vals[i] ) ); } } } public void testValueCollectionIterator() { int[] keys = {1138, 42, 86, 99, 101, 727, 117}; Long[] vals = new Long[keys.length]; TIntLongMap raw_map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { vals[i] = Long.valueOf( keys[i] * 2 ); raw_map.put( keys[i], vals[i] ); } Map map = TDecorators.wrap( raw_map ); List list = Arrays.asList( vals ); Collection set = map.values(); // test basic iterator function. Iterator iter = set.iterator(); while ( iter.hasNext() ) { long val = iter.next(); assertTrue( "value collection should only contain values: " + val + ", set; " + set, list.contains( val ) ); } assertFalse( iter.hasNext() ); try { iter.next(); fail( "Expect NoSuchElementException" ); } catch ( NoSuchElementException ex ) { // Expected. } // Start over with new iterator -- test iter.remove() iter = set.iterator(); while ( iter.hasNext() ) { long val = iter.next(); assertTrue( "value collection should only contain values: " + val + ", set; " + set, list.contains( val ) ); if ( val == vals[3] ) { iter.remove(); assertFalse( "set contains removed element: " + val + ", set: " + set, set.contains( val ) ); } } assertEquals( map.size(), set.size() ); assertEquals( keys.length - 1, map.size() ); assertNull( map.get( keys[3] ) ); } public void testValues() { TIntLongMap raw_map = new TIntLongHashMap(); Map map = TDecorators.wrap( raw_map ); map.put( KEY_ONE, Long.valueOf( 1 ) ); map.put( KEY_TWO, Long.valueOf( 2 ) ); assertEquals( 2, map.size() ); Long[] values = map.values().toArray( new Long[map.size()] ); assertEquals( 2, values.length ); List values_list = Arrays.asList( values ); assertTrue( values_list.contains( Long.valueOf( 1 ) ) ); assertTrue( values_list.contains( Long.valueOf( 2 ) ) ); Long[] values2 = map.values().toArray( new Long[map.size()] ); assertEquals( 2, values2.length ); List keys_list2 = Arrays.asList( values2 ); assertTrue( keys_list2.contains( Long.valueOf( 1 ) ) ); assertTrue( keys_list2.contains( Long.valueOf( 2 ) ) ); int element_count = 20; raw_map = new TIntLongHashMap( 20, 0.5f, Integer.MIN_VALUE, Long.MIN_VALUE ); map = TDecorators.wrap( raw_map ); for ( int i = 0; i < element_count; i++ ) { map.put( i, Long.valueOf( i * i ) ); } assertEquals( element_count, map.size() ); Long[] vals = map.values().toArray( new Long[map.size()] ); Arrays.sort( vals ); assertEquals( element_count, vals.length ); for ( int i = 0; i < element_count; i++ ) { assertEquals( "expected: " + i * i + " got: " + vals[i] + ", i: " + i + ", vals: " + Arrays.toString( vals ), Long.valueOf( i * i ), vals[i] ); assertEquals( Long.valueOf( i * i ), map.get( i ) ); } } public void testEntrySet() { int element_count = 20; Integer[] keys = new Integer[element_count]; Long[] vals = new Long[element_count]; TIntLongMap raw_map = new TIntLongHashMap( element_count, 0.5f, Integer.MIN_VALUE, Long.MIN_VALUE ); Map map = TDecorators.wrap( raw_map ); for ( int i = 0; i < element_count; i++ ) { keys[i] = Integer.valueOf( i + 1 ); vals[i] = Long.valueOf( i + 1 ); map.put( keys[i], vals[i] ); } assertEquals( element_count, map.size() ); Set> entries = map.entrySet(); assertEquals( element_count, entries.size() ); assertFalse( entries.isEmpty() ); //noinspection unchecked Map.Entry[] array = entries.toArray( new Map.Entry[entries.size()] ); for ( Map.Entry entry : array ) { assertTrue( entries.contains( entry ) ); } assertFalse( entries.contains( null ) ); assertEquals( array[0].hashCode(), array[0].hashCode() ); assertTrue( array[0].hashCode() != array[1].hashCode() ); assertTrue( array[0].equals( array[0] ) ); assertFalse( array[0].equals( array[1] ) ); Integer key = array[0].getKey(); Long old_value = Long.valueOf( array[0].getValue() ); assertEquals( Long.valueOf( old_value ), array[0].setValue( Long.valueOf( old_value * 2 ) ) ); assertEquals( Long.valueOf( old_value * 2 ), map.get( key ) ); assertEquals( Long.valueOf( old_value * 2 ), array[0].getValue() ); // Adds are not allowed Map.Entry invalid_entry = new Map.Entry() { public Integer getKey() { return null; } public Long getValue() { return null; } public Long setValue( Long value ) { return null; } }; List> invalid_entry_list = new ArrayList>(); invalid_entry_list.add( invalid_entry ); try { entries.add( invalid_entry ); fail( "Expected OperationUnsupportedException" ); } catch ( UnsupportedOperationException ex ) { // Expected } try { entries.addAll( invalid_entry_list ); fail( "Expected OperationUnsupportedException" ); } catch ( UnsupportedOperationException ex ) { // Expected } assertFalse( entries.containsAll( invalid_entry_list ) ); assertFalse( entries.removeAll( invalid_entry_list ) ); List> partial_list = new ArrayList>(); partial_list.add( array[3] ); partial_list.add( array[4] ); assertTrue( entries.removeAll( partial_list ) ); assertEquals( element_count - 2, entries.size() ); assertEquals( element_count - 2, map.size() ); entries.clear(); assertTrue( entries.isEmpty() ); assertTrue( map.isEmpty() ); } public void testEquals() { int[] keys = {1138, 42, 86, 99, 101, 727, 117}; long[] vals = new long[keys.length]; TIntLongMap raw_map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { vals[i] = keys[i] * 2; raw_map.put( keys[i], vals[i] ); } Map map = TDecorators.wrap( raw_map ); assertEquals( map, map ); TIntIntMap raw_int_map = new TIntIntHashMap(); for ( int i = 0; i < keys.length; i++ ) { raw_int_map.put( keys[i], (int) vals[i] ); } Map int_map = TDecorators.wrap( raw_int_map ); assertFalse( map.equals( int_map ) ); // Change a value.. TIntLongMap raw_unequal = new TIntLongHashMap( raw_map ); Map unequal = TDecorators.wrap( raw_unequal ); map.put( keys[3], vals[3] + 1 ); assertFalse( map.equals( unequal ) ); // Change length raw_unequal = new TIntLongHashMap( raw_map ); unequal = TDecorators.wrap( raw_unequal ); map.put( 13, Long.valueOf( 26 ) ); assertFalse( map.equals( unequal ) ); } public void testHashCode() { int[] keys = {1138, 42, 86, 99, 101, 727, 117}; long[] vals = new long[keys.length]; TIntLongMap raw_map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { vals[i] = keys[i] * 2; raw_map.put( keys[i], vals[i] ); } Map map = TDecorators.wrap( raw_map ); TIntLongMap raw_other = new TIntLongHashMap(); Map other = TDecorators.wrap( raw_other ); other.putAll( map ); assertTrue( "hashcodes incorrectly not equal: " + map + ", " + other, map.hashCode() == other.hashCode() ); TIntLongMap raw_unequal = new TIntLongHashMap(); for ( int key : keys ) { raw_unequal.put( key, key ); } Map unequal = TDecorators.wrap( raw_unequal ); assertFalse( "hashcodes unlikely equal: " + map + ", " + unequal, map.hashCode() == unequal.hashCode() ); int[] raw_mismatched = {72, 49, 53, 1024, 999}; TIntLongMap raw_mismatched_map = new TIntLongHashMap(); for ( int aRaw_mismatched : raw_mismatched ) { raw_mismatched_map.put( aRaw_mismatched, Long.valueOf( aRaw_mismatched * 37 ) ); } Map mismatched = TDecorators.wrap( raw_mismatched_map ); assertFalse( "hashcodes unlikely equal: " + map + ", " + mismatched, map.hashCode() == mismatched.hashCode() ); } public void testToString() { TIntLongMap raw_map = new TIntLongHashMap(); Map map = TDecorators.wrap( raw_map ); map.put( 11, Long.valueOf( 1 ) ); map.put( 22, Long.valueOf( 2 ) ); String to_string = map.toString(); assertTrue( to_string, to_string.equals( "{11=1, 22=2}" ) || to_string.equals( "{22=2, 11=1}" ) ); } public void testSerialize() throws Exception { int[] keys = {1138, 42, 86, 99, 101, 727, 117}; long[] vals = new long[keys.length]; TIntLongMap raw_map = new TIntLongHashMap(); for ( int i = 0; i < keys.length; i++ ) { vals[i] = keys[i] * 2; raw_map.put( keys[i], vals[i] ); } Map map = TDecorators.wrap( raw_map ); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream( baos ); oos.writeObject( map ); ByteArrayInputStream bias = new ByteArrayInputStream( baos.toByteArray() ); ObjectInputStream ois = new ObjectInputStream( bias ); //noinspection unchecked Map deserialized = (Map) ois.readObject(); assertEquals( map, deserialized ); } public void testBug3432212A() throws Exception { Map trove = new TIntLongMapDecorator(new TIntLongHashMap()); trove.put(null, 1L); assertFalse(trove.isEmpty()); assertEquals(1, trove.size()); assertEquals(1, trove.entrySet().size()); assertEquals(1, trove.keySet().size()); assertEquals(null, trove.keySet().iterator().next()); } public void testBug3432212B() throws Exception { Map trove = new TIntLongMapDecorator(new TIntLongHashMap()); trove.put(1, null); assertFalse(trove.isEmpty()); assertEquals(1, trove.size()); assertEquals(1, trove.entrySet().size()); assertEquals(1, trove.keySet().size()); assertEquals(null, trove.get(1)); assertEquals(null, trove.values().iterator().next()); } } trove-3.0.3/test/gnu/trove/decorator/TPrimitiveObjectMapDecoratorTest.java0000644000175000017500000011304511763017634025756 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2002, Eric D. Friedman All Rights Reserved. // Copyright (c) 2009, Robert D. Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.decorator; import gnu.trove.map.TIntObjectMap; import gnu.trove.map.hash.TIntObjectHashMap; import gnu.trove.TDecorators; import gnu.trove.set.TIntSet; import gnu.trove.set.hash.TIntHashSet; import junit.framework.TestCase; import java.io.ByteArrayOutputStream; import java.io.ObjectOutputStream; import java.io.ByteArrayInputStream; import java.io.ObjectInputStream; import java.util.*; /** * Test the primitive key/Object value map decorators * * @author Eric D. Friedman * @author Robert D. Eden * @author Jeff Randall */ public class TPrimitiveObjectMapDecoratorTest extends TestCase { public TPrimitiveObjectMapDecoratorTest(String name) { super(name); } public void testConstructors() { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; TIntObjectMap raw_map = new TIntObjectHashMap(); for (int i = 0; i < element_count; i++) { keys[i] = i + 1; vals[i] = Integer.toString(i + 1); raw_map.put(keys[i], vals[i]); } Map map = TDecorators.wrap(raw_map); TIntObjectMap raw_capacity = new TIntObjectHashMap(20); for (int i = 0; i < element_count; i++) { raw_capacity.put(keys[i], vals[i]); } Map capacity = TDecorators.wrap(raw_capacity); assertEquals(map, capacity); TIntObjectMap raw_cap_and_factor = new TIntObjectHashMap(20, 0.75f); for (int i = 0; i < element_count; i++) { raw_cap_and_factor.put(keys[i], vals[i]); } Map cap_and_factor = TDecorators.wrap(raw_cap_and_factor); assertEquals(map, cap_and_factor); TIntObjectMap raw_fully_specified = new TIntObjectHashMap(20, 0.75f, Integer.MIN_VALUE); for (int i = 0; i < element_count; i++) { raw_fully_specified.put(keys[i], vals[i]); } Map fully_specified = TDecorators.wrap(raw_fully_specified); assertEquals(map, fully_specified); TIntObjectMap raw_copy = new TIntObjectHashMap(raw_map); Map copy = TDecorators.wrap(raw_copy); assertEquals(map, copy); } public void testGet() { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; TIntObjectMap raw_map = new TIntObjectHashMap(); for (int i = 0; i < element_count; i++) { keys[i] = i + 1; vals[i] = Integer.toString(i + 1); raw_map.put(keys[i], vals[i]); } Map map = TDecorators.wrap(raw_map); assertEquals(vals[10], map.get(Integer.valueOf(keys[10]))); assertNull(map.get(Integer.valueOf(1138))); Integer key = Integer.valueOf(1138); map.put(key, null); assertTrue(map.containsKey(key)); assertNull(map.get(key)); Long long_key = Long.valueOf(1138); //noinspection SuspiciousMethodCalls assertNull(map.get(long_key)); map.put(null, "null-key"); assertEquals("null-key", map.get(null)); } public void testContainsKey() { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; TIntObjectMap raw_map = new TIntObjectHashMap(); for (int i = 0; i < element_count; i++) { keys[i] = i + 1; vals[i] = Integer.toString(i + 1); raw_map.put(keys[i], vals[i]); } Map map = TDecorators.wrap(raw_map); for (int i = 0; i < element_count; i++) { assertTrue("Key should be present: " + keys[i] + ", map: " + map, map.containsKey(keys[i])); } int key = 1138; assertFalse("Key should not be present: " + key + ", map: " + map, map.containsKey(key)); } public void testContainsValue() { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; TIntObjectMap raw_map = new TIntObjectHashMap(); for (int i = 0; i < element_count; i++) { keys[i] = i + 1; vals[i] = Integer.toString(i + 1); raw_map.put(keys[i], vals[i]); } Map map = TDecorators.wrap(raw_map); for (int i = 0; i < element_count; i++) { assertTrue("Value should be present: " + vals[i] + ", map: " + map, map.containsValue(vals[i])); } String val = "1138"; assertFalse("Key should not be present: " + val + ", map: " + map, map.containsValue(val)); //noinspection SuspiciousMethodCalls assertFalse("Random object should not be present in map: " + map, map.containsValue(new Object())); } public void testRemove() { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; TIntObjectMap raw_map = new TIntObjectHashMap(); for (int i = 0; i < element_count; i++) { keys[i] = i + 1; vals[i] = Integer.toString(i + 1); raw_map.put(keys[i], vals[i]); } Map map = TDecorators.wrap(raw_map); for (int i = 0; i < element_count; i++) { if (i % 2 == 1) { assertEquals("Remove should have modified map: " + keys[i] + ", map: " + map, vals[i], map.remove(keys[i])); } } for (int i = 0; i < element_count; i++) { if (i % 2 == 1) { assertTrue("Removed key still in map: " + keys[i] + ", map: " + map, map.get(keys[i]) == null); } else { assertTrue("Key should still be in map: " + keys[i] + ", map: " + map, map.get(keys[i]).equals(vals[i])); } } assertNull(map.get(1138)); //noinspection SuspiciousMethodCalls assertNull(map.get(Integer.valueOf(1138))); assertNull(map.get(null)); map.put(null, "null-value"); assertEquals("null-value", raw_map.get(raw_map.getNoEntryKey())); assertTrue(map.containsKey(null)); String value = map.get(null); assertEquals("value: " + value, "null-value", value); assertEquals("null-value", map.remove(null)); assertFalse(map.containsKey(null)); //noinspection SuspiciousMethodCalls assertNull(map.remove(Long.valueOf(1138))); } public void testPutAllMap() { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; TIntObjectMap raw_control = new TIntObjectHashMap(); for (int i = 0; i < element_count; i++) { keys[i] = i + 1; vals[i] = Integer.toString(i + 1); raw_control.put(keys[i], vals[i]); } Map control = TDecorators.wrap(raw_control); TIntObjectMap raw_map = new TIntObjectHashMap(); Map map = TDecorators.wrap(raw_map); Map source = new HashMap(); for (int i = 0; i < element_count; i++) { source.put(keys[i], vals[i]); } map.putAll(source); assertEquals(control, map); } public void testPutAll() throws Exception { TIntObjectMap raw_t = new TIntObjectHashMap(); Map t = TDecorators.wrap(raw_t); TIntObjectMap raw_m = new TIntObjectHashMap(); Map m = TDecorators.wrap(raw_m); m.put(2, "one"); m.put(4, "two"); m.put(6, "three"); t.put(5, "four"); assertEquals(1, t.size()); t.putAll(m); assertEquals(4, t.size()); assertEquals("two", t.get(4)); } public void testClear() { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; TIntObjectMap raw_map = new TIntObjectHashMap(); for (int i = 0; i < element_count; i++) { keys[i] = i + 1; vals[i] = Integer.toString(i + 1); raw_map.put(keys[i], vals[i]); } Map map = TDecorators.wrap(raw_map); assertEquals(element_count, map.size()); map.clear(); assertTrue(map.isEmpty()); assertEquals(0, map.size()); assertNull(map.get(keys[5])); } @SuppressWarnings({"ToArrayCallWithZeroLengthArrayArgument"}) public void testKeySet() { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; TIntObjectMap raw_map = new TIntObjectHashMap(); for (int i = 0; i < element_count; i++) { keys[i] = i + 1; vals[i] = Integer.toString(i + 1); raw_map.put(keys[i], vals[i]); } Map map = TDecorators.wrap(raw_map); assertEquals(element_count, map.size()); Set keyset = map.keySet(); for (int i = 0; i < keyset.size(); i++) { assertTrue(keyset.contains(keys[i])); } assertFalse(keyset.isEmpty()); Object[] keys_object_array = keyset.toArray(); int count = 0; Iterator iter = keyset.iterator(); while (iter.hasNext()) { int key = iter.next(); assertTrue(keyset.contains(key)); assertEquals(keys_object_array[count], key); count++; } Integer[] keys_array = keyset.toArray(new Integer[0]); count = 0; iter = keyset.iterator(); while (iter.hasNext()) { Integer key = iter.next(); assertTrue(keyset.contains(key)); assertEquals(keys_array[count], key); count++; } keys_array = keyset.toArray(new Integer[keyset.size()]); count = 0; iter = keyset.iterator(); while (iter.hasNext()) { Integer key = iter.next(); assertTrue(keyset.contains(key)); assertEquals(keys_array[count], key); count++; } keys_array = keyset.toArray(new Integer[keyset.size() * 2]); count = 0; iter = keyset.iterator(); while (iter.hasNext()) { Integer key = iter.next(); assertTrue(keyset.contains(key)); assertEquals(keys_array[count], key); count++; } assertNull(keys_array[keyset.size()]); TIntSet raw_other = new TIntHashSet(keyset); Set other = TDecorators.wrap(raw_other); assertFalse(keyset.retainAll(other)); other.remove(keys[5]); assertTrue(keyset.retainAll(other)); assertFalse(keyset.contains(keys[5])); assertFalse(map.containsKey(keys[5])); keyset.clear(); assertTrue(keyset.isEmpty()); } public void testKeySetAdds() { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; TIntObjectMap raw_map = new TIntObjectHashMap(); for (int i = 0; i < element_count; i++) { keys[i] = i + 1; vals[i] = Integer.toString(i + 1); raw_map.put(keys[i], vals[i]); } Map map = TDecorators.wrap(raw_map); assertEquals(element_count, map.size()); Set keyset = map.keySet(); for (int i = 0; i < keyset.size(); i++) { assertTrue(keyset.contains(keys[i])); } assertFalse(keyset.isEmpty()); try { keyset.add(1138); fail("Expected UnsupportedOperationException"); } catch (UnsupportedOperationException ex) { // Expected } try { Set test = new HashSet(); test.add(Integer.valueOf(1138)); keyset.addAll(test); fail("Expected UnsupportedOperationException"); } catch (UnsupportedOperationException ex) { // Expected } try { Set test = new HashSet(); test.add(1138); keyset.addAll(test); fail("Expected UnsupportedOperationException"); } catch (UnsupportedOperationException ex) { // Expected } } @SuppressWarnings({"ToArrayCallWithZeroLengthArrayArgument"}) public void testKeys() { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; TIntObjectMap raw_map = new TIntObjectHashMap(); for (int i = 0; i < element_count; i++) { keys[i] = i + 1; vals[i] = Integer.toString(i + 1); raw_map.put(keys[i], vals[i]); } Map map = TDecorators.wrap(raw_map); assertEquals(element_count, map.size()); // No argument Integer[] keys_array = map.keySet().toArray(new Integer[map.size()]); assertEquals(element_count, keys_array.length); List keys_list = Arrays.asList(keys_array); for (int i = 0; i < element_count; i++) { assertTrue(keys_list.contains(keys[i])); } // Zero length array //noinspection ToArrayCallWithZeroLengthArrayArgument keys_array = map.keySet().toArray(new Integer[0]); assertEquals(element_count, keys_array.length); keys_list = Arrays.asList(keys_array); for (int i = 0; i < element_count; i++) { assertTrue(keys_list.contains(keys[i])); } // appropriate length array keys_array = map.keySet().toArray(new Integer[map.size()]); assertEquals(element_count, keys_array.length); keys_list = Arrays.asList(keys_array); for (int i = 0; i < element_count; i++) { assertTrue(keys_list.contains(keys[i])); } // longer array keys_array = map.keySet().toArray(new Integer[element_count * 2]); assertEquals(element_count * 2, keys_array.length); keys_list = Arrays.asList(keys_array); for (int i = 0; i < element_count; i++) { assertTrue(keys_list.contains(keys[i])); } assertNull(keys_array[element_count]); } public void testValueCollectionToArray() { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; TIntObjectMap raw_map = new TIntObjectHashMap(); for (int i = 0; i < element_count; i++) { keys[i] = i + 1; vals[i] = Integer.toString(i + 1); raw_map.put(keys[i], vals[i]); } Map map = TDecorators.wrap(raw_map); assertEquals(element_count, map.size()); Collection collection = map.values(); for (int i = 0; i < collection.size(); i++) { assertTrue(collection.contains(vals[i])); } assertFalse(collection.isEmpty()); Object[] values_obj_array = collection.toArray(); int count = 0; Iterator iter = collection.iterator(); while (iter.hasNext()) { String value = iter.next(); assertTrue(collection.contains(value)); assertEquals(values_obj_array[count], value); count++; } //noinspection ToArrayCallWithZeroLengthArrayArgument String[] values_array = collection.toArray(new String[0]); count = 0; iter = collection.iterator(); while (iter.hasNext()) { String value = iter.next(); assertTrue(collection.contains(value)); assertEquals(values_array[count], value); count++; } values_array = collection.toArray(new String[collection.size()]); count = 0; iter = collection.iterator(); while (iter.hasNext()) { String value = iter.next(); assertTrue(collection.contains(value)); assertEquals(values_array[count], value); count++; } values_array = collection.toArray(new String[collection.size() * 2]); count = 0; iter = collection.iterator(); while (iter.hasNext()) { String value = iter.next(); assertTrue(collection.contains(value)); assertEquals(values_array[count], value); count++; } assertNull(values_array[collection.size()]); assertNull(values_array[collection.size()]); Collection other = new ArrayList(collection); assertFalse(collection.retainAll(other)); other.remove(vals[5]); assertTrue(collection.retainAll(other)); assertFalse(collection.contains(vals[5])); assertFalse(map.containsKey(keys[5])); collection.clear(); assertTrue(collection.isEmpty()); } public void testValueCollectionAdds() { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; TIntObjectMap raw_map = new TIntObjectHashMap(); for (int i = 0; i < element_count; i++) { keys[i] = i + 1; vals[i] = Integer.toString(i + 1); raw_map.put(keys[i], vals[i]); } Map map = TDecorators.wrap(raw_map); assertEquals(element_count, map.size()); Collection collection = map.values(); for (int i = 0; i < collection.size(); i++) { assertTrue(collection.contains(vals[i])); } assertFalse(collection.isEmpty()); try { collection.add("1138"); fail("Expected UnsupportedOperationException"); } catch (UnsupportedOperationException ex) { // Expected } try { Set test = new HashSet(); test.add("1138"); collection.addAll(test); fail("Expected UnsupportedOperationException"); } catch (UnsupportedOperationException ex) { // Expected } try { Collection test = new ArrayList(); test.add("1138"); collection.addAll(test); fail("Expected UnsupportedOperationException"); } catch (UnsupportedOperationException ex) { // Expected } try { collection.addAll(Arrays.asList(vals)); fail("Expected UnsupportedOperationException"); } catch (UnsupportedOperationException ex) { // Expected } } public void testValueCollectionContainsAll() { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; TIntObjectMap raw_map = new TIntObjectHashMap(); for (int i = 0; i < element_count; i++) { keys[i] = i + 1; vals[i] = Integer.toString(i + 1); raw_map.put(keys[i], vals[i]); } Map map = TDecorators.wrap(raw_map); assertEquals(element_count, map.size()); Collection collection = map.values(); for (int i = 0; i < collection.size(); i++) { assertTrue(collection.contains(vals[i])); } assertFalse(collection.isEmpty()); List java_list = new ArrayList(); java_list.addAll(Arrays.asList(vals)); assertTrue("collection: " + collection + ", should contain all in list: " + java_list, collection.containsAll(java_list)); java_list.add(String.valueOf(1138)); assertFalse("collection: " + collection + ", should not contain all in list: " + java_list, collection.containsAll(java_list)); List number_list = new ArrayList(); for (String value : vals) { if (value.equals("5")) { number_list.add(new StringBuilder().append(value)); } else { number_list.add(String.valueOf(value)); } } assertFalse("collection: " + collection + ", should not contain all in list: " + java_list, collection.containsAll(number_list)); Collection other = new ArrayList(collection); assertTrue("collection: " + collection + ", should contain all in other: " + other, collection.containsAll(other)); other.add("1138"); assertFalse("collection: " + collection + ", should not contain all in other: " + other, collection.containsAll(other)); } public void testValueCollectionRetainAllCollection() { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; TIntObjectMap raw_map = new TIntObjectHashMap(); for (int i = 0; i < element_count; i++) { keys[i] = i + 1; vals[i] = Integer.toString(i + 1); raw_map.put(keys[i], vals[i]); } Map map = TDecorators.wrap(raw_map); assertEquals(element_count, map.size()); Collection collection = map.values(); for (int i = 0; i < collection.size(); i++) { assertTrue(collection.contains(vals[i])); } assertFalse(collection.isEmpty()); List java_list = new ArrayList(); java_list.addAll(Arrays.asList(vals)); assertFalse("collection: " + collection + ", should contain all in list: " + java_list, collection.retainAll(java_list)); java_list.remove(5); assertTrue("collection: " + collection + ", should contain all in list: " + java_list, collection.retainAll(java_list)); assertFalse(collection.contains(vals[5])); assertFalse(map.containsKey(keys[5])); assertFalse(map.containsValue(vals[5])); assertTrue("collection: " + collection + ", should contain all in list: " + java_list, collection.containsAll(java_list)); } public void testValueCollectionRetainAllTCollection() { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; TIntObjectMap raw_map = new TIntObjectHashMap(); for (int i = 0; i < element_count; i++) { keys[i] = i + 1; vals[i] = Integer.toString(i + 1); raw_map.put(keys[i], vals[i]); } Map map = TDecorators.wrap(raw_map); assertEquals(element_count, map.size()); Collection collection = map.values(); for (int i = 0; i < collection.size(); i++) { assertTrue(collection.contains(vals[i])); } assertFalse(collection.isEmpty()); assertFalse("collection: " + collection + ", should be unmodified.", collection.retainAll(collection)); Collection other = new ArrayList(collection); assertFalse("collection: " + collection + ", should be unmodified. other: " + other, collection.retainAll(other)); other.remove(vals[5]); assertTrue("collection: " + collection + ", should be modified. other: " + other, collection.retainAll(other)); assertFalse(collection.contains(vals[5])); assertFalse(map.containsKey(keys[5])); assertFalse(map.containsValue(vals[5])); assertTrue("collection: " + collection + ", should contain all in other: " + other, collection.containsAll(other)); } public void testValueCollectionRemoveAllCollection() { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; TIntObjectMap raw_map = new TIntObjectHashMap(); for (int i = 0; i < element_count; i++) { keys[i] = i + 1; vals[i] = Integer.toString(i + 1); raw_map.put(keys[i], vals[i]); } Map map = TDecorators.wrap(raw_map); assertEquals(element_count, map.size()); Collection collection = map.values(); for (int i = 0; i < collection.size(); i++) { assertTrue(collection.contains(vals[i])); } assertFalse(collection.isEmpty()); List java_list = new ArrayList(); assertFalse("collection: " + collection + ", should contain all in list: " + java_list, collection.removeAll(java_list)); java_list.add(vals[5]); assertTrue("collection: " + collection + ", should contain all in list: " + java_list, collection.removeAll(java_list)); assertFalse(collection.contains(vals[5])); assertFalse(map.containsKey(keys[5])); assertFalse(map.containsValue(vals[5])); java_list = new ArrayList(); java_list.addAll(Arrays.asList(vals)); assertTrue("collection: " + collection + ", should contain all in list: " + java_list, collection.removeAll(java_list)); assertTrue(collection.isEmpty()); } public void testValueCollectionRemoveAllTCollection() { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; TIntObjectMap raw_map = new TIntObjectHashMap(); for (int i = 0; i < element_count; i++) { keys[i] = i + 1; vals[i] = Integer.toString(i + 1); raw_map.put(keys[i], vals[i]); } Map map = TDecorators.wrap(raw_map); assertEquals(element_count, map.size()); Collection collection = map.values(); for (int i = 0; i < collection.size(); i++) { assertTrue(collection.contains(vals[i])); } assertFalse(collection.isEmpty()); Collection other = new ArrayList(); assertFalse("collection: " + collection + ", should be unmodified.", collection.removeAll(other)); other = new ArrayList(collection); other.remove(vals[5]); assertTrue("collection: " + collection + ", should be modified. other: " + other, collection.removeAll(other)); assertEquals(1, collection.size()); for (int i = 0; i < element_count; i++) { if (i == 5) { assertTrue(collection.contains(vals[i])); assertTrue(map.containsKey(keys[i])); assertTrue(map.containsValue(vals[i])); } else { assertFalse(collection.contains(vals[i])); assertFalse(map.containsKey(keys[i])); assertFalse(map.containsValue(vals[i])); } } assertFalse("collection: " + collection + ", should be unmodified. other: " + other, collection.removeAll(other)); assertTrue("collection: " + collection + ", should be modified. other: " + other, collection.removeAll(collection)); assertTrue(collection.isEmpty()); } public void testValues() { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; TIntObjectMap raw_map = new TIntObjectHashMap(); for (int i = 0; i < element_count; i++) { keys[i] = i + 1; vals[i] = Integer.toString(i + 1); raw_map.put(keys[i], vals[i]); } Map map = TDecorators.wrap(raw_map); assertEquals(element_count, map.size()); // No argument Object[] values_object_array = map.values().toArray(); assertEquals(element_count, values_object_array.length); List values_object_list = Arrays.asList(values_object_array); for (int i = 0; i < element_count; i++) { assertTrue(values_object_list.contains(vals[i])); } // Zero length array //noinspection ToArrayCallWithZeroLengthArrayArgument String[] values_array = map.values().toArray(new String[0]); assertEquals(element_count, values_array.length); List values_list = Arrays.asList(values_array); for (int i = 0; i < element_count; i++) { assertTrue(values_list.contains(vals[i])); } // appropriate length array values_array = map.values().toArray(new String[map.size()]); assertEquals(element_count, values_array.length); values_list = Arrays.asList(values_array); for (int i = 0; i < element_count; i++) { assertTrue(values_list.contains(vals[i])); } // longer array values_array = map.values().toArray(new String[element_count * 2]); assertEquals(element_count * 2, values_array.length); values_list = Arrays.asList(values_array); for (int i = 0; i < element_count; i++) { assertTrue(values_list.contains(vals[i])); } assertEquals(null, values_array[element_count]); } public void testEntrySet() { int element_count = 20; Integer[] keys = new Integer[element_count]; String[] vals = new String[element_count]; TIntObjectMap raw_map = new TIntObjectHashMap(element_count, 0.5f, Integer.MIN_VALUE); Map map = TDecorators.wrap(raw_map); for (int i = 0; i < element_count; i++) { keys[i] = Integer.valueOf(i + 1); vals[i] = Integer.toString(i + 1); map.put(keys[i], vals[i]); } assertEquals(element_count, map.size()); Set> entries = map.entrySet(); assertEquals(element_count, entries.size()); assertFalse(entries.isEmpty()); //noinspection unchecked Map.Entry[] array = entries.toArray(new Map.Entry[entries.size()]); for (Map.Entry entry : array) { assertTrue(entries.contains(entry)); } assertFalse(entries.contains(null)); assertEquals(array[0].hashCode(), array[0].hashCode()); assertTrue(array[0].hashCode() != array[1].hashCode()); assertTrue(array[0].equals(array[0])); assertFalse(array[0].equals(array[1])); Integer key = array[0].getKey(); Integer old_value = Integer.valueOf(array[0].getValue()); assertEquals(Integer.toString(old_value), array[0].setValue(Integer.toString(old_value * 2))); assertEquals(Integer.toString(old_value * 2), map.get(key)); assertEquals(Integer.toString(old_value * 2), array[0].getValue()); // Adds are not allowed Map.Entry invalid_entry = new Map.Entry() { public Integer getKey() { return null; } public String getValue() { return null; } public String setValue(String value) { return null; } }; List> invalid_entry_list = new ArrayList>(); invalid_entry_list.add(invalid_entry); try { entries.add(invalid_entry); fail("Expected OperationUnsupportedException"); } catch (UnsupportedOperationException ex) { // Expected } try { entries.addAll(invalid_entry_list); fail("Expected OperationUnsupportedException"); } catch (UnsupportedOperationException ex) { // Expected } assertFalse(entries.containsAll(invalid_entry_list)); assertFalse(entries.removeAll(invalid_entry_list)); List> partial_list = new ArrayList>(); partial_list.add(array[3]); partial_list.add(array[4]); assertTrue(entries.removeAll(partial_list)); assertEquals(element_count - 2, entries.size()); assertEquals(element_count - 2, map.size()); entries.clear(); assertTrue(entries.isEmpty()); assertTrue(map.isEmpty()); } public void testEquals() { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; TIntObjectMap raw_map = new TIntObjectHashMap(element_count, 0.5f, Integer.MIN_VALUE); for (int i = 0; i < element_count; i++) { keys[i] = i + 1; vals[i] = Integer.toString(i + 1); raw_map.put(keys[i], vals[i]); } Map map = TDecorators.wrap(raw_map); assertEquals(element_count, map.size()); TIntObjectHashMap raw_fully_specified = new TIntObjectHashMap(20, 0.75f, Integer.MIN_VALUE); for (int i = 0; i < element_count; i++) { raw_fully_specified.put(keys[i], vals[i]); } Map fully_specified = TDecorators.wrap(raw_fully_specified); assertEquals(map, fully_specified); assertFalse("shouldn't equal random object", map.equals(new Object())); assertSame(raw_map, ((TIntObjectMapDecorator) map).getMap()); } @SuppressWarnings({"unchecked"}) public void testSerialize() throws Exception { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; TIntObjectMap raw_map = new TIntObjectHashMap(); for (int i = 0; i < element_count; i++) { keys[i] = i + 1; vals[i] = Integer.toString(i + 1); raw_map.put(keys[i], vals[i]); } Map map = TDecorators.wrap(raw_map); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(map); ByteArrayInputStream bias = new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bias); Map deserialized = (Map) ois.readObject(); assertEquals(map, deserialized); } public void testToString() { TIntObjectHashMap raw_map = new TIntObjectHashMap(); Map map = TDecorators.wrap(raw_map); map.put(11, "One"); map.put(22, "Two"); String to_string = map.toString(); assertTrue(to_string, to_string.equals("{11=One, 22=Two}") || to_string.equals("{22=Two, 11=One}")); } public void testBug3432175() throws Exception { Map trove = new TIntObjectMapDecorator(new TIntObjectHashMap()); trove.put(null, new Object()); assertFalse(trove.isEmpty()); assertEquals(1, trove.size()); assertEquals(1, trove.entrySet().size()); assertEquals(1, trove.keySet().size()); assertEquals(null, trove.keySet().iterator().next()); } } trove-3.0.3/test/gnu/trove/strategy/0000755000175000017500000000000012000515265016367 5ustar ericherichtrove-3.0.3/test/gnu/trove/strategy/IdentityHashingStrategyTest.java0000644000175000017500000000166711763017634024736 0ustar ericherichpackage gnu.trove.strategy; import gnu.trove.map.hash.TCustomHashMap; import junit.framework.TestCase; import java.util.Map; /** * */ public class IdentityHashingStrategyTest extends TestCase { public void testInMap() { Map map = new TCustomHashMap( new IdentityHashingStrategy() ); Integer first = new Integer( 0 ); Integer second = new Integer( 0 ); map.put( first, "first" ); assertEquals( 1, map.size() ); assertTrue( map.containsKey( first )); assertFalse( map.containsKey( second ) ); assertEquals( "first", map.get( first ) ); map.put( second, "second" ); assertEquals( 2, map.size() ); assertEquals( "first", map.get( first ) ); assertEquals( "second", map.get( second ) ); map.remove( first ); assertEquals( 1, map.size() ); assertFalse( map.containsKey( first ) ); assertTrue( map.containsKey( second ) ); } } trove-3.0.3/test/gnu/trove/list/0000755000175000017500000000000011763017634015514 5ustar ericherichtrove-3.0.3/test/gnu/trove/list/linked/0000755000175000017500000000000012000515265016746 5ustar ericherichtrove-3.0.3/test/gnu/trove/list/linked/TPrimitiveLinkedListTest.java0000644000175000017500000013343211763017634024552 0ustar ericherichpackage gnu.trove.list.linked; import gnu.trove.TIntCollection; import gnu.trove.function.TIntFunction; import gnu.trove.impl.Constants; import gnu.trove.iterator.TIntIterator; import gnu.trove.list.TIntList; import gnu.trove.procedure.TIntProcedure; import gnu.trove.set.TIntSet; import gnu.trove.set.hash.TIntHashSet; import junit.framework.TestCase; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.*; /** * Created by IntelliJ IDEA. * User: jparent * Date: 24/03/11 * Time: 12:27 * To change this template use File | Settings | File Templates. */ public class TPrimitiveLinkedListTest extends TestCase { private TIntList list; public void setUp() throws Exception { super.setUp(); list = new TIntLinkedList(); list.add( 1 ); list.add( 2 ); list.add( 3 ); list.add( 4 ); list.add(5); } public void tearDown() throws Exception { super.tearDown(); } public void testGet() { assertEquals( 4, list.get( 3 ) ); try { list.get( 10 ); fail( "Expected IndexOutOfBoundsException" ); } catch ( IndexOutOfBoundsException ex ) { // Expected } int element_count = 10; TIntLinkedList array_list = new TIntLinkedList(); for ( int i = 1; i <= element_count; i++ ) { array_list.add(i); } for ( int i = 0; i < array_list.size(); i++ ) { int expected = i + 1; assertEquals( expected, array_list.get( i ) ); } try { array_list.get( 100 ); fail( "Expected IndexOutOfBoundsException" ); } catch ( IndexOutOfBoundsException ex ) { // Expected } } public void testContains() { int element_count = 10; TIntList a = new TIntLinkedList(); assertTrue( a.isEmpty() ); for ( int i = 1; i <= element_count; i++ ) { a.add( i ); } for ( int i = 1; i <= element_count; i++ ) { assertTrue( "element " + i + " not found in " + a, a.contains( i ) ); } assertFalse("list doesn't hold MAX_VALUE: " + a, a.contains(Integer.MAX_VALUE)); } public void testInsert() { int element_count = 10; TIntList a = new TIntLinkedList(); assertTrue( a.isEmpty() ); for ( int i = 1; i <= element_count; i++ ) { a.add( i ); } int testval = 1138; a.insert( 5, testval ); for ( int i = 0; i < 5; i++ ) { int result = a.get( i ); int expected = i + 1; assertTrue( "element " + result + " should be " + expected, result == expected ); } assertEquals( testval, a.get( 5 ) ); for ( int i = 6; i < a.size(); i++ ) { int result = a.get( i ); assertTrue("element " + result + " should be " + i, result == i); } } public void testInsertArray() { int element_count = 10; int[] ints = {1138, 42, 86, 99, 101}; TIntList a = new TIntLinkedList(); assertTrue( a.isEmpty() ); for ( int i = 1; i <= element_count; i++ ) { a.add( i ); } a.insert( 0, ints ); assertEquals(ints.length + element_count, a.size()); for ( int i = 0; i < ints.length; i++ ) { assertEquals( ints[i], a.get( i ) ); } for ( int i = ints.length, j = 1; i < ints.length + element_count; i++, j++ ) { assertEquals( j, a.get( i ) ); } } public void testInsertAtEnd() { int element_count = 10; TIntList a = new TIntLinkedList(); assertTrue( a.isEmpty() ); for ( int i = 1; i <= element_count; i++ ) { a.add( i ); } a.insert( a.size(), 11 ); for ( int i = 0; i < element_count; i++ ) { assertEquals( i + 1, a.get( i ) ); } for ( int i = element_count; i < a.size(); i++ ) { int expected = i + 1; assertEquals( expected, a.get( i ) ); } } public void testInsertArrayAtEnd() { int element_count = 10; int[] ints = {1138, 42, 86, 99, 101}; TIntList a = new TIntLinkedList(); assertTrue( a.isEmpty() ); for ( int i = 1; i <= element_count; i++ ) { a.add( i ); } a.insert(a.size(), ints); for ( int i = 0; i < element_count; i++ ) { assertEquals( i + 1, a.get( i ) ); } for ( int i = element_count, j = 0; i < ints.length + element_count; i++, j++ ) { assertEquals( ints[j], a.get( i ) ); } } public void testSetArray() { int element_count = 10; int[] ints = {1138, 42, 86, 99, 101}; TIntList a = new TIntLinkedList(); assertTrue( a.isEmpty() ); for ( int i = 1; i <= element_count; i++ ) { a.add( i ); } a.set( a.size() - ints.length, ints ); for ( int i = 0; i < element_count - ints.length; i++ ) { assertEquals(i + 1, a.get(i)); } for ( int i = element_count - ints.length, j = 0; i < a.size(); i++, j++ ) { assertEquals(ints[j], a.get(i)); } try { a.set( a.size(), ints ); fail( "Expected IndexOutOfBoundsException" ); } catch ( IndexOutOfBoundsException ex ) { // Expected } } public void testSet() { int element_count = 10; TIntList a = new TIntLinkedList(); assertTrue( a.isEmpty() ); for ( int i = 1; i <= element_count; i++ ) { a.add( i ); } int testval = 1138; a.set( 5, testval ); for ( int i = 0; i < 5; i++ ) { int result = a.get( i ); int expected = i + 1; assertTrue( "element " + result + " should be " + expected, result == expected ); } assertEquals( testval, a.get( 5 ) ); for ( int i = 6; i < a.size(); i++ ) { int result = a.get( i ); int expected = i + 1; assertTrue( "element " + result + " should be " + expected, result == expected ); } try { a.set(100, 20); fail( "Expected IndexOutOfBoundsException" ); } catch ( IndexOutOfBoundsException ex ) { // Expected } } public void testReplace() { int element_count = 10; TIntList a = new TIntLinkedList(); assertTrue( a.isEmpty() ); for ( int i = 1; i <= element_count; i++ ) { a.add( i ); } int testval = 1138; assertEquals( 6, a.replace( 5, testval ) ); for ( int i = 0; i < 5; i++ ) { int result = a.get( i ); int expected = i + 1; assertTrue( "element " + result + " should be " + expected, result == expected ); } assertEquals( testval, a.get( 5 ) ); for ( int i = 6; i < a.size(); i++ ) { int result = a.get( i ); int expected = i + 1; assertTrue( "element " + result + " should be " + expected, result == expected ); } try { a.replace( 100, 20 ); fail( "Expected IndexOutOfBoundsException" ); } catch ( IndexOutOfBoundsException ex ) { // Expected } } public void testRemove() { int element_count = 10; TIntList a = new TIntLinkedList(); assertTrue( a.isEmpty() ); for ( int i = 1; i <= element_count; i++ ) { a.add( i ); } assertEquals( 6, a.get( 5 ) ); assertTrue( a.remove( 5 ) ); for ( int i = 0; i < 4; i++ ) { int expected = i + 1; assertTrue( "index " + i + " expected " + expected, a.get( i ) == expected ); } for ( int i = 4; i < a.size(); i++ ) { int expected = i + 2; assertTrue( "index " + i + " expected " + expected, a.get( i ) == expected ); } // Can't remove again from THIS list because it's not present. assertFalse( a.remove( 5 ) ); assertEquals( 6, a.removeAt( 4 ) ); for ( int i = 0; i < 4; i++ ) { int expected = i + 1; assertTrue( "index " + i + " expected " + expected, a.get( i ) == expected ); } for ( int i = 4; i < a.size(); i++ ) { int expected = i + 3; assertTrue( "index " + i + " expected " + expected, a.get( i ) == expected ); } a.insert( 4, 6 ); // Add a value twice, can remove it twice assertTrue( a.add( 5 ) ); assertTrue( a.add( 5 ) ); assertTrue( a.remove( 5 ) ); assertTrue( a.remove( 5 ) ); assertFalse( a.remove( 5 ) ); a.insert( 4, 5 ); assertTrue( a.add( 5 ) ); for ( int i = 0; i < 5; i++ ) { int expected = i + 1; assertTrue( "index " + i + " expected " + expected, a.get( i ) == expected ); } for ( int i = 5; i < a.size() - 1; i++ ) { int expected = i + 1; assertTrue( "index " + i + " expected " + expected + ", list: " + a, a.get( i ) == expected ); } assertEquals( 5, a.get( a.size() - 1 ) ); assertTrue( a.remove( 5 ) ); assertEquals( element_count, a.size() ); for ( int i = 0; i < 4; i++ ) { int expected = i + 1; assertTrue( "index " + i + " expected " + expected, a.get( i ) == expected ); } for ( int i = 4; i < a.size() - 1; i++ ) { int expected = i + 2; assertTrue( "index " + i + " expected " + expected, a.get( i ) == expected ); } assertEquals( 5, a.get( a.size() - 1 ) ); } public void testRemoveMultiple() { int element_count = 20; TIntList a = new TIntLinkedList(); assertTrue( a.isEmpty() ); for ( int i = 1; i <= element_count; i++ ) { a.add( i ); } // Remove odd offsets, which are even numbers. for ( int i = element_count; i >= 0; i-- ) { if ( i % 2 == 1 ) { a.removeAt( i ); } } for ( int i = 0; i < a.size(); i++ ) { int expected = i * 2 + 1; assertTrue( "index " + i + " expected " + expected, a.get( i ) == expected ); } } public void testRemoveChunk() { int element_count = 20; TIntList a = new TIntLinkedList(); assertTrue( a.isEmpty() ); for ( int i = 1; i <= element_count; i++ ) { a.add( i ); } a.remove( 5, 10 ); for ( int i = 0; i < 5; i++ ) { int expected = i + 1; assertTrue( "index " + i + " expected " + expected, a.get( i ) == expected ); } for ( int i = 5; i < a.size(); i++ ) { int expected = i + 11; assertTrue( "index " + i + " expected " + expected + " but got " + a.get( i ), a.get( i ) == expected ); } try { a.remove( -1, 10 ); fail( "Expected ArrayIndexOutOfBoundsException" ); } catch ( ArrayIndexOutOfBoundsException ex ) { // Expected } try { a.remove( a.size(), 1 ); fail( "Expected ArrayIndexOutOfBoundsException" ); } catch ( ArrayIndexOutOfBoundsException ex ) { // Expected } } public void testContainsAllCollection() { int element_count = 20; SortedSet set = new TreeSet(); for ( int i = 0; i < element_count; i++ ) { set.add( Integer.valueOf( i ) ); } TIntLinkedList list = new TIntLinkedList( ); for ( int i = 0; i < element_count; i++ ) { list.add( i ); } assertTrue( "list: " + list + " should contain all of set: " + set, list.containsAll( set ) ); set.remove( element_count ); assertTrue( "list: " + list + " should contain all of set: " + set, list.containsAll( set ) ); list.remove( 5 ); assertFalse( "list: " + list + " should not contain all of set: " + set, list.containsAll( set ) ); list.add( 5 ); // Test when not all objects are Integers.. Set obj_set = new HashSet(); for ( int i = 0; i < element_count; i++ ) { if ( i != 5 ) { obj_set.add( Integer.valueOf( i ) ); } else { obj_set.add( Long.valueOf( ( long ) i ) ); } } assertFalse( "list should not contain all of obj_set", list.containsAll( obj_set ) ); } public void testContainsAllTCollection() { int element_count = 20; TIntLinkedList list = new TIntLinkedList( element_count * 2 ); for ( int i = 0; i < element_count; i++ ) { list.add( i ); } TIntLinkedList other = new TIntLinkedList( list ); assertEquals( element_count, list.size() ); assertEquals( element_count, other.size() ); assertEquals( list, other ); assertTrue( "list should contain all of itself: " + list, list.containsAll( list ) ); assertTrue( "list should contain all of equal list " + list + ", " + other, list.containsAll( other ) ); for ( int i = 0; i < other.size(); i++ ) { if ( i % 2 == 0 ) { other.removeAt( i ); } } assertTrue( "list: " + list + " should contain all of other: " + other, list.containsAll( other ) ); other.add( 1138 ); assertFalse( "list: " + list + " should not contain all of other: " + other, list.containsAll( other ) ); TIntSet set = new TIntHashSet( list ); assertTrue( "list: " + list + " should contain all of set: " + set, list.containsAll( set ) ); set.add ( 1138 ); assertFalse( "list: " + list + " should not contain all of set: " + set, list.containsAll( set ) ); } public void testContainsAllArray() { int element_count = 20; int[] ints = new int[element_count]; TIntLinkedList list = new TIntLinkedList( element_count * 2 ); for ( int i = 0; i < element_count; i++ ) { ints[i] = i; list.add( i ); } assertTrue( "list: " + list + " should contain all of array: " + Arrays.toString(ints), list.containsAll( ints ) ); ints[5] = 1138; assertFalse( "list: " + list + " should cnot ontain all of array: " + Arrays.toString( ints ), list.containsAll( ints ) ); } public void testAddAllCollection() { int element_count = 20; SortedSet set = new TreeSet(); for ( int i = 0; i < element_count; i++ ) { set.add( Integer.valueOf( i ) ); } TIntLinkedList list = new TIntLinkedList( 20 ); for ( int i = 0; i < element_count; i++ ) { list.add( i ); } assertEquals( element_count, set.size() ); assertEquals( element_count, list.size() ); list.addAll( set ); assertEquals( element_count * 2, list.size() ); for ( int i = 0; i < list.size(); i++ ) { int expected; if ( i < element_count ) { expected = i; } else { expected = i - element_count; } assertEquals( expected , list.get( i ) ); } } public void testAddAllTCollection() { int element_count = 20; TIntLinkedList source = new TIntLinkedList(); for ( int i = 0; i < element_count; i++ ) { source.add( Integer.valueOf( i ) ); } TIntLinkedList list = new TIntLinkedList( 20 ); for ( int i = 0; i < element_count; i++ ) { list.add( i ); } assertEquals( element_count, source.size() ); assertEquals( element_count, list.size() ); list.addAll( source ); assertEquals( element_count * 2, list.size() ); for ( int i = 0; i < list.size(); i++ ) { int expected; if ( i < element_count ) { expected = i; } else { expected = i - element_count; } assertEquals( expected , list.get( i ) ); } } public void testAddAllArray() { int element_count = 20; int[] ints = new int[element_count]; TIntLinkedList list = new TIntLinkedList(); for ( int i = 0; i < element_count; i++ ) { ints[i] = i; list.add( Integer.valueOf( i ) ); } assertEquals( element_count, list.size() ); assertTrue ( list.addAll( ints ) ); assertEquals( element_count * 2, list.size() ); for ( int i = 0; i < list.size(); i++ ) { int expected; if ( i < element_count ) { expected = i; } else { expected = i - element_count; } assertEquals( "expected: " + expected + ", got: " + list.get( i ) + ", list: " + list + ", array: " + Arrays.toString( ints ), expected , list.get( i ) ); } } public void testRetainAllCollection() { int element_count = 20; SortedSet set = new TreeSet(); for ( int i = 0; i < element_count; i++ ) { set.add( Integer.valueOf( i ) ); } TIntList list = new TIntLinkedList( 20 ); for ( int i = 0; i < element_count; i++ ) { list.add( i ); } assertEquals( element_count, set.size() ); assertEquals( element_count, list.size() ); assertFalse( list.retainAll( set ) ); assertEquals( element_count, list.size() ); for ( int i = 0; i < list.size(); i++ ) { assertEquals( i , list.get( i ) ); } set.remove( 0 ); set.remove( 5 ); set.remove( 10 ); set.remove( 15 ); assertTrue( list.retainAll( set ) ); int expected = element_count - 4; assertEquals( "expected: " + expected + ", was: " + list.size() + ", list: " + list , expected, list.size() ); for ( int i = 0; i < list.size(); i++ ) { expected = ( int ) Math.floor( i / 4 ) + i + 1; assertEquals( "expected: " + expected + ", was: " + list.get( i ) + ", list: " + list, expected , list.get( i ) ); } } public void testRetainAllTCollection() { int element_count = 20; TIntList other = new TIntLinkedList(); for ( int i = 0; i < element_count; i++ ) { other.add( i ); } TIntList list = new TIntLinkedList( 20 ); for ( int i = 0; i < element_count; i++ ) { list.add( i ); } assertEquals( element_count, list.size() ); assertEquals( element_count, other.size() ); assertFalse( list.retainAll( list ) ); assertFalse( list.retainAll( other ) ); assertEquals( element_count, list.size() ); for ( int i = 0; i < list.size(); i++ ) { assertEquals( i , list.get( i ) ); } other.remove( 0 ); other.remove( 5 ); other.remove( 10 ); other.remove( 15 ); assertTrue( list.retainAll( other ) ); int expected = element_count - 4; assertEquals( expected, list.size() ); for ( int i = 0; i < list.size(); i++ ) { expected = ( int ) Math.floor( i / 4 ) + i + 1; assertEquals( "expected: " + expected + ", was: " + list.get( i ) + ", list: " + list, expected , list.get( i ) ); } } public void testRetainAllArray() { int element_count = 20; int ints[] = new int[element_count]; for ( int i = 0; i < element_count; i++ ) { ints[i] = i; } TIntList list = new TIntLinkedList( 20 ); for ( int i = 0; i < element_count; i++ ) { list.add( i ); } assertEquals( element_count, list.size() ); assertFalse( list.retainAll( ints ) ); assertEquals( element_count, list.size() ); for ( int i = 0; i < list.size(); i++ ) { assertEquals( i , list.get( i ) ); } ints = new int[( element_count - 4 )] ; for ( int i = 0, j = 0; i < ints.length; i++, j++ ) { if ( i % 4 == 0 ) { j++; } ints[i] = j; } assertTrue( list.retainAll( ints ) ); int expected = element_count - 4; assertEquals( expected, list.size() ); for ( int i = 0; i < list.size(); i++ ) { expected = ( int ) Math.floor( i / 4 ) + i + 1; assertEquals( "expected: " + expected + ", was: " + list.get( i ) + ", list: " + list, expected , list.get( i ) ); } } public void testRemoveAllCollection() { int element_count = 20; SortedSet set = new TreeSet(); for ( int i = 0; i < element_count; i++ ) { set.add( Integer.valueOf( i ) ); } TIntList list = new TIntLinkedList( 20 ); for ( int i = 0; i < element_count; i++ ) { list.add( i ); } assertEquals( element_count, set.size() ); assertEquals( element_count, list.size() ); assertTrue( list.removeAll( set ) ); assertTrue( list.isEmpty() ); assertEquals( 0, list.size() ); assertEquals( element_count, set.size() ); for ( int i = 0; i < set.size(); i++ ) { assertTrue( set.contains( Integer.valueOf( i ) ) ); } // Reset the list list = new TIntLinkedList( 20 ); for ( int i = 0; i < element_count; i++ ) { list.add( i ); } set.remove( 0 ); set.remove( 5 ); set.remove( 10 ); set.remove( 15 ); assertTrue( list.removeAll( set ) ); int expected = 4; assertEquals( "expected: " + expected + ", was: " + list.size() + ", list: " + list , expected, list.size() ); for ( int i = 0; i < list.size(); i++ ) { expected = i * 5; assertEquals( "expected: " + expected + ", was: " + list.get( i ) + ", list: " + list, expected , list.get( i ) ); } } public void testRemoveAllTCollection() { int element_count = 20; TIntList other = new TIntLinkedList(); for ( int i = 0; i < element_count; i++ ) { other.add( i ); } TIntList list = new TIntLinkedList( 20 ); for ( int i = 0; i < element_count; i++ ) { list.add( i ); } assertEquals( element_count, list.size() ); assertEquals( element_count, other.size() ); assertTrue( list.removeAll( list ) ); assertEquals( 0, list.size() ); assertTrue( list.isEmpty() ); // Reset the list list = new TIntLinkedList( 20 ); for ( int i = 0; i < element_count; i++ ) { list.add( i ); } assertTrue( list.removeAll( other ) ); assertEquals( 0, list.size() ); assertTrue( list.isEmpty() ); for ( int i = 0; i < list.size(); i++ ) { assertEquals( i , list.get( i ) ); } // Reset the list list = new TIntLinkedList( 20 ); for ( int i = 0; i < element_count; i++ ) { list.add( i ); } other.remove( 0 ); other.remove( 5 ); other.remove( 10 ); other.remove( 15 ); assertTrue( list.removeAll( other ) ); int expected = 4; assertEquals( "expected: " + expected + ", was: " + list.size() + ", list: " + list , expected, list.size() ); for ( int i = 0; i < list.size(); i++ ) { expected = i * 5; assertEquals( "expected: " + expected + ", was: " + list.get( i ) + ", list: " + list, expected , list.get( i ) ); } } public void testRemoveAllArray() { int element_count = 20; int ints[] = new int[element_count]; for ( int i = 0; i < element_count; i++ ) { ints[i] = i; } TIntList list = new TIntLinkedList( 20 ); for ( int i = 0; i < element_count; i++ ) { list.add( i ); } assertEquals( element_count, list.size() ); assertTrue( list.removeAll( ints ) ); assertEquals( 0, list.size() ); assertTrue( list.isEmpty() ); // Reset the list list = new TIntLinkedList( 20 ); for ( int i = 0; i < element_count; i++ ) { list.add( i ); } ints = new int[( element_count - 4 )] ; for ( int i = 0, j = 0; i < ints.length; i++, j++ ) { if ( i % 4 == 0 ) { j++; } ints[i] = j; } assertTrue( list.removeAll( ints ) ); int expected = 4; assertEquals( expected, list.size() ); for ( int i = 0; i < list.size(); i++ ) { expected = i * 5; assertEquals( "expected: " + expected + ", was: " + list.get( i ) + ", list: " + list, expected , list.get( i ) ); } } public void testShuffle() { int element_count = 20; TIntList list = new TIntLinkedList( 20 ); for ( int i = 0; i < element_count; i++ ) { list.add( i ); } TIntList copy = new TIntLinkedList(list); list.shuffle( new Random( System.currentTimeMillis() ) ); boolean differ = false; for ( int i = 0; i < list.size(); i++ ) { assertTrue( list.contains( i ) ); if (copy.get(i) != list.get(i)) differ = true; } // lost nothing Set s = new HashSet(); for (TIntIterator iterator = list.iterator(); iterator.hasNext();) { int next = iterator.next(); s.add(next); } assertTrue(s.size() == list.size()); assertTrue(copy.size() == list.size()); assertTrue("list not different " + copy + " shuffled= " + list, differ); } public void testIterator() { int element_count = 20; TIntList list = new TIntLinkedList(); for ( int i = 0; i < element_count; i++ ) { list.add( i ); } TIntIterator iter = list.iterator(); assertTrue( "iter should have next: " + list.size(), iter.hasNext() ); int j = 0; while ( iter.hasNext() ) { int next = iter.next(); assertEquals( j, next ); j++; } assertFalse( iter.hasNext() ); iter = list.iterator(); for ( int i = 0; i < element_count / 2; i++ ) { iter.next(); } iter.remove(); try { // trying to remove it again should fail. iter.remove(); fail( "Expected IllegalStateException" ); } catch ( IllegalStateException ex ) { // Expected } for ( int i = 0; i < element_count / 2 - 1; i++ ) { iter.next(); } } public void testIteratorAbuseNext() { int element_count = 20; TIntList list = new TIntLinkedList(); for ( int i = 0; i < element_count; i++ ) { list.add( i ); } TIntIterator iter = list.iterator(); while ( iter.hasNext() ) { iter.next(); } assertFalse( iter.hasNext() ); list.remove( 5, 10 ); assertFalse( iter.hasNext() ); try { iter.next(); fail( "Expected NoSuchElementException" ); } catch( NoSuchElementException ex ) { // Expected. } } /* Disable since not clear how iterator implementation can detect concurrent modification and throw CME public void testIteratorAbuseRemove() { int element_count = 20; TIntList list = new TIntLinkedList(); for ( int i = 0; i < element_count; i++ ) { list.add( i ); } TIntIterator iter = list.iterator(); while ( iter.hasNext() ) { iter.next(); } assertFalse( iter.hasNext() ); list.remove( 5, 10 ); assertFalse( iter.hasNext() ); try { iter.remove(); fail( "Expected ConcurrentModificationException" ); } catch( ConcurrentModificationException ex ) { // Expected. } } */ /* public void testEnsureCapacity() { int size = 1000; TIntLinkedList array_list = new TIntLinkedList(); int initial_length = array_list._data.length; assertEquals( Constants.DEFAULT_CAPACITY, initial_length ); array_list.ensureCapacity( size ); int max_length = array_list._data.length; assertTrue( "not large enough: " + max_length + " should be >= " + size, max_length >= size ); } public void testTrimToSize() { int initial_size = 1000; int element_count = 100; TIntLinkedList array_list = new TIntLinkedList( initial_size ); int initial_length = array_list._data.length; assertEquals( initial_size, initial_length ); assertTrue( array_list.isEmpty() ); for ( int i = 1; i <= element_count; i++ ) { array_list.add( i ); } array_list.trimToSize(); int trimmed_length = array_list._data.length; assertTrue( "not trimmed: " + trimmed_length + " should be == " + element_count, trimmed_length == element_count ); }*/ public void testToArray() { assertTrue( Arrays.equals( new int[]{1, 2, 3, 4, 5}, list.toArray() ) ); assertTrue( Arrays.equals( new int[]{1, 2, 3, 4}, list.toArray( 0, 4 ) ) ); assertTrue( Arrays.equals( new int[]{2, 3, 4, 5}, list.toArray( 1, 4 ) ) ); assertTrue( Arrays.equals( new int[]{2, 3, 4}, list.toArray( 1, 3 ) ) ); try { list.toArray( -1, 5 ); fail( "Expected ArrayIndexOutOfBoundsException when begin < 0" ); } catch ( ArrayIndexOutOfBoundsException expected ) { // Expected } } public void testToArrayWithDest() { int[] dest = new int[5]; assertTrue( Arrays.equals( new int[]{1, 2, 3, 4, 5}, list.toArray( dest ) ) ); dest = new int[4]; assertTrue( Arrays.equals( new int[]{1, 2, 3, 4}, list.toArray( dest, 0, 4 ) ) ); dest = new int[4]; assertTrue( Arrays.equals( new int[]{2, 3, 4, 5}, list.toArray( dest, 1, 4 ) ) ); dest = new int[3]; assertTrue( Arrays.equals( new int[]{2, 3, 4}, list.toArray( dest, 1, 3 ) ) ); try { list.toArray( dest, -1, 5 ); fail( "Expected ArrayIndexOutOfBoundsException when begin < 0" ); } catch ( ArrayIndexOutOfBoundsException expected ) { // Expected } } public void testToArrayWithDestTarget() { int[] dest = new int[5]; assertTrue( Arrays.equals( new int[]{1, 2, 3, 4, 5}, list.toArray( dest ) ) ); dest = new int[4]; assertTrue( Arrays.equals( new int[]{1, 2, 3, 4}, list.toArray( dest, 0, 0, 4 ) ) ); dest = new int[5]; assertTrue( Arrays.equals( new int[]{0, 2, 3, 4, 5}, list.toArray( dest, 1, 1, 4 ) ) ); dest = new int[4]; assertTrue( Arrays.equals( new int[]{0, 2, 3, 4}, list.toArray( dest, 1, 1, 3 ) ) ); dest = new int[5]; assertTrue( Arrays.equals( new int[]{0, 0, 0, 0, 0}, list.toArray( dest, 0, 0, 0 ) ) ); try { list.toArray( dest, -1, 0, 5 ); fail( "Expected ArrayIndexOutOfBoundsException when begin < 0" ); } catch ( ArrayIndexOutOfBoundsException expected ) { // Expected } } public void testSubList() throws Exception { TIntList subList = list.subList( 1, 4 ); assertEquals( 3, subList.size() ); assertEquals( 2, subList.get( 0 ) ); assertEquals( 4, subList.get( 2 ) ); } public void testSublist_Exceptions() { try { list.subList( 1, 0 ); fail( "expected IllegalArgumentException when end < begin" ); } catch ( IllegalArgumentException expected ) { } try { list.subList( -1, 3 ); fail( "expected IndexOutOfBoundsException when begin < 0" ); } catch ( IndexOutOfBoundsException expected ) { } try { list.subList( 1, 42 ); fail( "expected IndexOutOfBoundsException when end > length" ); } catch ( IndexOutOfBoundsException expected ) { } } public void testIndexOf() { int element_count = 20; TIntList a = new TIntLinkedList(); for ( int i = 1; i <= element_count; i++ ) { a.add( i ); } int index = a.indexOf( 10 ); assertEquals( 9, index ); // Add more elements, but duplicates for ( int i = 1; i <= element_count; i++ ) { a.add( i ); } index = a.indexOf( 10 ); assertEquals( 9, index ); index = a.indexOf( 5 ); assertEquals( 4, index ); index = a.lastIndexOf( 5 ); assertEquals( 24, index ); // Non-existant entry index = a.indexOf( 100 ); assertEquals( -1, index ); } public void testBinarySearch() { int element_count = 20; TIntList a = new TIntLinkedList(); for ( int i = 1; i <= element_count; i++ ) { a.add( i ); } a.sort(); int index = a.binarySearch( 5 ); assertEquals( 4, index ); index = a.binarySearch( 8 ); assertEquals( 7, index ); // Add more elements, but duplicates for ( int i = 1; i <= element_count; i++ ) { a.add( i ); } a.sort(); index = a.indexOf( 5 ); assertTrue( "index: " + index, index >= 8 && index <= 9 ); // Not in this range. index = a.binarySearch( 5, 15, 30 ); assertTrue( "index: " + index, index < 0 ); try { a.binarySearch( 5, 10, 55 ); fail( "Expected ArrayIndexOutOfBoundsException" ); } catch ( IndexOutOfBoundsException ex ) { // Expected } try { a.binarySearch( 5, -1, 15 ); fail( "Expected ArrayIndexOutOfBoundsException" ); } catch ( IndexOutOfBoundsException ex ) { // Expected } } public void testFill() { int element_count = 20; TIntList a = new TIntLinkedList(); for ( int i = 1; i <= element_count; i++ ) { a.add( i ); } a.fill( 0xdeadbeef ); for ( int i = 0; i < element_count; i++ ) { assertEquals( 0xdeadbeef, a.get( i ) ); } } public void testFillOffsets() { int element_count = 20; TIntList a = new TIntLinkedList(); for ( int i = 1; i <= element_count; i++ ) { a.add( i ); } a.fill( 10, 15, 0xdeadbeef ); for ( int i = 0; i < 10; i++ ) { assertEquals( i + 1, a.get( i ) ); } for ( int i = 10; i < 15; i++ ) { assertEquals( 0xdeadbeef, a.get( i ) ); } for ( int i = 15; i < a.size(); i++ ) { assertEquals( i + 1, a.get( i ) ); } a.fill( 15, 25, 0xcafebabe ); assertEquals( 25, a.size() ); for ( int i = 0; i < 10; i++ ) { assertEquals( i + 1, a.get( i ) ); } for ( int i = 10; i < 15; i++ ) { assertEquals( 0xdeadbeef, a.get( i ) ); } for ( int i = 15; i < a.size(); i++ ) { assertEquals( 0xcafebabe, a.get( i ) ); } } public void testGrep() { int element_count = 20; TIntList a = new TIntLinkedList(); for ( int i = 1; i < element_count; i++ ) { a.add( i ); } TIntList grepped = a.grep( new TIntProcedure() { public boolean execute( int value ) { return value > 10; } } ); for ( int i = 0; i < grepped.size(); i++ ) { int expected = i + 11; assertEquals( expected, grepped.get( i ) ); } } public void testInverseGrep() { int element_count = 20; TIntList a = new TIntLinkedList(); for ( int i = 1; i < element_count; i++ ) { a.add( i ); } TIntList grepped = a.inverseGrep( new TIntProcedure() { public boolean execute( int value ) { return value <= 10; } } ); for ( int i = 0; i < grepped.size(); i++ ) { int expected = i + 11; assertEquals( expected, grepped.get( i ) ); } } public void testMax() { assertEquals( 5, list.max() ); assertEquals( 1, list.min() ); TIntList list2 = new TIntLinkedList(); assertTrue( list2.isEmpty() ); list2.add( 3 ); list2.add( 1 ); list2.add( 2 ); list2.add( 5 ); list2.add( 4 ); assertEquals( 5, list2.max() ); assertEquals( 1, list2.min() ); try { TIntList list3 = new TIntLinkedList(); list3.min(); fail( "Expected IllegalStateException" ); } catch ( IllegalStateException ex ) { // Expected } try { TIntList list3 = new TIntLinkedList(); list3.max(); fail( "Expected IllegalStateException" ); } catch ( IllegalStateException ex ) { // Expected } } public void testForEach() { int element_count = 20; TIntList a = new TIntLinkedList(); for ( int i = 1; i < element_count; i++ ) { a.add( i ); } class ForEach implements TIntProcedure { TIntList built = new TIntLinkedList(); public boolean execute( int value ) { built.add( value ); return true; } TIntList getBuilt() { return built; } } ForEach foreach = new ForEach(); a.forEach( foreach ); TIntList built = foreach.getBuilt(); assertEquals( a, built ); } public void testForEachFalse() { int element_count = 20; TIntList a = new TIntLinkedList(); for ( int i = 1; i < element_count; i++ ) { a.add( i ); } class ForEach implements TIntProcedure { TIntList built = new TIntLinkedList(); public boolean execute( int value ) { built.add( value ); return false; } TIntList getBuilt() { return built; } } ForEach foreach = new ForEach(); a.forEach( foreach ); TIntList built = foreach.getBuilt(); assertEquals( 1, built.size() ); assertEquals( 1, built.get( 0 ) ); } public void testForEachDescending() { int element_count = 20; TIntList a = new TIntLinkedList(); for ( int i = 1; i < element_count; i++ ) { a.add( i ); } class ForEach implements TIntProcedure { TIntList built = new TIntLinkedList(); public boolean execute( int value ) { built.add( value ); return true; } TIntList getBuilt() { return built; } } ForEach foreach = new ForEach(); a.forEachDescending( foreach ); TIntList built = foreach.getBuilt(); built.reverse(); assertEquals( a, built ); } public void testForEachDescendingFalse() { int element_count = 20; TIntList a = new TIntLinkedList(); for ( int i = 1; i < element_count; i++ ) { a.add( i ); } class ForEach implements TIntProcedure { TIntList built = new TIntLinkedList(); public boolean execute( int value ) { built.add( value ); return false; } TIntList getBuilt() { return built; } } ForEach foreach = new ForEach(); a.forEachDescending( foreach ); TIntList built = foreach.getBuilt(); built.reverse(); assertEquals( 1, built.size() ); assertEquals( 19, built.get( 0 ) ); } public void testTransform() { int element_count = 20; TIntList a = new TIntLinkedList(); for ( int i = 1; i < element_count; i++ ) { a.add( i ); } a.transformValues( new TIntFunction() { public int execute( int value ) { return value * value; } } ); for ( int i = 0; i < a.size(); i++ ) { int result = a.get( i ); int expected = ( i + 1 ) * ( i + 1 ); assertEquals( expected, result ); } } public void testReverse() { int element_count = 20; TIntList a = new TIntLinkedList(); for ( int i = 1; i <= element_count; i++ ) { a.add( i ); } a.reverse(); a.reverse(); a.reverse(); for ( int i = 0, j = a.size(); i < a.size(); i++, j-- ) { assertEquals( j, a.get( i ) ); } } public void testReversePartial() { int element_count = 20; TIntList a = new TIntLinkedList(); for ( int i = 1; i <= element_count; i++ ) { a.add( i ); } a.reverse( 1, 19 ); int[] expected = {1, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 20}; for ( int i = 0; i < a.size(); i++ ) { assertEquals( expected[i], a.get( i ) ); } try { a.reverse( 20, 10 ); fail( "Expected IllegalArgumentException" ); } catch ( IllegalArgumentException ex ) { // Expected } } public void testSortPartial() { int element_count = 20; TIntList a = new TIntLinkedList(); for ( int i = 1; i <= element_count; i++ ) { a.add( i ); } a.reverse(); a.sort( 5, 15 ); int[] expected = {20, 19, 18, 17, 16, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 5, 4, 3, 2, 1}; for ( int i = 0; i < a.size(); i++ ) { assertEquals( expected[i], a.get( i ) ); } try { a.sort( 20, 10 ); fail( "Expected IllegalArgumentException" ); } catch ( IllegalArgumentException ex ) { // Expected } } public void testEquals() { int element_count = 20; TIntList list = new TIntLinkedList(); for ( int i = 1; i <= element_count; i++ ) { list.add( i ); } assertEquals( list, list ); assertEquals( list, new TIntLinkedList( list ) ); TIntCollection collection = new TIntHashSet(); for ( int i = 1; i <= element_count; i++ ) { collection.add( i ); } assertFalse( list.equals( collection ) ); collection.add( 1138 ); assertFalse( list.equals( collection ) ); TIntList other = new TIntLinkedList( list ); other.replace( 10, 1138 ); assertFalse( list.equals( other ) ); } public void testSerialization() throws Exception { ByteArrayOutputStream bout = new ByteArrayOutputStream(); ObjectOutputStream oout = new ObjectOutputStream( bout ); oout.writeObject( list ); oout.close(); ObjectInputStream oin = new ObjectInputStream( new ByteArrayInputStream( bout.toByteArray() ) ); TIntLinkedList new_list = (TIntLinkedList) oin.readObject(); assertEquals( list, new_list ); } } trove-3.0.3/test/gnu/trove/list/linked/TLinkableAdapterTest.java0000644000175000017500000000126211763017634023634 0ustar ericherichpackage gnu.trove.list.linked; import gnu.trove.list.TLinkableAdapter; import junit.framework.TestCase; /** * */ public class TLinkableAdapterTest extends TestCase { public void testOverride() { TLinkedList list = new TLinkedList(); list.add( new MyObject( "1" ) ); list.add( new MyObject( "2" ) ); list.add( new MyObject( "3" ) ); int i = 1; for( MyObject obj : list ) { assertEquals( String.valueOf( i ), obj.getValue() ); i++; } } private class MyObject extends TLinkableAdapter { private final String value; MyObject( String value ) { this.value = value; } public String getValue() { return value; } } } trove-3.0.3/test/gnu/trove/list/linked/TLinkedListTest.java0000644000175000017500000010415211763017634022656 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001, Eric D. Friedman All Rights Reserved. // Copyright (c) 2009, Rob Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.list.linked; import gnu.trove.list.TIntList; import gnu.trove.list.TLinkable; import gnu.trove.procedure.TObjectProcedure; import junit.framework.TestCase; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.*; /** * Created: Sat Nov 10 15:57:07 2001 * * @author Eric D. Friedman * @author Rob Eden * @author Jeff Randall * @version $Id: TLinkedListTest.java,v 1.1.2.4 2010/09/27 17:23:07 robeden Exp $ */ @SuppressWarnings({"ForLoopReplaceableByForEach", "ManualArrayToCollectionCopy"}) public class TLinkedListTest extends TestCase { protected TLinkedList list; public TLinkedListTest( String name ) { super( name ); } public void setUp() throws Exception { list = new TLinkedList(); } public void tearDown() throws Exception { list = null; } public void testAdd() throws Exception { Data[] data = {new Data( 1 ), new Data( 2 ), new Data( 3 )}; for ( int i = 0; i < data.length; i++ ) { list.add( data[i] ); } assertEquals( 3, list.size() ); } public void testAddAtIndex() throws Exception { Data[] data = {new Data( 1 ), new Data( 2 ), new Data( 3 ), new Data( 4 ), new Data( 5 ), new Data( 6 ), new Data( 7 ), new Data( 8 ), new Data( 9 )}; for ( int i = 0; i < data.length; i++ ) { list.add( data[i] ); } assertEquals( data.length, list.size() ); for ( int i = 0; i < data.length; i++ ) { assertEquals( data[i], list.get( i ) ); } Data to_insert = new Data( 1138 ); list.add( 1, to_insert ); assertEquals( to_insert, list.get( 1 ) ); assertEquals( data[0], list.get( 0 ) ); for ( int i = 2; i < data.length; i++ ) { assertEquals( data[i - 1], list.get( i ) ); } } public void testAddIllegalArgs() { Data[] data = {new Data( 1 ), new Data( 2 ), new Data( 3 ), new Data( 4 ), new Data( 5 ), new Data( 6 ), new Data( 7 ), new Data( 8 ), new Data( 9 )}; for ( int i = 0; i < data.length; i++ ) { list.add( data[i] ); } assertEquals( data.length, list.size() ); for ( int i = 0; i < data.length; i++ ) { assertEquals( data[i], list.get( i ) ); } try { list.add( -1, new Data( 1138 ) ); fail( "Expected IndexOutOfBoundsException" ); } catch ( IndexOutOfBoundsException ex ) { // Expected } try { list.add( list.size() + 1, new Data( 1138 ) ); fail( "Expected IndexOutOfBoundsException" ); } catch ( IndexOutOfBoundsException ex ) { // Expected } } public void testClear() { Data[] data = {new Data( 1 ), new Data( 2 ), new Data( 3 ), new Data( 4 ), new Data( 5 ), new Data( 6 ), new Data( 7 ), new Data( 8 ), new Data( 9 )}; for ( int i = 0; i < data.length; i++ ) { list.add( data[i] ); } assertEquals( data.length, list.size() ); for ( int i = 0; i < data.length; i++ ) { assertEquals( data[i], list.get( i ) ); } list.clear(); assertTrue( "list should be empty", list.isEmpty() ); } public void testInsert() throws Exception { Data[] data = {new Data( 2 ), new Data( 4 ), new Data( 6 )}; for ( int i = 0; i < data.length; i++ ) { list.add( data[i] ); } list.insert( 0, new Data( 1 ) ); list.insert( 2, new Data( 3 ) ); list.insert( 4, new Data( 5 ) ); list.insert( list.size(), new Data( 7 ) ); assertEquals( 7, list.size() ); for ( int i = 0; i < list.size(); i++ ) { assertEquals( i + 1, list.get( i )._val ); } } public void testToArray() { Data[] data = {new Data( 1 ), new Data( 2 ), new Data( 3 ), new Data( 4 ), new Data( 5 ), new Data( 6 ), new Data( 7 ), new Data( 8 ), new Data( 9 )}; for ( int i = 0; i < data.length; i++ ) { list.add( data[i] ); } assertEquals( data.length, list.size() ); for ( int i = 0; i < data.length; i++ ) { assertEquals( data[i], list.get( i ) ); } Data[] data_array = list.toArray( new Data[0] ); assertEquals( list.size(), data_array.length ); for ( int i = 0; i < list.size(); i++ ) { assertEquals( data_array[i], list.get( i ) ); } Object[] obj_array = list.toArray(); assertEquals( list.size(), obj_array.length ); for ( int i = 0; i < list.size(); i++ ) { assertEquals( obj_array[i], list.get( i ) ); } } public void testToUnlinkedArray() { Data[] data = {new Data( 1 ), new Data( 2 ), new Data( 3 ), new Data( 4 ), new Data( 5 ), new Data( 6 ), new Data( 7 ), new Data( 8 ), new Data( 9 )}; for ( int i = 0; i < data.length; i++ ) { list.add( data[i] ); } assertEquals( data.length, list.size() ); for ( int i = 0; i < data.length; i++ ) { assertEquals( data[i], list.get( i ) ); } Object[] data_array = list.toUnlinkedArray(); assertEquals( data.length, data_array.length ); for ( int i = 0; i < data.length; i++ ) { assertEquals( data[i], data_array[i] ); } } public void testToUnlinkedArrayTyped() { Data[] data = {new Data( 1 ), new Data( 2 ), new Data( 3 ), new Data( 4 ), new Data( 5 ), new Data( 6 ), new Data( 7 ), new Data( 8 ), new Data( 9 )}; for ( int i = 0; i < data.length; i++ ) { list.add( data[i] ); } assertEquals( data.length, list.size() ); for ( int i = 0; i < data.length; i++ ) { assertEquals( data[i], list.get( i ) ); } Data[] data_array = list.toUnlinkedArray( new Data[0] ); assertEquals( data.length, data_array.length ); for ( int i = 0; i < data.length; i++ ) { assertEquals( data[i], data_array[i] ); } } public void testContains() { Data[] data = {new Data( 1 ), new Data( 2 ), new Data( 3 ), new Data( 4 ), new Data( 5 ), new Data( 6 ), new Data( 7 ), new Data( 8 ), new Data( 9 )}; for ( int i = 0; i < data.length; i++ ) { list.add( data[i] ); } assertEquals( data.length, list.size() ); for ( int i = 0; i < data.length; i++ ) { assertEquals( data[i], list.get( i ) ); } Data item = new Data( 5 ); assertTrue( "list contains item: " + item + ", " + list, list.contains( item ) ); item = new Data( 1138 ); assertFalse( "list doesn't contain item: "+ item + ", " + list, list.contains( item ) ); } public void testNextIterator() throws Exception { Data[] data = new Data[100]; for ( int i = 0; i < data.length; i++ ) { data[i] = new Data( i ); list.add( data[i] ); } int count = 0; for ( Iterator i = list.iterator(); i.hasNext(); ) { assertEquals( data[count++], i.next() ); } assertEquals( data.length, count ); count = 4; for ( Iterator i = list.listIterator( 4 ); i.hasNext(); ) { assertEquals( data[count++], i.next() ); } assertEquals( data.length, count ); } public void testPreviousIterator() throws Exception { Data[] data = new Data[100]; for ( int i = 0; i < data.length; i++ ) { data[i] = new Data( i ); list.add( data[i] ); } int count = 100; for ( ListIterator i = list.listIterator( list.size() ); i.hasPrevious(); ) { assertEquals( data[--count], i.previous() ); } assertEquals( 0, count ); count = 5; for ( ListIterator i = list.listIterator( count ); i.hasPrevious(); ) { assertEquals( data[--count], i.previous() ); } assertEquals( 0, count ); } public void testIteratorSet() throws Exception { Data[] data = new Data[100]; for ( int i = 0; i < data.length; i++ ) { data[i] = new Data( i ); list.add( data[i] ); } ListIterator i; i = list.listIterator( 5 ); i.next(); Data d = new Data( 999 ); i.set( d ); assertEquals( d, list.get( 5 ) ); } public void testRemoveOnlyElementInList() throws Exception { Data d = new Data( 0 ); list.add( d ); ListIterator i = list.listIterator(); assertTrue( i.hasNext() ); assertEquals( d, i.next() ); i.remove(); assertTrue( !i.hasNext() ); assertTrue( !i.hasPrevious() ); assertEquals( 0, list.size() ); } public void testRemovePrevious() throws Exception { Data[] d = {new Data( 0 ), new Data( 1 ), new Data( 2 )}; list.addAll( Arrays.asList( d ) ); ListIterator i = list.listIterator( list.size() ); i.previous(); i.previous(); i.remove(); assertEquals( 2, list.size() ); assertTrue( i.hasPrevious() ); assertEquals( d[0], i.previous() ); assertTrue( !i.hasPrevious() ); assertTrue( i.hasNext() ); assertEquals( d[0], i.next() ); assertTrue( i.hasNext() ); assertEquals( d[2], i.next() ); assertTrue( !i.hasNext() ); assertTrue( i.hasPrevious() ); assertEquals( 2, list.size() ); } public void testRemoveLast() throws Exception { Data[] d = {new Data( 0 ), new Data( 1 ), new Data( 2 )}; list.addAll( Arrays.asList( d ) ); ListIterator i = list.listIterator( list.size() ); i.previous(); i.remove(); assertEquals( 2, list.size() ); assertTrue( i.hasPrevious() ); assertTrue( !i.hasNext() ); } public void testRemoveFirst() throws Exception { Data[] d = {new Data( 0 ), new Data( 1 ), new Data( 2 )}; list.addAll( Arrays.asList( d ) ); ListIterator i = list.listIterator( 0 ); i.next(); i.remove(); assertEquals( 2, list.size() ); assertTrue( !i.hasPrevious() ); assertTrue( i.hasNext() ); } public void testRemoveNext() throws Exception { Data[] d = {new Data( 0 ), new Data( 1 ), new Data( 2 )}; list.addAll( Arrays.asList( d ) ); ListIterator i = list.listIterator(); assertTrue( i.hasNext() ); i.next(); assertTrue( i.hasNext() ); assertTrue( i.hasPrevious() ); i.remove(); assertEquals( 2, list.size() ); assertTrue( !i.hasPrevious() ); assertTrue( i.hasNext() ); assertEquals( d[1], i.next() ); assertTrue( i.hasNext() ); assertEquals( d[2], i.next() ); assertTrue( i.hasPrevious() ); assertTrue( !i.hasNext() ); } public void testRemoveThrowsAfterAdd() throws Exception { Data d = new Data( 0 ); list.add( d ); ListIterator i = list.listIterator(); boolean didThrow = false; try { i.remove(); } catch ( IllegalStateException e ) { didThrow = true; } // end of try-catch assertTrue( didThrow ); } public void testRemoveThrowsWithoutPrevious() throws Exception { Data d = new Data( 0 ); list.add( d ); ListIterator i = list.listIterator( list.size() ); boolean didThrow = false; assertTrue( i.hasPrevious() ); try { i.remove(); } catch ( IllegalStateException e ) { didThrow = true; } // end of try-catch assertTrue( didThrow ); } public void testRemoveThrowsWithoutNext() throws Exception { Data d = new Data( 0 ); list.add( d ); ListIterator i = list.listIterator(); boolean didThrow = false; assertTrue( i.hasNext() ); try { i.remove(); } catch ( IllegalStateException e ) { didThrow = true; } // end of try-catch assertTrue( didThrow ); } public void testRemoveInvalidObject() { Object obj = new Object(); Data d = new Data( 1 ); list.add( d ); assertEquals( 1, list.size() ); assertFalse( "cannot remove elements that don't implement TLinkable", list.remove( obj ) ); } public void testIteratorAddFront() throws Exception { Data[] d = {new Data( 0 ), new Data( 1 ), new Data( 2 )}; list.addAll( Arrays.asList( d ) ); ListIterator i = list.listIterator(); Data d1 = new Data( 5 ); assertTrue( !i.hasPrevious() ); i.add( d1 ); assertTrue( i.hasPrevious() ); assertEquals( d1, i.previous() ); assertEquals( d1, i.next() ); assertEquals( d[0], i.next() ); assertEquals( d1, list.get( 0 ) ); } public void testIteratorAddBack() throws Exception { Data[] d = {new Data( 0 ), new Data( 1 ), new Data( 2 )}; list.addAll( Arrays.asList( d ) ); ListIterator i = list.listIterator( list.size() ); Data d1 = new Data( 5 ); assertEquals( 3, list.size() ); assertTrue( i.hasPrevious() ); assertTrue( !i.hasNext() ); i.add( d1 ); assertTrue( i.hasPrevious() ); assertTrue( !i.hasNext() ); assertEquals( 4, list.size() ); assertEquals( d1, i.previous() ); assertEquals( d1, i.next() ); assertEquals( d1, list.get( 3 ) ); } public void testIteratorAddMiddle() throws Exception { Data[] d = {new Data( 0 ), new Data( 1 ), new Data( 2 )}; list.addAll( Arrays.asList( d ) ); ListIterator i = list.listIterator( 1 ); Data d1 = new Data( 5 ); assertEquals( 3, list.size() ); assertTrue( i.hasPrevious() ); assertTrue( i.hasNext() ); i.add( d1 ); assertTrue( i.hasPrevious() ); assertTrue( i.hasNext() ); assertEquals( 4, list.size() ); assertEquals( d1, i.previous() ); assertEquals( d1, i.next() ); assertEquals( d1, list.get( 1 ) ); } public void testIteratorSetSingleElementList() throws Exception { Data d1 = new Data( 5 ); Data d2 = new Data( 4 ); list.add( d1 ); ListIterator i = list.listIterator( 0 ); i.next(); i.set( d2 ); assertEquals( 1, list.size() ); assertTrue( !i.hasNext() ); assertTrue( i.hasPrevious() ); assertEquals( d2, i.previous() ); assertTrue( i.hasNext() ); assertTrue( !i.hasPrevious() ); assertEquals( d2, i.next() ); } public void testIteratorAddEmptyList() throws Exception { ListIterator i = list.listIterator(); Data d1 = new Data( 5 ); assertTrue( !i.hasPrevious() ); assertTrue( !i.hasNext() ); i.add( d1 ); assertTrue( i.hasPrevious() ); assertTrue( !i.hasNext() ); assertEquals( d1, i.previous() ); assertEquals( d1, i.next() ); assertEquals( d1, list.get( 0 ) ); } public void testIteratorRemoveOnNext() throws Exception { Data[] data = new Data[100]; for ( int i = 0; i < data.length; i++ ) { data[i] = new Data( i ); list.add( data[i] ); } ListIterator i; i = list.listIterator( 5 ); i.next(); i.remove(); Data d = new Data( 6 ); assertEquals( d, list.get( 5 ) ); } public void testIteratorPastEnds() { int size = 10; Data[] data = new Data[size]; for ( int i = 0; i < data.length; i++ ) { data[i] = new Data( i ); list.add( data[i] ); } ListIterator iter = list.listIterator(); Data current = list.getFirst(); while( iter.hasNext() ) { assertEquals( current, list.get( iter.nextIndex() ) ); assertEquals( current, iter.next() ); Data test = list.getNext( current ); if ( test != null ) { current = test; } } // Now at end of the list; assertEquals( current, list.getLast() ); assertFalse( iter.hasNext() ); assertNull( list.getNext( current ) ); try { iter.next(); fail( "Expected NoSuchElementException" ); } catch ( NoSuchElementException ex ) { // Expected } /// Start end and work to the front. current = list.getLast(); iter = list.listIterator( list.size() ); while ( iter.hasPrevious() ) { assertEquals( current, list.get( iter.previousIndex() ) ); assertEquals( current, iter.previous() ); Data test = list.getPrevious( current ); if ( test != null ) { current = test; } } // Now at front of the list; assertEquals( current, list.getFirst() ); assertFalse( iter.hasPrevious() ); assertNull( list.getPrevious( current ) ); try { iter.previous(); fail( "Expected NoSuchElementException" ); } catch ( NoSuchElementException ex ) { // Expected } } public void testInvalidIterators() { int size = 10; Data[] data = new Data[size]; for ( int i = 0; i < data.length; i++ ) { data[i] = new Data( i ); list.add( data[i] ); } // Creating an iterator pointing before the start of the list should fail try { ListIterator iter = list.listIterator( -1 ); fail( "Expected IndexOutOfBoundsException" ); iter.next(); // prevent unused inspection, never reached } catch ( IndexOutOfBoundsException ex ) { // Expected } // Creating an iterator pointing past the end of the list should fail try { ListIterator iter = list.listIterator( list.size() + 1 ); fail( "Expected IndexOutOfBoundsException" ); iter.next(); // prevent unused inspection, never reached } catch ( IndexOutOfBoundsException ex ) { // Expected } // Set on a fresh iterator should fail. try { ListIterator iter = list.listIterator(); iter.set( new Data( 1138 ) ); fail( "Expected IllegalStateException" ); } catch ( IllegalStateException ex ) { // Expected } } public void testSerialize() throws Exception { TLinkedList list1 = new TLinkedList(); Data[] data = new Data[100]; for ( int i = 0; i < data.length; i++ ) { data[i] = new Data( i ); list1.add( data[i] ); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream( baos ); oos.writeObject( list1 ); ByteArrayInputStream bais = new ByteArrayInputStream( baos.toByteArray() ); ObjectInputStream ois = new ObjectInputStream( bais ); TLinkedList list2 = (TLinkedList) ois.readObject(); assertEquals( list1, list2 ); } public void testForEach() throws Exception { list.add( new Data( 0 ) ); list.add( new Data( 1 ) ); list.add( new Data( 2 ) ); list.add( new Data( 3 ) ); list.add( new Data( 4 ) ); // test exiting early boolean processed_full_list = list.forEachValue( new TObjectProcedure() { public boolean execute( Data object ) { if ( object._val == 2 ) { return false; } object._val++; return true; } } ); assertFalse( processed_full_list ); assertEquals( 1, list.get( 0 )._val ); assertEquals( 2, list.get( 1 )._val ); assertEquals( 2, list.get( 2 )._val ); assertEquals( 3, list.get( 3 )._val ); assertEquals( 4, list.get( 4 )._val ); // test full list processing processed_full_list = list.forEachValue( new TObjectProcedure() { public boolean execute( Data object ) { object._val++; return true; } } ); assertTrue( processed_full_list ); assertEquals( 2, list.get( 0 )._val ); assertEquals( 3, list.get( 1 )._val ); assertEquals( 3, list.get( 2 )._val ); assertEquals( 4, list.get( 3 )._val ); assertEquals( 5, list.get( 4 )._val ); } public void testAddBefore() { Data one = new Data( 1 ); Data three = new Data( 3 ); Data four = new Data( 4 ); Data five = new Data( 5 ); list.add( one ); list.add( three ); list.add( four ); list.add( five ); list.addBefore( one, new Data( 0 ) ); list.addBefore( three, new Data( 2 ) ); list.addBefore( null, new Data( 6 ) ); // System.out.println( "List: " + list ); // Iterate forward int value = -1; Data cur = list.getFirst(); while ( cur != null ) { assertEquals( value + 1, cur._val ); value = cur._val; cur = cur.getNext(); } assertEquals( 6, value ); // Iterate backward value = 7; cur = list.getLast(); while ( cur != null ) { assertEquals( value - 1, cur._val ); value = cur._val; cur = cur.getPrevious(); } assertEquals( 0, value ); } public void testAddAfter() { Data one = new Data( 1 ); Data three = new Data( 3 ); Data five = new Data( 5 ); list.add( one ); list.add( three ); list.add( five ); list.addAfter( one, new Data( 2 ) ); list.addAfter( three, new Data( 4 ) ); list.addAfter( five, new Data( 6 ) ); list.addAfter( null, new Data( 0 ) ); // System.out.println( "List: " + list ); // Iterate forward int value = -1; Data cur = list.getFirst(); while ( cur != null ) { assertEquals( value + 1, cur._val ); value = cur._val; cur = cur.getNext(); } assertEquals( 6, value ); // Iterate backward value = 7; cur = list.getLast(); while ( cur != null ) { // System.out.println( "Itr back: " + cur._val ); assertEquals( value - 1, cur._val ); value = cur._val; cur = cur.getPrevious(); } assertEquals( 0, value ); } public void testMultipleRemove() { Data one = new Data( 1 ); Data two = new Data( 2 ); Data three = new Data( 3 ); list.add( one ); list.add( two ); list.add( three ); list.remove( one ); assertEquals( 2, list.size() ); assertEquals( new Data( 2 ), list.get( 0 ) ); assertEquals( new Data( 3 ), list.get( 1 ) ); list.remove( one ); assertEquals( 2, list.size() ); assertEquals( new Data( 2 ), list.get( 0 ) ); assertEquals( new Data( 3 ), list.get( 1 ) ); list.remove( one ); assertEquals( 2, list.size() ); assertEquals( new Data( 2 ), list.get( 0 ) ); assertEquals( new Data( 3 ), list.get( 1 ) ); list.remove( one ); assertEquals( 2, list.size() ); assertEquals( new Data( 2 ), list.get( 0 ) ); assertEquals( new Data( 3 ), list.get( 1 ) ); list.remove( one ); assertEquals( 2, list.size() ); assertEquals( new Data( 2 ), list.get( 0 ) ); assertEquals( new Data( 3 ), list.get( 1 ) ); } public void testRemoveFirstAll() { list.add( new Data( 1 ) ); list.add( new Data( 2 ) ); list.add( new Data( 3 ) ); list.add( new Data( 4 ) ); int expected = 1; Data data; while ( ( data = list.removeFirst() ) != null ) { assertEquals( expected, data._val ); expected++; } assertTrue( list.isEmpty() ); } public void testRemoveLastAll() { list.add( new Data( 1 ) ); list.add( new Data( 2 ) ); list.add( new Data( 3 ) ); list.add( new Data( 4 ) ); int expected = 4; Data data; while ( ( data = list.removeLast() ) != null ) { assertEquals( expected, data._val ); expected--; } assertTrue( list.isEmpty() ); } public void testPastIndexGet() { try { list.get( 0 ); fail( "Shouldn't have allowed get of index 0" ); } catch ( IndexOutOfBoundsException ex ) { // this is good } try { list.get( 1 ); fail( "Shouldn't have allowed get of index 1" ); } catch ( IndexOutOfBoundsException ex ) { // this is good } list.add( new Data( 1 ) ); list.get( 0 ); try { list.get( 1 ); fail( "Shouldn't have allowed get of index 1" ); } catch ( IndexOutOfBoundsException ex ) { // this is good } } public void testJDKIteratorSet2() { LinkedList list = new LinkedList(); list.add( new Data( 1 ) ); list.add( new Data( 9 ) ); list.add( new Data( 3 ) ); ListIterator it = ( ListIterator ) list.iterator(); assertEquals( 1, it.next()._val ); assertEquals( 9, it.next()._val ); it.set( new Data( 2 ) ); assertEquals( 3, it.next()._val ); assertEquals( 3, list.size() ); assertEquals( 1, list.get( 0 )._val ); assertEquals( 2, list.get( 1 )._val ); assertEquals( 3, list.get( 2 )._val ); } public void testIteratorSet2() { TLinkedList list = new TLinkedList(); list.add( new Data( 1 ) ); list.add( new Data( 9 ) ); list.add( new Data( 3 ) ); ListIterator it = ( ListIterator ) list.iterator(); assertEquals( 1, it.next()._val ); assertEquals( 9, it.next()._val ); it.set( new Data( 2 ) ); assertEquals( 3, it.next()._val ); assertEquals( 3, list.size() ); assertEquals( 1, list.get( 0 )._val ); assertEquals( 2, list.get( 1 )._val ); assertEquals( 3, list.get( 2 )._val ); } // See bug 2993599 public void testShuffle() { for( int loop = 0; loop < 10000; loop++ ) { if ( ( loop % 10000 ) ==0 ) System.out.println( "Loop: " + loop ); TLinkedList list = new TLinkedList(); list.add( new Data( 1 ) ); list.add( new Data( 2 ) ); list.add( new Data( 3 ) ); list.add( new Data( 4 ) ); list.add( new Data( 5 ) ); list.add( new Data( 6 ) ); list.add( new Data( 7 ) ); list.add( new Data( 8 ) ); list.add( new Data( 9 ) ); list.add( new Data( 10 ) ); Collections.shuffle( list ); assertEquals( 10, list.size() ); // Make sure all numbers are contained in the list exactly once for( int i = 1; i <= 10; i++ ) { boolean found_it = false; for( Data data : list ) { if ( data._val == i ) { assertFalse( "Number found twice: " + i, found_it ); found_it = true; } } assertTrue( "Number not found: " + i, found_it ); } } } public void testShuffle2() { Data data1 = new Data( 1 ); Data data2 = new Data( 2 ); Data data3 = new Data( 3 ); Data data4 = new Data( 4 ); Data data5 = new Data( 5 ); Data data6 = new Data( 6 ); Data data7 = new Data( 7 ); Data data8 = new Data( 8 ); Data data9 = new Data( 9 ); Data data10 = new Data( 10 ); TLinkedList list = new TLinkedList(); list.add( new Data( 1 ) ); list.add( new Data( 2 ) ); list.add( new Data( 3 ) ); list.add( new Data( 4 ) ); list.add( new Data( 5 ) ); list.add( new Data( 6 ) ); list.add( new Data( 7 ) ); list.add( new Data( 8 ) ); list.add( new Data( 9 ) ); list.add( new Data( 10 ) ); ListIterator it = ( ListIterator ) list.iterator(); it.next(); it.set( data10 ); } public void testFirstLastIteratorSwap() { Data data10 = new Data( 10 ); TLinkedList list = new TLinkedList(); list.add( new Data( 1 ) ); list.add( new Data( 2 ) ); list.add( new Data( 3 ) ); list.add( new Data( 4 ) ); list.add( new Data( 5 ) ); list.add( new Data( 6 ) ); list.add( new Data( 7 ) ); list.add( new Data( 8 ) ); list.add( new Data( 9 ) ); list.add( data10 ); ListIterator it = ( ListIterator ) list.iterator(); it.next(); it.set( data10 ); } public void testIteratorSwapSequential() { Data slot3 = new Data( 3 ); TLinkedList list = new TLinkedList(); list.add( new Data( 1 ) ); list.add( new Data( 2 ) ); list.add( slot3 ); list.add( new Data( 4 ) ); ListIterator it = ( ListIterator ) list.iterator(); it.next(); it.next(); it.set( slot3 ); } public void testBinarySearch() { System.out.println( "Java version: " + System.getProperty( "java.version" ) ); TIntList list; // Uncomment to stress test // for( int i = 0; i <= 100000; i++ ) { // if ( ( i % 100 ) == 0 ) { // System.out.print( i ); // System.out.print( " " ); // } // // list = new TIntArrayList( i ); // list.add( 5 ); // list.binarySearch( 6 ); // } list = new TIntLinkedList(); list.add( 5 ); // Uncomment this to see infinite loop from bug 3379877 // list.binarySearch( 6 ); assertEquals( -1, list.binarySearch( Integer.MIN_VALUE ) ); assertEquals( -1, list.binarySearch( -1 ) ); assertEquals( -1, list.binarySearch( 0 ) ); assertEquals( -1, list.binarySearch( 1 ) ); assertEquals( -1, list.binarySearch( 2 ) ); assertEquals( -1, list.binarySearch( 3 ) ); assertEquals( -1, list.binarySearch( 4 ) ); assertEquals( 0, list.binarySearch( 5 ) ); assertEquals( -2, list.binarySearch( 6 ) ); } public void testSum() { TIntList list = new TIntLinkedList(); assertEquals( 0, list.sum() ); list.add( 1 ); assertEquals( 1, list.sum() ); list.add( 1234 ); assertEquals( 1235, list.sum() ); list.removeAt( 0 ); assertEquals( 1234, list.sum() ); list.clear(); assertEquals( 0, list.sum() ); } static class Data implements TLinkable { protected int _val; public Data( int val ) { _val = val; } protected TLinkable _next; // NOTE: use covariant overriding /** * Get the value of next. * * @return value of next. */ public Data getNext() { return (Data) _next; } /** * Set the value of next. * * @param next value to assign to next. */ public void setNext( Data next ) { this._next = next; } protected Data _previous; // NOTE: use covariant overriding /** * Get the value of previous. * * @return value of previous. */ public Data getPrevious() { return _previous; } /** * Set the value of previous. * * @param previous value to assign to previous. */ public void setPrevious( Data previous ) { this._previous = previous; } public String toString() { return "" + _val; } public boolean equals( Object o ) { if ( !( o instanceof Data ) ) { return false; } Data that = (Data) o; return this._val == that._val; } } } // TLinkedListTests trove-3.0.3/test/gnu/trove/list/array/0000755000175000017500000000000012000515265016616 5ustar ericherichtrove-3.0.3/test/gnu/trove/list/array/TPrimitiveArrayListTest.java0000644000175000017500000013500611763017634024271 0ustar ericherichpackage gnu.trove.list.array; import gnu.trove.TIntCollection; import gnu.trove.function.TIntFunction; import gnu.trove.impl.Constants; import gnu.trove.iterator.TIntIterator; import gnu.trove.list.TIntList; import gnu.trove.procedure.TIntProcedure; import gnu.trove.set.TIntSet; import gnu.trove.set.hash.TIntHashSet; import junit.framework.TestCase; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.*; public class TPrimitiveArrayListTest extends TestCase { private TIntList list; public void setUp() throws Exception { super.setUp(); list = new TIntArrayList(); list.add( 1 ); list.add( 2 ); list.add( 3 ); list.add( 4 ); list.add( 5 ); } public void tearDown() throws Exception { super.tearDown(); } public void testGet() { assertEquals( 4, list.get( 3 ) ); try { list.get( 10 ); fail( "Expected IndexOutOfBoundsException" ); } catch ( IndexOutOfBoundsException ex ) { // Expected } int element_count = 10; TIntArrayList array_list = new TIntArrayList(); for ( int i = 1; i <= element_count; i++ ) { array_list.add( i ); } for ( int i = 0; i < array_list.size(); i++ ) { int expected = i + 1; assertEquals( expected, array_list.getQuick( i ) ); } try { array_list.getQuick( 100 ); fail( "Expected IndexOutOfBoundsException" ); } catch ( IndexOutOfBoundsException ex ) { // Expected } } public void testContains() { int element_count = 10; TIntList a = new TIntArrayList(); assertTrue( a.isEmpty() ); for ( int i = 1; i <= element_count; i++ ) { a.add( i ); } for ( int i = 1; i <= element_count; i++ ) { assertTrue( "element " + i + " not found in " + a, a.contains( i ) ); } assertFalse( "list doesn't hold MAX_VALUE: " + a, a.contains( Integer.MAX_VALUE ) ); } public void testInsert() { int element_count = 10; TIntList a = new TIntArrayList(); assertTrue( a.isEmpty() ); for ( int i = 1; i <= element_count; i++ ) { a.add( i ); } int testval = 1138; a.insert( 5, testval ); for ( int i = 0; i < 5; i++ ) { int result = a.get( i ); int expected = i + 1; assertTrue( "element " + result + " should be " + expected, result == expected ); } assertEquals( testval, a.get( 5 ) ); for ( int i = 6; i < a.size(); i++ ) { int result = a.get( i ); assertTrue( "element " + result + " should be " + i, result == i ); } } public void testInsertArray() { int element_count = 10; int[] ints = {1138, 42, 86, 99, 101}; TIntList a = new TIntArrayList(); assertTrue( a.isEmpty() ); for ( int i = 1; i <= element_count; i++ ) { a.add( i ); } a.insert( 0, ints ); assertEquals( ints.length + element_count, a.size() ); for ( int i = 0; i < ints.length; i++ ) { assertEquals( ints[i], a.get( i ) ); } for ( int i = ints.length, j = 1; i < ints.length + element_count; i++, j++ ) { assertEquals( j, a.get( i ) ); } } public void testInsertAtEnd() { int element_count = 10; TIntList a = new TIntArrayList(); assertTrue( a.isEmpty() ); for ( int i = 1; i <= element_count; i++ ) { a.add( i ); } a.insert( a.size(), 11 ); for ( int i = 0; i < element_count; i++ ) { assertEquals( i + 1, a.get( i ) ); } for ( int i = element_count; i < a.size(); i++ ) { int expected = i + 1; assertEquals( expected, a.get( i ) ); } } public void testInsertArrayAtEnd() { int element_count = 10; int[] ints = {1138, 42, 86, 99, 101}; TIntList a = new TIntArrayList(); assertTrue( a.isEmpty() ); for ( int i = 1; i <= element_count; i++ ) { a.add( i ); } a.insert( a.size(), ints ); for ( int i = 0; i < element_count; i++ ) { assertEquals( i + 1, a.get( i ) ); } for ( int i = element_count, j = 0; i < ints.length + element_count; i++, j++ ) { assertEquals( ints[j], a.get( i ) ); } } public void testSetArray() { int element_count = 10; int[] ints = {1138, 42, 86, 99, 101}; TIntList a = new TIntArrayList(); assertTrue( a.isEmpty() ); for ( int i = 1; i <= element_count; i++ ) { a.add( i ); } a.set( a.size() - ints.length, ints ); for ( int i = 0; i < element_count - ints.length; i++ ) { assertEquals( i + 1, a.get( i ) ); } for ( int i = element_count - ints.length, j = 0; i < a.size(); i++, j++ ) { assertEquals( ints[j], a.get( i ) ); } try { a.set( a.size(), ints ); fail( "Expected IndexOutOfBoundsException" ); } catch ( IndexOutOfBoundsException ex ) { // Expected } } public void testSet() { int element_count = 10; TIntList a = new TIntArrayList(); assertTrue( a.isEmpty() ); for ( int i = 1; i <= element_count; i++ ) { a.add( i ); } int testval = 1138; a.set( 5, testval ); for ( int i = 0; i < 5; i++ ) { int result = a.get( i ); int expected = i + 1; assertTrue( "element " + result + " should be " + expected, result == expected ); } assertEquals( testval, a.get( 5 ) ); for ( int i = 6; i < a.size(); i++ ) { int result = a.get( i ); int expected = i + 1; assertTrue( "element " + result + " should be " + expected, result == expected ); } try { a.set( 100, 20 ); fail( "Expected IndexOutOfBoundsException" ); } catch ( IndexOutOfBoundsException ex ) { // Expected } } public void testSetQuick() { int element_count = 10; TIntArrayList a = new TIntArrayList(); assertTrue( a.isEmpty() ); for ( int i = 1; i <= element_count; i++ ) { a.add( i ); } int testval = 1138; a.setQuick( 5, testval ); for ( int i = 0; i < 5; i++ ) { int result = a.get( i ); int expected = i + 1; assertTrue( "element " + result + " should be " + expected, result == expected ); } assertEquals( testval, a.get( 5 ) ); for ( int i = 6; i < a.size(); i++ ) { int result = a.get( i ); int expected = i + 1; assertTrue( "element " + result + " should be " + expected, result == expected ); } try { a.setQuick( 100, 20 ); fail( "Expected IndexOutOfBoundsException" ); } catch ( IndexOutOfBoundsException ex ) { // Expected } } public void testReplace() { int element_count = 10; TIntList a = new TIntArrayList(); assertTrue( a.isEmpty() ); for ( int i = 1; i <= element_count; i++ ) { a.add( i ); } int testval = 1138; assertEquals( 6, a.replace( 5, testval ) ); for ( int i = 0; i < 5; i++ ) { int result = a.get( i ); int expected = i + 1; assertTrue( "element " + result + " should be " + expected, result == expected ); } assertEquals( testval, a.get( 5 ) ); for ( int i = 6; i < a.size(); i++ ) { int result = a.get( i ); int expected = i + 1; assertTrue( "element " + result + " should be " + expected, result == expected ); } try { a.replace( 100, 20 ); fail( "Expected IndexOutOfBoundsException" ); } catch ( IndexOutOfBoundsException ex ) { // Expected } } public void testRemove() { int element_count = 10; TIntList a = new TIntArrayList(); assertTrue( a.isEmpty() ); for ( int i = 1; i <= element_count; i++ ) { a.add( i ); } assertEquals( 6, a.get( 5 ) ); assertTrue( a.remove( 5 ) ); for ( int i = 0; i < 4; i++ ) { int expected = i + 1; assertTrue( "index " + i + " expected " + expected, a.get( i ) == expected ); } for ( int i = 4; i < a.size(); i++ ) { int expected = i + 2; assertTrue( "index " + i + " expected " + expected, a.get( i ) == expected ); } // Can't remove again from THIS list because it's not present. assertFalse( a.remove( 5 ) ); assertEquals( 6, a.removeAt( 4 ) ); for ( int i = 0; i < 4; i++ ) { int expected = i + 1; assertTrue( "index " + i + " expected " + expected, a.get( i ) == expected ); } for ( int i = 4; i < a.size(); i++ ) { int expected = i + 3; assertTrue( "index " + i + " expected " + expected, a.get( i ) == expected ); } a.insert( 4, 6 ); // Add a value twice, can remove it twice assertTrue( a.add( 5 ) ); assertTrue( a.add( 5 ) ); assertTrue( a.remove( 5 ) ); assertTrue( a.remove( 5 ) ); assertFalse( a.remove( 5 ) ); a.insert( 4, 5 ); assertTrue( a.add( 5 ) ); for ( int i = 0; i < 5; i++ ) { int expected = i + 1; assertTrue( "index " + i + " expected " + expected, a.get( i ) == expected ); } for ( int i = 5; i < a.size() - 1; i++ ) { int expected = i + 1; assertTrue( "index " + i + " expected " + expected + ", list: " + a, a.get( i ) == expected ); } assertEquals( 5, a.get( a.size() - 1 ) ); assertTrue( a.remove( 5 ) ); assertEquals( element_count, a.size() ); for ( int i = 0; i < 4; i++ ) { int expected = i + 1; assertTrue( "index " + i + " expected " + expected, a.get( i ) == expected ); } for ( int i = 4; i < a.size() - 1; i++ ) { int expected = i + 2; assertTrue( "index " + i + " expected " + expected, a.get( i ) == expected ); } assertEquals( 5, a.get( a.size() - 1 ) ); } public void testRemoveMultiple() { int element_count = 20; TIntList a = new TIntArrayList(); assertTrue( a.isEmpty() ); for ( int i = 1; i <= element_count; i++ ) { a.add( i ); } // Remove odd offsets, which are even numbers. for ( int i = element_count; i >= 0; i-- ) { if ( i % 2 == 1 ) { a.removeAt( i ); } } for ( int i = 0; i < a.size(); i++ ) { int expected = i * 2 + 1; assertTrue( "index " + i + " expected " + expected, a.get( i ) == expected ); } } public void testRemoveChunk() { int element_count = 20; TIntList a = new TIntArrayList(); assertTrue( a.isEmpty() ); for ( int i = 1; i <= element_count; i++ ) { a.add( i ); } a.remove( 5, 10 ); for ( int i = 0; i < 5; i++ ) { int expected = i + 1; assertTrue( "index " + i + " expected " + expected, a.get( i ) == expected ); } for ( int i = 5; i < a.size(); i++ ) { int expected = i + 11; assertTrue( "index " + i + " expected " + expected + " but got " + a.get( i ), a.get( i ) == expected ); } try { a.remove( -1, 10 ); fail( "Expected ArrayIndexOutOfBoundsException" ); } catch ( ArrayIndexOutOfBoundsException ex ) { // Expected } try { a.remove( a.size(), 1 ); fail( "Expected ArrayIndexOutOfBoundsException" ); } catch ( ArrayIndexOutOfBoundsException ex ) { // Expected } } public void testContainsAllCollection() { int element_count = 20; SortedSet set = new TreeSet(); for ( int i = 0; i < element_count; i++ ) { set.add( Integer.valueOf( i ) ); } TIntArrayList list = new TIntArrayList( 20 ); for ( int i = 0; i < element_count; i++ ) { list.add( i ); } assertTrue( "list: " + list + " should contain all of set: " + set, list.containsAll( set ) ); set.remove( element_count ); assertTrue( "list: " + list + " should contain all of set: " + set, list.containsAll( set ) ); list.remove( 5 ); assertFalse( "list: " + list + " should not contain all of set: " + set, list.containsAll( set ) ); list.add( 5 ); // Test when not all objects are Integers.. Set obj_set = new HashSet(); for ( int i = 0; i < element_count; i++ ) { if ( i != 5 ) { obj_set.add( Integer.valueOf( i ) ); } else { obj_set.add( Long.valueOf( ( long ) i ) ); } } assertFalse( "list should not contain all of obj_set", list.containsAll( obj_set ) ); } public void testContainsAllTCollection() { int element_count = 20; TIntArrayList list = new TIntArrayList( element_count * 2 ); for ( int i = 0; i < element_count; i++ ) { list.add( i ); } TIntArrayList other = new TIntArrayList( list ); assertEquals( element_count, list.size() ); assertEquals( element_count, other.size() ); assertEquals( list, other ); assertTrue( "list should contain all of itself: " + list, list.containsAll( list ) ); assertTrue( "list should contain all of equal list " + list + ", " + other, list.containsAll( other ) ); for ( int i = 0; i < other.size(); i++ ) { if ( i % 2 == 0 ) { other.removeAt( i ); } } assertTrue( "list: " + list + " should contain all of other: " + other, list.containsAll( other ) ); other.add( 1138 ); assertFalse( "list: " + list + " should not contain all of other: " + other, list.containsAll( other ) ); TIntSet set = new TIntHashSet( list ); assertTrue( "list: " + list + " should contain all of set: " + set, list.containsAll( set ) ); set.add ( 1138 ); assertFalse( "list: " + list + " should not contain all of set: " + set, list.containsAll( set ) ); } public void testContainsAllArray() { int element_count = 20; int[] ints = new int[element_count]; TIntArrayList list = new TIntArrayList( element_count * 2 ); for ( int i = 0; i < element_count; i++ ) { ints[i] = i; list.add( i ); } assertTrue( "list: " + list + " should contain all of array: " + Arrays.toString( ints ), list.containsAll( ints ) ); ints[5] = 1138; assertFalse( "list: " + list + " should cnot ontain all of array: " + Arrays.toString( ints ), list.containsAll( ints ) ); } public void testAddAllCollection() { int element_count = 20; SortedSet set = new TreeSet(); for ( int i = 0; i < element_count; i++ ) { set.add( Integer.valueOf( i ) ); } TIntArrayList list = new TIntArrayList( 20 ); for ( int i = 0; i < element_count; i++ ) { list.add( i ); } assertEquals( element_count, set.size() ); assertEquals( element_count, list.size() ); list.addAll( set ); assertEquals( element_count * 2, list.size() ); for ( int i = 0; i < list.size(); i++ ) { int expected; if ( i < element_count ) { expected = i; } else { expected = i - element_count; } assertEquals( expected , list.get( i ) ); } } public void testAddAllTCollection() { int element_count = 20; TIntArrayList source = new TIntArrayList(); for ( int i = 0; i < element_count; i++ ) { source.add( Integer.valueOf( i ) ); } TIntArrayList list = new TIntArrayList( 20 ); for ( int i = 0; i < element_count; i++ ) { list.add( i ); } assertEquals( element_count, source.size() ); assertEquals( element_count, list.size() ); list.addAll( source ); assertEquals( element_count * 2, list.size() ); for ( int i = 0; i < list.size(); i++ ) { int expected; if ( i < element_count ) { expected = i; } else { expected = i - element_count; } assertEquals( expected , list.get( i ) ); } } public void testAddAllArray() { int element_count = 20; int[] ints = new int[element_count]; TIntArrayList list = new TIntArrayList(); for ( int i = 0; i < element_count; i++ ) { ints[i] = i; list.add( Integer.valueOf( i ) ); } assertEquals( element_count, list.size() ); assertTrue ( list.addAll( ints ) ); assertEquals( element_count * 2, list.size() ); for ( int i = 0; i < list.size(); i++ ) { int expected; if ( i < element_count ) { expected = i; } else { expected = i - element_count; } assertEquals( "expected: " + expected + ", got: " + list.get( i ) + ", list: " + list + ", array: " + Arrays.toString( ints ), expected , list.get( i ) ); } } public void testRetainAllCollection() { int element_count = 20; SortedSet set = new TreeSet(); for ( int i = 0; i < element_count; i++ ) { set.add( Integer.valueOf( i ) ); } TIntList list = new TIntArrayList( 20 ); for ( int i = 0; i < element_count; i++ ) { list.add( i ); } assertEquals( element_count, set.size() ); assertEquals( element_count, list.size() ); assertFalse( list.retainAll( set ) ); assertEquals( element_count, list.size() ); for ( int i = 0; i < list.size(); i++ ) { assertEquals( i , list.get( i ) ); } set.remove( 0 ); set.remove( 5 ); set.remove( 10 ); set.remove( 15 ); assertTrue( list.retainAll( set ) ); int expected = element_count - 4; assertEquals( "expected: " + expected + ", was: " + list.size() + ", list: " + list , expected, list.size() ); for ( int i = 0; i < list.size(); i++ ) { expected = ( int ) Math.floor( i / 4 ) + i + 1; assertEquals( "expected: " + expected + ", was: " + list.get( i ) + ", list: " + list, expected , list.get( i ) ); } } public void testRetainAllTCollection() { int element_count = 20; TIntList other = new TIntArrayList(); for ( int i = 0; i < element_count; i++ ) { other.add( i ); } TIntList list = new TIntArrayList( 20 ); for ( int i = 0; i < element_count; i++ ) { list.add( i ); } assertEquals( element_count, list.size() ); assertEquals( element_count, other.size() ); assertFalse( list.retainAll( list ) ); assertFalse( list.retainAll( other ) ); assertEquals( element_count, list.size() ); for ( int i = 0; i < list.size(); i++ ) { assertEquals( i , list.get( i ) ); } other.remove( 0 ); other.remove( 5 ); other.remove( 10 ); other.remove( 15 ); assertTrue( list.retainAll( other ) ); int expected = element_count - 4; assertEquals( expected, list.size() ); for ( int i = 0; i < list.size(); i++ ) { expected = ( int ) Math.floor( i / 4 ) + i + 1; assertEquals( "expected: " + expected + ", was: " + list.get( i ) + ", list: " + list, expected , list.get( i ) ); } } public void testRetainAllArray() { int element_count = 20; int ints[] = new int[element_count]; for ( int i = 0; i < element_count; i++ ) { ints[i] = i; } TIntList list = new TIntArrayList( 20 ); for ( int i = 0; i < element_count; i++ ) { list.add( i ); } assertEquals( element_count, list.size() ); assertFalse( list.retainAll( ints ) ); assertEquals( element_count, list.size() ); for ( int i = 0; i < list.size(); i++ ) { assertEquals( i , list.get( i ) ); } ints = new int[( element_count - 4 )] ; for ( int i = 0, j = 0; i < ints.length; i++, j++ ) { if ( i % 4 == 0 ) { j++; } ints[i] = j; } assertTrue( list.retainAll( ints ) ); int expected = element_count - 4; assertEquals( expected, list.size() ); for ( int i = 0; i < list.size(); i++ ) { expected = ( int ) Math.floor( i / 4 ) + i + 1; assertEquals( "expected: " + expected + ", was: " + list.get( i ) + ", list: " + list, expected , list.get( i ) ); } } public void testRemoveAllCollection() { int element_count = 20; SortedSet set = new TreeSet(); for ( int i = 0; i < element_count; i++ ) { set.add( Integer.valueOf( i ) ); } TIntList list = new TIntArrayList( 20 ); for ( int i = 0; i < element_count; i++ ) { list.add( i ); } assertEquals( element_count, set.size() ); assertEquals( element_count, list.size() ); assertTrue( list.removeAll( set ) ); assertTrue( list.isEmpty() ); assertEquals( 0, list.size() ); assertEquals( element_count, set.size() ); for ( int i = 0; i < set.size(); i++ ) { assertTrue( set.contains( Integer.valueOf( i ) ) ); } // Reset the list list = new TIntArrayList( 20 ); for ( int i = 0; i < element_count; i++ ) { list.add( i ); } set.remove( 0 ); set.remove( 5 ); set.remove( 10 ); set.remove( 15 ); assertTrue( list.removeAll( set ) ); int expected = 4; assertEquals( "expected: " + expected + ", was: " + list.size() + ", list: " + list , expected, list.size() ); for ( int i = 0; i < list.size(); i++ ) { expected = i * 5; assertEquals( "expected: " + expected + ", was: " + list.get( i ) + ", list: " + list, expected , list.get( i ) ); } } public void testRemoveAllTCollection() { int element_count = 20; TIntList other = new TIntArrayList(); for ( int i = 0; i < element_count; i++ ) { other.add( i ); } TIntList list = new TIntArrayList( 20 ); for ( int i = 0; i < element_count; i++ ) { list.add( i ); } assertEquals( element_count, list.size() ); assertEquals( element_count, other.size() ); assertTrue( list.removeAll( list ) ); assertEquals( 0, list.size() ); assertTrue( list.isEmpty() ); // Reset the list list = new TIntArrayList( 20 ); for ( int i = 0; i < element_count; i++ ) { list.add( i ); } assertTrue( list.removeAll( other ) ); assertEquals( 0, list.size() ); assertTrue( list.isEmpty() ); for ( int i = 0; i < list.size(); i++ ) { assertEquals( i , list.get( i ) ); } // Reset the list list = new TIntArrayList( 20 ); for ( int i = 0; i < element_count; i++ ) { list.add( i ); } other.remove( 0 ); other.remove( 5 ); other.remove( 10 ); other.remove( 15 ); assertTrue( list.removeAll( other ) ); int expected = 4; assertEquals( "expected: " + expected + ", was: " + list.size() + ", list: " + list , expected, list.size() ); for ( int i = 0; i < list.size(); i++ ) { expected = i * 5; assertEquals( "expected: " + expected + ", was: " + list.get( i ) + ", list: " + list, expected , list.get( i ) ); } } public void testRemoveAllArray() { int element_count = 20; int ints[] = new int[element_count]; for ( int i = 0; i < element_count; i++ ) { ints[i] = i; } TIntList list = new TIntArrayList( 20 ); for ( int i = 0; i < element_count; i++ ) { list.add( i ); } assertEquals( element_count, list.size() ); assertTrue( list.removeAll( ints ) ); assertEquals( 0, list.size() ); assertTrue( list.isEmpty() ); // Reset the list list = new TIntArrayList( 20 ); for ( int i = 0; i < element_count; i++ ) { list.add( i ); } ints = new int[( element_count - 4 )] ; for ( int i = 0, j = 0; i < ints.length; i++, j++ ) { if ( i % 4 == 0 ) { j++; } ints[i] = j; } assertTrue( list.removeAll( ints ) ); int expected = 4; assertEquals( expected, list.size() ); for ( int i = 0; i < list.size(); i++ ) { expected = i * 5; assertEquals( "expected: " + expected + ", was: " + list.get( i ) + ", list: " + list, expected , list.get( i ) ); } } public void testShuffle() { int element_count = 20; TIntList list = new TIntArrayList( 20 ); for ( int i = 0; i < element_count; i++ ) { list.add( i ); } list.shuffle( new Random( System.currentTimeMillis() ) ); for ( int i = 0; i < list.size(); i++ ) { assertTrue( list.contains( i ) ); } } public void testIterator() { int element_count = 20; TIntList list = new TIntArrayList(); for ( int i = 0; i < element_count; i++ ) { list.add( i ); } TIntIterator iter = list.iterator(); assertTrue( "iter should have next: " + list.size(), iter.hasNext() ); int j = 0; while ( iter.hasNext() ) { int next = iter.next(); assertEquals( j, next ); j++; } assertFalse( iter.hasNext() ); iter = list.iterator(); for ( int i = 0; i < element_count / 2; i++ ) { iter.next(); } iter.remove(); try { // trying to remove it again should fail. iter.remove(); fail( "Expected IllegalStateException" ); } catch ( IllegalStateException ex ) { // Expected } for ( int i = 0; i < element_count / 2 - 1; i++ ) { iter.next(); } } public void testIteratorAbuseNext() { int element_count = 20; TIntList list = new TIntArrayList(); for ( int i = 0; i < element_count; i++ ) { list.add( i ); } TIntIterator iter = list.iterator(); while ( iter.hasNext() ) { iter.next(); } assertFalse( iter.hasNext() ); list.remove( 5, 10 ); assertFalse( iter.hasNext() ); try { iter.next(); fail( "Expected NoSuchElementException" ); } catch( NoSuchElementException ex ) { // Expected. } } public void testIteratorAbuseRemove() { int element_count = 20; TIntList list = new TIntArrayList(); for ( int i = 0; i < element_count; i++ ) { list.add( i ); } TIntIterator iter = list.iterator(); while ( iter.hasNext() ) { iter.next(); } assertFalse( iter.hasNext() ); list.remove( 5, 10 ); assertFalse( iter.hasNext() ); try { iter.remove(); fail( "Expected ConcurrentModificationException" ); } catch( ConcurrentModificationException ex ) { // Expected. } } public void testEnsureCapacity() { int size = 1000; TIntArrayList array_list = new TIntArrayList(); int initial_length = array_list._data.length; assertEquals( Constants.DEFAULT_CAPACITY, initial_length ); array_list.ensureCapacity( size ); int max_length = array_list._data.length; assertTrue( "not large enough: " + max_length + " should be >= " + size, max_length >= size ); } public void testTrimToSize() { int initial_size = 1000; int element_count = 100; TIntArrayList array_list = new TIntArrayList( initial_size ); int initial_length = array_list._data.length; assertEquals( initial_size, initial_length ); assertTrue( array_list.isEmpty() ); for ( int i = 1; i <= element_count; i++ ) { array_list.add( i ); } array_list.trimToSize(); int trimmed_length = array_list._data.length; assertTrue( "not trimmed: " + trimmed_length + " should be == " + element_count, trimmed_length == element_count ); } public void testToArray() { assertTrue( Arrays.equals( new int[]{1, 2, 3, 4, 5}, list.toArray() ) ); assertTrue( Arrays.equals( new int[]{1, 2, 3, 4}, list.toArray( 0, 4 ) ) ); assertTrue( Arrays.equals( new int[]{2, 3, 4, 5}, list.toArray( 1, 4 ) ) ); assertTrue( Arrays.equals( new int[]{2, 3, 4}, list.toArray( 1, 3 ) ) ); try { list.toArray( -1, 5 ); fail( "Expected ArrayIndexOutOfBoundsException when begin < 0" ); } catch ( ArrayIndexOutOfBoundsException expected ) { // Expected } } public void testToArrayWithDest() { int[] dest = new int[5]; assertTrue( Arrays.equals( new int[]{1, 2, 3, 4, 5}, list.toArray( dest ) ) ); dest = new int[4]; assertTrue( Arrays.equals( new int[]{1, 2, 3, 4}, list.toArray( dest, 0, 4 ) ) ); dest = new int[4]; assertTrue( Arrays.equals( new int[]{2, 3, 4, 5}, list.toArray( dest, 1, 4 ) ) ); dest = new int[3]; assertTrue( Arrays.equals( new int[]{2, 3, 4}, list.toArray( dest, 1, 3 ) ) ); try { list.toArray( dest, -1, 5 ); fail( "Expected ArrayIndexOutOfBoundsException when begin < 0" ); } catch ( ArrayIndexOutOfBoundsException expected ) { // Expected } } public void testToArrayWithDestTarget() { int[] dest = new int[5]; assertTrue( Arrays.equals( new int[]{1, 2, 3, 4, 5}, list.toArray( dest ) ) ); dest = new int[4]; assertTrue( Arrays.equals( new int[]{1, 2, 3, 4}, list.toArray( dest, 0, 0, 4 ) ) ); dest = new int[5]; assertTrue( Arrays.equals( new int[]{0, 2, 3, 4, 5}, list.toArray( dest, 1, 1, 4 ) ) ); dest = new int[4]; assertTrue( Arrays.equals( new int[]{0, 2, 3, 4}, list.toArray( dest, 1, 1, 3 ) ) ); dest = new int[5]; assertTrue( Arrays.equals( new int[]{0, 0, 0, 0, 0}, list.toArray( dest, 0, 0, 0 ) ) ); try { list.toArray( dest, -1, 0, 5 ); fail( "Expected ArrayIndexOutOfBoundsException when begin < 0" ); } catch ( ArrayIndexOutOfBoundsException expected ) { // Expected } } public void testSubList() throws Exception { TIntList subList = list.subList( 1, 4 ); assertEquals( 3, subList.size() ); assertEquals( 2, subList.get( 0 ) ); assertEquals( 4, subList.get( 2 ) ); } public void testSublist_Exceptions() { try { list.subList( 1, 0 ); fail( "expected IllegalArgumentException when end < begin" ); } catch ( IllegalArgumentException expected ) { } try { list.subList( -1, 3 ); fail( "expected IndexOutOfBoundsException when begin < 0" ); } catch ( IndexOutOfBoundsException expected ) { } try { list.subList( 1, 42 ); fail( "expected IndexOutOfBoundsException when end > length" ); } catch ( IndexOutOfBoundsException expected ) { } } public void testIndexOf() { int element_count = 20; TIntList a = new TIntArrayList(); for ( int i = 1; i <= element_count; i++ ) { a.add( i ); } int index = a.indexOf( 10 ); assertEquals( 9, index ); // Add more elements, but duplicates for ( int i = 1; i <= element_count; i++ ) { a.add( i ); } index = a.indexOf( 10 ); assertEquals( 9, index ); index = a.indexOf( 5 ); assertEquals( 4, index ); index = a.lastIndexOf( 5 ); assertEquals( 24, index ); // Non-existant entry index = a.indexOf( 100 ); assertEquals( -1, index ); } public void testBinarySearch() { int element_count = 20; TIntList a = new TIntArrayList(); for ( int i = 1; i <= element_count; i++ ) { a.add( i ); } a.sort(); int index = a.binarySearch( 5 ); assertEquals( 4, index ); index = a.binarySearch( 8 ); assertEquals( 7, index ); // Add more elements, but duplicates for ( int i = 1; i <= element_count; i++ ) { a.add( i ); } a.sort(); index = a.indexOf( 5 ); assertTrue( "index: " + index, index >= 8 && index <= 9 ); // Not in this range. index = a.binarySearch( 5, 15, 30 ); assertTrue( "index: " + index, index < 0 ); try { a.binarySearch( 5, 10, 55 ); fail( "Expected ArrayIndexOutOfBoundsException" ); } catch ( ArrayIndexOutOfBoundsException ex ) { // Expected } try { a.binarySearch( 5, -1, 15 ); fail( "Expected ArrayIndexOutOfBoundsException" ); } catch ( ArrayIndexOutOfBoundsException ex ) { // Expected } } public void testFill() { int element_count = 20; TIntList a = new TIntArrayList(); for ( int i = 1; i <= element_count; i++ ) { a.add( i ); } a.fill( 0xdeadbeef ); for ( int i = 0; i < element_count; i++ ) { assertEquals( 0xdeadbeef, a.get( i ) ); } } public void testFillOffsets() { int element_count = 20; TIntList a = new TIntArrayList(); for ( int i = 1; i <= element_count; i++ ) { a.add( i ); } a.fill( 10, 15, 0xdeadbeef ); for ( int i = 0; i < 10; i++ ) { assertEquals( i + 1, a.get( i ) ); } for ( int i = 10; i < 15; i++ ) { assertEquals( 0xdeadbeef, a.get( i ) ); } for ( int i = 15; i < a.size(); i++ ) { assertEquals( i + 1, a.get( i ) ); } a.fill( 15, 25, 0xcafebabe ); assertEquals( 25, a.size() ); for ( int i = 0; i < 10; i++ ) { assertEquals( i + 1, a.get( i ) ); } for ( int i = 10; i < 15; i++ ) { assertEquals( 0xdeadbeef, a.get( i ) ); } for ( int i = 15; i < a.size(); i++ ) { assertEquals( 0xcafebabe, a.get( i ) ); } } public void testReset() { int element_count = 20; TIntArrayList a = new TIntArrayList( 20, Integer.MIN_VALUE ); for ( int i = 1; i <= element_count; i++ ) { a.add( i ); } assertEquals( element_count, a.size() ); a.reset(); assertEquals( 0, a.size() ); for ( int i = 0; i < element_count; i++ ) { int expected = a.getQuick( i ); assertTrue( "index " + i + " is " + expected, a.getNoEntryValue() == expected ); } } public void testGrep() { int element_count = 20; TIntList a = new TIntArrayList(); for ( int i = 1; i < element_count; i++ ) { a.add( i ); } TIntList grepped = a.grep( new TIntProcedure() { public boolean execute( int value ) { return value > 10; } } ); for ( int i = 0; i < grepped.size(); i++ ) { int expected = i + 11; assertEquals( expected, grepped.get( i ) ); } } public void testInverseGrep() { int element_count = 20; TIntList a = new TIntArrayList(); for ( int i = 1; i < element_count; i++ ) { a.add( i ); } TIntList grepped = a.inverseGrep( new TIntProcedure() { public boolean execute( int value ) { return value <= 10; } } ); for ( int i = 0; i < grepped.size(); i++ ) { int expected = i + 11; assertEquals( expected, grepped.get( i ) ); } } public void testMax() { assertEquals( 5, list.max() ); assertEquals( 1, list.min() ); TIntList list2 = new TIntArrayList(); assertTrue( list2.isEmpty() ); list2.add( 3 ); list2.add( 1 ); list2.add( 2 ); list2.add( 5 ); list2.add( 4 ); assertEquals( 5, list2.max() ); assertEquals( 1, list2.min() ); try { TIntList list3 = new TIntArrayList(); list3.min(); fail( "Expected IllegalStateException" ); } catch ( IllegalStateException ex ) { // Expected } try { TIntList list3 = new TIntArrayList(); list3.max(); fail( "Expected IllegalStateException" ); } catch ( IllegalStateException ex ) { // Expected } } public void testForEach() { int element_count = 20; TIntList a = new TIntArrayList(); for ( int i = 1; i < element_count; i++ ) { a.add( i ); } class ForEach implements TIntProcedure { TIntList built = new TIntArrayList(); public boolean execute( int value ) { built.add( value ); return true; } TIntList getBuilt() { return built; } } ForEach foreach = new ForEach(); a.forEach( foreach ); TIntList built = foreach.getBuilt(); assertEquals( a, built ); } public void testForEachFalse() { int element_count = 20; TIntList a = new TIntArrayList(); for ( int i = 1; i < element_count; i++ ) { a.add( i ); } class ForEach implements TIntProcedure { TIntList built = new TIntArrayList(); public boolean execute( int value ) { built.add( value ); return false; } TIntList getBuilt() { return built; } } ForEach foreach = new ForEach(); a.forEach( foreach ); TIntList built = foreach.getBuilt(); assertEquals( 1, built.size() ); assertEquals( 1, built.get( 0 ) ); } public void testForEachDescending() { int element_count = 20; TIntList a = new TIntArrayList(); for ( int i = 1; i < element_count; i++ ) { a.add( i ); } class ForEach implements TIntProcedure { TIntList built = new TIntArrayList(); public boolean execute( int value ) { built.add( value ); return true; } TIntList getBuilt() { return built; } } ForEach foreach = new ForEach(); a.forEachDescending( foreach ); TIntList built = foreach.getBuilt(); built.reverse(); assertEquals( a, built ); } public void testForEachDescendingFalse() { int element_count = 20; TIntList a = new TIntArrayList(); for ( int i = 1; i < element_count; i++ ) { a.add( i ); } class ForEach implements TIntProcedure { TIntList built = new TIntArrayList(); public boolean execute( int value ) { built.add( value ); return false; } TIntList getBuilt() { return built; } } ForEach foreach = new ForEach(); a.forEachDescending( foreach ); TIntList built = foreach.getBuilt(); built.reverse(); assertEquals( 1, built.size() ); assertEquals( 19, built.get( 0 ) ); } public void testTransform() { int element_count = 20; TIntList a = new TIntArrayList(); for ( int i = 1; i < element_count; i++ ) { a.add( i ); } a.transformValues( new TIntFunction() { public int execute( int value ) { return value * value; } } ); for ( int i = 0; i < a.size(); i++ ) { int result = a.get( i ); int expected = ( i + 1 ) * ( i + 1 ); assertEquals( expected, result ); } } public void testReverse() { int element_count = 20; TIntList a = new TIntArrayList(); for ( int i = 1; i <= element_count; i++ ) { a.add( i ); } a.reverse(); for ( int i = 0, j = a.size(); i < a.size(); i++, j-- ) { assertEquals( j, a.get( i ) ); } } public void testReversePartial() { int element_count = 20; TIntList a = new TIntArrayList(); for ( int i = 1; i <= element_count; i++ ) { a.add( i ); } a.reverse( 1, 19 ); int[] expected = {1, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 20}; for ( int i = 0; i < a.size(); i++ ) { assertEquals( expected[i], a.get( i ) ); } try { a.reverse( 20, 10 ); fail( "Expected IllegalArgumentException" ); } catch ( IllegalArgumentException ex ) { // Expected } } public void testSortPartial() { int element_count = 20; TIntList a = new TIntArrayList(); for ( int i = 1; i <= element_count; i++ ) { a.add( i ); } a.reverse(); a.sort( 5, 15 ); int[] expected = {20, 19, 18, 17, 16, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 5, 4, 3, 2, 1}; for ( int i = 0; i < a.size(); i++ ) { assertEquals( expected[i], a.get( i ) ); } try { a.sort( 20, 10 ); fail( "Expected IllegalArgumentException" ); } catch ( IllegalArgumentException ex ) { // Expected } } public void testEquals() { int element_count = 20; TIntList list = new TIntArrayList(); for ( int i = 1; i <= element_count; i++ ) { list.add( i ); } assertEquals( list, list ); assertEquals( list, new TIntArrayList( list ) ); TIntCollection collection = new TIntHashSet(); for ( int i = 1; i <= element_count; i++ ) { collection.add( i ); } assertFalse( list.equals( collection ) ); collection.add( 1138 ); assertFalse( list.equals( collection ) ); TIntList other = new TIntArrayList( list ); other.replace( 10, 1138 ); assertFalse( list.equals( other ) ); } public void testSerialization() throws Exception { ByteArrayOutputStream bout = new ByteArrayOutputStream(); ObjectOutputStream oout = new ObjectOutputStream( bout ); oout.writeObject( list ); oout.close(); ObjectInputStream oin = new ObjectInputStream( new ByteArrayInputStream( bout.toByteArray() ) ); TIntArrayList new_list = (TIntArrayList) oin.readObject(); assertEquals( list, new_list ); } } trove-3.0.3/test/gnu/trove/list/array/TArrayListTest.java0000644000175000017500000002133311763017634022375 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001, Eric D. Friedman All Rights Reserved. // Copyright (c) 2009, Rob Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.list.array; import gnu.trove.list.TIntList; import junit.framework.TestCase; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Arrays; public class TArrayListTest extends TestCase { private TIntList list; public void setUp() throws Exception { super.setUp(); list = new TIntArrayList(15, Integer.MIN_VALUE); list.add(1); list.add(2); list.add(3); list.add(4); list.add(5); } public void tearDown() throws Exception { super.tearDown(); } public void testToArray() { assertTrue(Arrays.equals(new int[]{1, 2, 3, 4, 5}, list.toArray())); assertTrue(Arrays.equals(new int[]{1, 2, 3, 4}, list.toArray(0, 4))); assertTrue(Arrays.equals(new int[]{2, 3, 4, 5}, list.toArray(1, 4))); assertTrue(Arrays.equals(new int[]{2, 3, 4}, list.toArray(1, 3))); int[] array_correct_size = new int[5]; list.toArray(array_correct_size); assertEquals(1, array_correct_size[0]); assertEquals(2, array_correct_size[1]); assertEquals(3, array_correct_size[2]); assertEquals(4, array_correct_size[3]); assertEquals(5, array_correct_size[4]); assertEquals(array_correct_size.length, list.size()); int[] array_too_long = new int[8]; list.toArray(array_too_long); assertEquals(1, array_too_long[0]); assertEquals(2, array_too_long[1]); assertEquals(3, array_too_long[2]); assertEquals(4, array_too_long[3]); assertEquals(5, array_too_long[4]); assertEquals(list.getNoEntryValue(), array_too_long[5]); int[] array_too_short = new int[2]; list.toArray(array_too_short); assertEquals(1, array_too_short[0]); assertEquals(2, array_too_short[1]); } public void testSubList() throws Exception { TIntList subList = list.subList(1, 4); assertEquals(3, subList.size()); assertEquals(2, subList.get(0)); assertEquals(4, subList.get(2)); } public void testSublist_Exceptions() { try { list.subList(1, 0); fail("expected IllegalArgumentException when end < begin"); } catch (IllegalArgumentException expected) { } try { list.subList(-1, 3); fail("expected IndexOutOfBoundsException when begin < 0"); } catch (IndexOutOfBoundsException expected) { } try { list.subList(1, 42); fail("expected IndexOutOfBoundsException when end > length"); } catch (IndexOutOfBoundsException expected) { } } public void testMax() { assertEquals(5, list.max()); assertEquals(1, list.min()); TIntArrayList list2 = new TIntArrayList(); list2.add(3); list2.add(1); list2.add(2); list2.add(5); list2.add(4); assertEquals(5, list2.max()); assertEquals(1, list2.min()); } public void testSerialization() throws Exception { ByteArrayOutputStream bout = new ByteArrayOutputStream(); ObjectOutputStream oout = new ObjectOutputStream(bout); oout.writeObject(list); oout.close(); ObjectInputStream oin = new ObjectInputStream( new ByteArrayInputStream(bout.toByteArray())); TIntArrayList new_list = (TIntArrayList) oin.readObject(); assertEquals(list, new_list); } // From bug 3077245 public void testInvalidStartRemoveZeroLength() { try { TIntArrayList bug = new TIntArrayList(); bug.remove(0, 0); } catch (ArrayIndexOutOfBoundsException ex) { ex.printStackTrace(); fail("Shouldn't raise exception"); } } // From bug 3197201 public void testListRemove() { // Remove by value TIntArrayList list = new TIntArrayList(); list.add(0); list.add(1); list.add(2); list.remove(1); assertEquals(2, list.size()); assertEquals(0, list.get(0)); assertEquals(2, list.get(1)); // Remove by position with range list = new TIntArrayList(); list.add(0); list.add(1); list.add(2); list.remove(1, 1); assertEquals(2, list.size()); assertEquals(0, list.get(0)); assertEquals(2, list.get(1)); // Remove by position, no range list = new TIntArrayList(); list.add(0); list.add(1); list.add(2); list.removeAt(1); assertEquals(2, list.size()); assertEquals(0, list.get(0)); assertEquals(2, list.get(1)); // Remove by value (ensure no collision) list = new TIntArrayList(); list.add(10); list.add(11); list.add(12); list.remove(11); assertEquals(2, list.size()); assertEquals(10, list.get(0)); assertEquals(12, list.get(1)); } public void testSum() { TIntList list = new TIntArrayList(); assertEquals(0, list.sum()); list.add(1); assertEquals(1, list.sum()); list.add(1234); assertEquals(1235, list.sum()); list.removeAt(0); assertEquals(1234, list.sum()); list.clear(); assertEquals(0, list.sum()); } public void testBinarySearch() { System.out.println("Java version: " + System.getProperty("java.version")); TIntList list; for (int i = 0; i <= 100000; i++) { if ((i % 100) == 0) { System.out.print(i); System.out.print(" "); } list = new TIntArrayList(i); list.add(5); list.binarySearch(6); } list = new TIntArrayList(); list.add(5); assertEquals(-1, list.binarySearch(Integer.MIN_VALUE)); assertEquals(-1, list.binarySearch(-1)); assertEquals(-1, list.binarySearch(0)); assertEquals(-1, list.binarySearch(1)); assertEquals(-1, list.binarySearch(2)); assertEquals(-1, list.binarySearch(3)); assertEquals(-1, list.binarySearch(4)); assertEquals(0, list.binarySearch(5)); assertEquals(-2, list.binarySearch(6)); } public void testListWrapExpand() { // Remove by value TIntArrayList list = TIntArrayList.wrap(new int[]{1, 0, 2}); try { list.add(0); fail(); } catch (Exception expected) { } } public void testListWrap() { // Remove by value TIntArrayList list = TIntArrayList.wrap(new int[]{1, 0, 2}); list.remove(1); assertEquals(2, list.size()); assertEquals(0, list.get(0)); assertEquals(2, list.get(1)); list.add(1); assertEquals(3, list.size()); assertEquals(0, list.get(0)); assertEquals(2, list.get(1)); assertEquals(1, list.get(2)); list.fill(5); assertEquals(3, list.size()); assertEquals(5, list.get(0)); assertEquals(5, list.get(1)); assertEquals(5, list.get(2)); } public void test3448111() throws Exception { TIntArrayList i = new TIntArrayList(); i.add(1); i.add(2); i.add(3); i.add(4); int[] a = new int[]{1, 2, 3}; i.retainAll(a); } } trove-3.0.3/test/gnu/trove/impl/0000755000175000017500000000000012000515265015466 5ustar ericherichtrove-3.0.3/test/gnu/trove/impl/hash/0000755000175000017500000000000012000515265016411 5ustar ericherichtrove-3.0.3/test/gnu/trove/impl/hash/TObjectHashTest.java0000644000175000017500000000150011763017634022262 0ustar ericherichpackage gnu.trove.impl.hash; import gnu.trove.map.hash.TObjectLongHashMap; import junit.framework.TestCase; /** * */ public class TObjectHashTest extends TestCase { // Test case bug bug ID 3067307 public static void testBug3067307() { TObjectLongHashMap testHash = new TObjectLongHashMap(); final int c = 1000; for ( long i = 1; i < c; i++ ) { final String data = "test-" + i; testHash.put( data, i ); testHash.remove( data ); } } // Test case bug bug ID 3067307 public static void testBug3067307_noAutoCompact() { TObjectLongHashMap testHash = new TObjectLongHashMap(); testHash.setAutoCompactionFactor( 0 ); final int c = 1000; for ( long i = 1; i < c; i++ ) { final String data = "test-" + i; testHash.put( data, i ); testHash.remove( data ); } } } trove-3.0.3/test/gnu/trove/impl/hash/THashTest.java0000644000175000017500000002220211763017634021135 0ustar ericherichpackage gnu.trove.impl.hash; import junit.framework.TestCase; import gnu.trove.set.hash.THashSet; import gnu.trove.map.hash.THashMap; import gnu.trove.map.hash.TIntLongHashMap; import gnu.trove.map.hash.TIntObjectHashMap; import gnu.trove.map.hash.TObjectIntHashMap; import gnu.trove.map.TIntLongMap; import gnu.trove.map.TIntObjectMap; import gnu.trove.map.TObjectIntMap; import java.io.ByteArrayOutputStream; import java.io.ObjectOutputStream; import java.io.ByteArrayInputStream; import java.io.ObjectInputStream; /** * tests that need access to internals of THash or THashSet */ public class THashTest extends TestCase { public THashTest( String name ) { super( name ); } public void setUp() throws Exception { super.setUp(); } public void tearDown() throws Exception { super.tearDown(); } @SuppressWarnings({"MismatchedQueryAndUpdateOfCollection"}) public void testNormalLoad() throws Exception { THashSet set = new THashSet( 11, 0.5f ); assertEquals( set._maxSize, 11 ); for ( int i = 0; i < 12; i++ ) { set.add( new Integer( i ) ); } assertTrue( set._maxSize > 12 ); } @SuppressWarnings({"MismatchedQueryAndUpdateOfCollection"}) public void testMaxLoad() throws Exception { THashSet set = new THashSet( 11, 1.0f ); assertEquals( 10, set._maxSize ); for ( int i = 0; i < 12; i++ ) { set.add( new Integer( i ) ); } assertTrue( set._maxSize > 12 ); } public void testReusesRemovedSlotsOnCollision() { THashSet set = new THashSet( 11, 0.5f ); class Foo { public int hashCode() { return 4; } } Foo f1 = new Foo(); Foo f2 = new Foo(); Foo f3 = new Foo(); set.add( f1 ); int idx = set.insertionIndex( f2 ); set.add( f2 ); assertEquals( f2, set._set[idx] ); set.remove( f2 ); assertEquals( THashSet.REMOVED, set._set[idx] ); assertEquals( idx, set.insertionIndex( f3 ) ); set.add( f3 ); assertEquals( f3, set._set[idx] ); } public void testCompact() throws Exception { THashMap map = new THashMap(); Integer[] data = new Integer[1000]; for (int i = 0; i < 1000; i++) { data[i] = new Integer(i); map.put(data[i], data[i]); } assertTrue(map._maxSize > 1000); for (int i = 0; i < 1000; i+=2) { // try { map.remove(data[i]); // } // catch( RuntimeException ex ) { // System.err.println("Error on i: " + i); // System.out.println("Hash codes:"); // for( int j = 0 ; j < data.length; j++ ) { // if ( ( j % 8 ) == 0 ) { // System.out.println(","); // } // else System.out.print(","); // System.out.print(map._hashingStrategy.computeHashCode(data[j])); // } // // // System.out.println("Remove:"); // for( int j = 0 ; j <= i; j+=2 ) { // if ( ( j % 8 ) == 0 ) { // System.out.println(","); // } // else System.out.print(","); // System.out.print(map._hashingStrategy.computeHashCode(data[j])); // } // throw ex; // } } assertEquals(500, map.size()); map.compact(); assertEquals(500, map.size()); assertTrue(map._maxSize < 1000); } @SuppressWarnings({"MismatchedQueryAndUpdateOfCollection"}) public void testTPHashMapConstructors() { int cap = 20; THashMap cap_and_factor = new THashMap( cap, 0.75f ); assertTrue( "capacity not sufficient: " + cap + ", " + cap_and_factor.capacity(), cap <= cap_and_factor.capacity() ); assertEquals( 0.75f, cap_and_factor._loadFactor ); } public void testTPrimitivePrimitveHashMapConstructors() { int cap = 20; TIntLongMap cap_and_factor = new TIntLongHashMap( cap, 0.75f ); TPrimitiveHash cap_and_factor_hash = (TPrimitiveHash) cap_and_factor; assertTrue( "capacity not sufficient: " + cap + ", " + cap_and_factor_hash.capacity(), cap <= cap_and_factor_hash.capacity() ); assertEquals( 0.75f, cap_and_factor_hash._loadFactor ); TIntLongMap fully_specified = new TIntLongHashMap( cap, 0.5f, Integer.MIN_VALUE, Long.MIN_VALUE ); TPrimitiveHash fully_specified_hash = (TPrimitiveHash) fully_specified; assertTrue( "capacity not sufficient: " + cap + ", " + fully_specified_hash.capacity(), cap <= fully_specified_hash.capacity() ); assertEquals( 0.5f, fully_specified_hash._loadFactor ); assertEquals( Integer.MIN_VALUE, fully_specified.getNoEntryKey() ); assertEquals( Long.MIN_VALUE, fully_specified.getNoEntryValue() ); } // test all the way up the chain to THash public void testTPrimitivePrimitveHashMapSerialize() throws Exception { int[] keys = {1138, 42, 86, 99, 101, 727, 117}; long[] vals = new long[keys.length]; TIntLongMap original_map = new TIntLongHashMap( 200, 0.75f, Integer.MIN_VALUE, Long.MIN_VALUE ); for ( int i = 0; i < keys.length; i++ ) { vals[i] = keys[i] * 2; original_map.put( keys[i], vals[i] ); } THash original_hash = ( THash ) original_map; ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream( baos ); oos.writeObject( original_map ); ByteArrayInputStream bias = new ByteArrayInputStream( baos.toByteArray() ); ObjectInputStream ois = new ObjectInputStream( bias ); TIntLongMap deserialized_map = ( TIntLongMap ) ois.readObject(); THash deserialized_hash = ( THash ) deserialized_map; assertEquals( original_map, deserialized_map ); assertEquals( original_map.getNoEntryKey(), deserialized_map.getNoEntryKey() ); assertEquals( original_map.getNoEntryValue(), deserialized_map.getNoEntryValue() ); assertEquals( original_hash._loadFactor, deserialized_hash._loadFactor ); } // test all the way up the chain to THash public void testTPrimitiveObjectHashMapSerialize() throws Exception { int[] keys = {1138, 42, 86, 99, 101, 727, 117}; String[] vals = new String[keys.length]; TIntObjectMap original_map = new TIntObjectHashMap( 200, 0.75f, Integer.MIN_VALUE ); for ( int i = 0; i < keys.length; i++ ) { vals[i] = String.valueOf( keys[i] * 2 ); original_map.put( keys[i], vals[i] ); } THash original_hash = ( THash ) original_map; ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream( baos ); oos.writeObject( original_map ); ByteArrayInputStream bias = new ByteArrayInputStream( baos.toByteArray() ); ObjectInputStream ois = new ObjectInputStream( bias ); TIntObjectMap deserialized_map = ( TIntObjectMap ) ois.readObject(); THash deserialized_hash = ( THash ) deserialized_map; assertEquals( original_map, deserialized_map ); assertEquals( original_map.getNoEntryKey(), deserialized_map.getNoEntryKey() ); assertEquals( original_hash._loadFactor, deserialized_hash._loadFactor ); } // test all the way up the chain to THash public void testTObjectPrimitiveHashMapSerialize() throws Exception { int[] vals = {1138, 42, 86, 99, 101, 727, 117}; String[] keys = new String[vals.length]; TObjectIntMap original_map = new TObjectIntHashMap( 200, 0.75f, Integer.MIN_VALUE ); for ( int i = 0; i < keys.length; i++ ) { keys[i] = String.valueOf( vals[i] * 2 ); original_map.put( keys[i], vals[i] ); } THash original_hash = ( THash ) original_map; ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream( baos ); oos.writeObject( original_map ); ByteArrayInputStream bias = new ByteArrayInputStream( baos.toByteArray() ); ObjectInputStream ois = new ObjectInputStream( bias ); TObjectIntMap deserialized_map = ( TObjectIntMap ) ois.readObject(); THash deserialized_hash = ( THash ) deserialized_map; assertEquals( original_map, deserialized_map ); assertEquals( original_map.getNoEntryValue(), deserialized_map.getNoEntryValue() ); assertEquals( original_hash._loadFactor, deserialized_hash._loadFactor ); } } trove-3.0.3/test/gnu/trove/impl/hash/HashTestKit.java0000644000175000017500000000302611763017634021464 0ustar ericherich/* * //////////////////////////////////////////////////////////////////////////// * // Copyright (c) 2010, Rob Eden All Rights Reserved. * // * // This library is free software; you can redistribute it and/or * // modify it under the terms of the GNU Lesser General Public * // License as published by the Free Software Foundation; either * // version 2.1 of the License, or (at your option) any later version. * // * // This library is distributed in the hope that it will be useful, * // but WITHOUT ANY WARRANTY; without even the implied warranty of * // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * // GNU General Public License for more details. * // * // You should have received a copy of the GNU Lesser General Public * // License along with this program; if not, write to the Free Software * // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * /////////////////////////////////////////////////////////////////////////////// */ package gnu.trove.impl.hash; import junit.framework.TestCase; /** * Static functions for unit tests */ public class HashTestKit { /** * Confirm that the internal FREE counter matches the values in the slots. */ public static void checkFreeSlotCount( THash hash, Object[] slot_keys, Object free_marker ) { int free_counter = hash._free; int count = 0; for( Object slot_key : slot_keys ) { if ( slot_key == free_marker ) count++; } TestCase.assertEquals( free_counter, count ); } } trove-3.0.3/test/gnu/trove/impl/PrimeFinderTest.java0000644000175000017500000000300311763017634021405 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001-2006, Eric D. Friedman All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.impl; import junit.framework.*; import gnu.trove.impl.PrimeFinder; /** * * Created: Sun Nov 4 11:37:24 2001 * * @author Eric D. Friedman * @version $Id: PrimeFinderTest.java,v 1.1.2.1 2009/11/07 03:55:33 robeden Exp $ */ public class PrimeFinderTest extends TestCase { public PrimeFinderTest(String name) { super(name); } public void testPrimeFinder() throws Exception { int r = PrimeFinder.nextPrime(999999); assertEquals(1070981,r); } } // PrimeFinderTests trove-3.0.3/idea/0000755000175000017500000000000012000515241012512 5ustar ericherichtrove-3.0.3/idea/Core.iml0000644000175000017500000000313311763017635014130 0ustar ericherich trove-3.0.3/idea/Trove.iws0000644000175000017500000015613511763017635014373 0ustar ericherich localhost 5050 1267111902568 1267111902568 Android JasperReports 1.6 Core JUnit trove-3.0.3/idea/Benchmarks.iml0000644000175000017500000000301011763017635015307 0ustar ericherich trove-3.0.3/idea/Generator.iml0000644000175000017500000000133511763017635015170 0ustar ericherich trove-3.0.3/idea/Trove.ipr0000644000175000017500000003462011763017635014355 0ustar ericherich 0 false trove-3.0.3/AUTHORS.txt0000644000175000017500000000105111763017636013517 0ustar ericherichRob Eden Johan Parent Jeff Randall Eric D. Friedman Please do NOT email bug reports or feature requests. Instead use the very fine bug tracking system and feature request service on SourceForge: http://sourceforge.net/projects/trove4j/ We'll read your issue just as quickly, and the project's issues will remain out in the open where everyone can see them. We also monitor the project forums, so feel free to use those too. trove-3.0.3/src/0000755000175000017500000000000011763017634012421 5ustar ericherichtrove-3.0.3/src/gnu/0000755000175000017500000000000011763017634013212 5ustar ericherichtrove-3.0.3/src/gnu/trove/0000755000175000017500000000000012000515264014334 5ustar ericherichtrove-3.0.3/src/gnu/trove/set/0000755000175000017500000000000011763017634015144 5ustar ericherichtrove-3.0.3/src/gnu/trove/set/hash/0000755000175000017500000000000012000515265016053 5ustar ericherichtrove-3.0.3/src/gnu/trove/set/hash/TLinkedHashSet.java0000644000175000017500000002410611763017634021547 0ustar ericherichpackage gnu.trove.set.hash; import gnu.trove.iterator.TIntIterator; import gnu.trove.iterator.hash.TObjectHashIterator; import gnu.trove.list.TIntList; import gnu.trove.list.array.TIntArrayList; import gnu.trove.list.linked.TIntLinkedList; import gnu.trove.procedure.TIntProcedure; import gnu.trove.procedure.TObjectProcedure; import java.io.IOException; import java.io.ObjectOutput; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; /** * Created by IntelliJ IDEA. * User: Johan * Date: 15/03/11 * Time: 18:15 * To change this template use File | Settings | File Templates. */ public class TLinkedHashSet extends THashSet { TIntList order; /** * Creates a new THashSet instance with the default * capacity and load factor. */ public TLinkedHashSet() { } /** * Creates a new THashSet instance with a prime * capacity equal to or greater than initialCapacity and * with the default load factor. * * @param initialCapacity an int value */ public TLinkedHashSet(int initialCapacity) { super(initialCapacity); } /** * Creates a new THashSet instance with a prime * capacity equal to or greater than initialCapacity and * with the specified load factor. * * @param initialCapacity an int value * @param loadFactor a float value */ public TLinkedHashSet(int initialCapacity, float loadFactor) { super(initialCapacity, loadFactor); } /** * Creates a new THashSet instance containing the * elements of collection. * * @param es a Collection value */ public TLinkedHashSet(Collection es) { super(es); } /** * initializes the Object set of this hash table. * * @param initialCapacity an int value * @return an int value */ @Override public int setUp(int initialCapacity) { order = new TIntArrayList(initialCapacity) { /** * Grow the internal array as needed to accommodate the specified number of elements. * The size of the array bytes on each resize unless capacity requires more than twice * the current capacity. */ @Override public void ensureCapacity(int capacity) { if (capacity > _data.length) { int newCap = Math.max(_set.length, capacity); int[] tmp = new int[newCap]; System.arraycopy(_data, 0, tmp, 0, _data.length); _data = tmp; } } }; return super.setUp(initialCapacity); //To change body of overridden methods use File | Settings | File Templates. } /** * Empties the set. */ @Override public void clear() { super.clear(); order.clear(); } @Override public String toString() { final StringBuilder buf = new StringBuilder("{"); boolean first = true; for (Iterator it = iterator(); it.hasNext();) { if (first) { first = false; } else { buf.append(", "); } buf.append(it.next()); } buf.append("}"); return buf.toString(); } /** * Inserts a value into the set. * * @param obj an Object value * @return true if the set was modified by the add operation */ @Override public boolean add(E obj) { int index = insertKey(obj); if (index < 0) { return false; // already present in set, nothing to add } if (!order.add(index)) throw new IllegalStateException("Order not changed after insert"); postInsertHook(consumeFreeSlot); return true; // yes, we added something } @Override protected void removeAt(int index) { // Remove from order first since super.removeAt can trigger compaction // making the index invalid afterwards order.remove(index); super.removeAt(index); } /** * Expands the set to accommodate new values. * * @param newCapacity an int value */ @Override protected void rehash(int newCapacity) { TIntLinkedList oldOrder = new TIntLinkedList(order); int oldSize = size(); Object oldSet[] = _set; order.clear(); _set = new Object[newCapacity]; Arrays.fill(_set, FREE); for (TIntIterator iterator = oldOrder.iterator(); iterator.hasNext();) { int i = iterator.next(); E o = (E) oldSet[i]; if (o == FREE || o == REMOVED) { throw new IllegalStateException("Iterating over empty location while rehashing"); } if (o != FREE && o != REMOVED) { int index = insertKey(o); if (index < 0) { // everyone pays for this because some people can't RTFM throwObjectContractViolation(_set[(-index - 1)], o, size(), oldSize, oldSet); } if (!order.add(index)) throw new IllegalStateException("Order not changed after insert"); } } } class WriteProcedure implements TIntProcedure { final ObjectOutput output; IOException ioException; WriteProcedure(ObjectOutput output) { this.output = output; } public IOException getIoException() { return ioException; } public boolean execute(int value) { try { output.writeObject(_set[value]); } catch (IOException e) { ioException = e; return false; } return true; } } @Override protected void writeEntries(ObjectOutput out) throws IOException { // ENTRIES WriteProcedure writeProcedure = new WriteProcedure(out); if (!order.forEach(writeProcedure)) throw writeProcedure.getIoException(); } /** * Creates an iterator over the values of the set. The iterator * supports element deletion. * * @return an Iterator value */ @Override public TObjectHashIterator iterator() { return new TObjectHashIterator(this) { TIntIterator localIterator = order.iterator(); int lastIndex; /** * Moves the iterator to the next Object and returns it. * * @return an Object value * @throws java.util.ConcurrentModificationException * if the structure * was changed using a method that isn't on this iterator. * @throws java.util.NoSuchElementException * if this is called on an * exhausted iterator. */ @Override public E next() { lastIndex = localIterator.next(); return objectAtIndex(lastIndex); } /** * Returns true if the iterator can be advanced past its current * location. * * @return a boolean value */ @Override public boolean hasNext() { return localIterator.hasNext(); //To change body of overridden methods use File | Settings | File Templates. } /** * Removes the last entry returned by the iterator. * Invoking this method more than once for a single entry * will leave the underlying data structure in a confused * state. */ @Override public void remove() { // Remove for iterator first localIterator.remove(); // the removal within removeAt() will not change the collection // but the localIterator will remain valid try { _hash.tempDisableAutoCompaction(); TLinkedHashSet.this.removeAt(lastIndex); } finally { _hash.reenableAutoCompaction(false); } } }; //To change body of overridden methods use File | Settings | File Templates. } class ForEachProcedure implements TIntProcedure { boolean changed = false; final Object[] set; final TObjectProcedure procedure; public ForEachProcedure(Object[] set, TObjectProcedure procedure) { this.set = set; this.procedure = procedure; } /** * Executes this procedure. A false return value indicates that * the application executing this procedure should not invoke this * procedure again. * * @param value a value of type int * @return true if additional invocations of the procedure are * allowed. */ public boolean execute(int value) { return procedure.execute((E) set[value]); } } /** * Executes procedure for each element in the set. * * @param procedure a TObjectProcedure value * @return false if the loop over the set terminated because * the procedure returned false for some value. */ @Override public boolean forEach(TObjectProcedure procedure) { ForEachProcedure forEachProcedure = new ForEachProcedure(_set, procedure); return order.forEach(forEachProcedure); } } trove-3.0.3/src/gnu/trove/set/hash/TCustomHashSet.java0000644000175000017500000002742711763017634021624 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001, Eric D. Friedman All Rights Reserved. // Copyright (c) 2009, Rob Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.set.hash; import gnu.trove.strategy.HashingStrategy; import gnu.trove.impl.HashFunctions; import gnu.trove.impl.hash.TCustomObjectHash; import gnu.trove.iterator.hash.TObjectHashIterator; import gnu.trove.procedure.TObjectProcedure; import gnu.trove.procedure.array.ToObjectArrayProceedure; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.lang.reflect.Array; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.Set; /** * An implementation of the Set interface that uses an * open-addressed hash table to store its contents. * * @author Rob Eden */ public class TCustomHashSet extends TCustomObjectHash implements Set, Iterable, Externalizable { static final long serialVersionUID = 1L; /** FOR EXTERNALIZATION ONLY!!! */ public TCustomHashSet() {} /** * Creates a new THashSet instance with the default * capacity and load factor. */ public TCustomHashSet( HashingStrategy strategy ) { super( strategy ); } /** * Creates a new THashSet instance with a prime * capacity equal to or greater than initialCapacity and * with the default load factor. * * @param initialCapacity an int value */ public TCustomHashSet( HashingStrategy strategy, int initialCapacity ) { super( strategy, initialCapacity ); } /** * Creates a new THashSet instance with a prime * capacity equal to or greater than initialCapacity and * with the specified load factor. * * @param initialCapacity an int value * @param loadFactor a float value */ public TCustomHashSet( HashingStrategy strategy, int initialCapacity, float loadFactor ) { super( strategy, initialCapacity, loadFactor ); } /** * Creates a new THashSet instance containing the * elements of collection. * * @param collection a Collection value */ public TCustomHashSet( HashingStrategy strategy, Collection collection ) { this( strategy, collection.size() ); addAll( collection ); } /** * Inserts a value into the set. * * @param obj an Object value * @return true if the set was modified by the add operation */ public boolean add( E obj ) { int index = insertKey( obj ); if ( index < 0 ) { return false; // already present in set, nothing to add } postInsertHook( consumeFreeSlot ); return true; // yes, we added something } @SuppressWarnings({"SimplifiableIfStatement"}) public boolean equals( Object other ) { if ( !( other instanceof Set ) ) { return false; } Set that = (Set) other; if ( that.size() != this.size() ) { return false; } return containsAll( that ); } public int hashCode() { HashProcedure p = new HashProcedure(); forEach( p ); return p.getHashCode(); } private final class HashProcedure implements TObjectProcedure { private int h = 0; public int getHashCode() { return h; } public final boolean execute( E key ) { h += HashFunctions.hash( key ); return true; } } /** * Expands the set to accommodate new values. * * @param newCapacity an int value */ @SuppressWarnings({"unchecked"}) protected void rehash( int newCapacity ) { int oldCapacity = _set.length; int oldSize = size(); Object oldSet[] = _set; _set = new Object[newCapacity]; Arrays.fill( _set, FREE ); for ( int i = oldCapacity; i-- > 0; ) { E o = (E) oldSet[i]; if ( o != FREE && o != REMOVED ) { int index = insertKey( o ); if ( index < 0 ) { // everyone pays for this because some people can't RTFM throwObjectContractViolation( _set[( -index - 1 )], o, size(), oldSize, oldSet); } } } } /** * Returns a new array containing the objects in the set. * * @return an Object[] value */ @SuppressWarnings({"unchecked"}) public Object[] toArray() { Object[] result = new Object[size()]; forEach( new ToObjectArrayProceedure( result ) ); return result; } /** * Returns a typed array of the objects in the set. * * @param a an Object[] value * @return an Object[] value */ @SuppressWarnings({"unchecked"}) public T[] toArray( T[] a ) { int size = size(); if ( a.length < size ) { a = (T[]) Array.newInstance( a.getClass().getComponentType(), size ); } forEach( new ToObjectArrayProceedure( a ) ); // If this collection fits in the specified array with room to // spare (i.e., the array has more elements than this // collection), the element in the array immediately following // the end of the collection is set to null. This is useful in // determining the length of this collection only if the // caller knows that this collection does not contain any null // elements.) if ( a.length > size ) { a[size] = null; } return a; } /** Empties the set. */ public void clear() { super.clear(); Arrays.fill( _set, 0, _set.length, FREE ); } /** * Removes obj from the set. * * @param obj an Object value * @return true if the set was modified by the remove operation. */ @SuppressWarnings({"unchecked"}) public boolean remove( Object obj ) { int index = index( obj ); if ( index >= 0 ) { removeAt( index ); return true; } return false; } /** * Creates an iterator over the values of the set. The iterator * supports element deletion. * * @return an Iterator value */ @SuppressWarnings({"unchecked"}) public TObjectHashIterator iterator() { return new TObjectHashIterator( this ); } /** * Tests the set to determine if all of the elements in * collection are present. * * @param collection a Collection value * @return true if all elements were present in the set. */ @SuppressWarnings("ForLoopReplaceableByForEach") public boolean containsAll( Collection collection ) { for ( Iterator i = collection.iterator(); i.hasNext(); ) { if ( !contains( i.next() ) ) { return false; } } return true; } /** * Adds all of the elements in collection to the set. * * @param collection a Collection value * @return true if the set was modified by the add all operation. */ public boolean addAll( Collection collection ) { boolean changed = false; int size = collection.size(); ensureCapacity( size ); Iterator it = collection.iterator(); while ( size-- > 0 ) { if ( add( it.next() ) ) { changed = true; } } return changed; } /** * Removes all of the elements in collection from the set. * * @param collection a Collection value * @return true if the set was modified by the remove all operation. */ public boolean removeAll( Collection collection ) { boolean changed = false; int size = collection.size(); Iterator it; it = collection.iterator(); while ( size-- > 0 ) { if ( remove( it.next() ) ) { changed = true; } } return changed; } /** * Removes any values in the set which are not contained in * collection. * * @param collection a Collection value * @return true if the set was modified by the retain all operation */ @SuppressWarnings({"SuspiciousMethodCalls"}) public boolean retainAll( Collection collection ) { boolean changed = false; int size = size(); Iterator it = iterator(); while ( size-- > 0 ) { if ( !collection.contains( it.next() ) ) { it.remove(); changed = true; } } return changed; } public String toString() { final StringBuilder buf = new StringBuilder( "{" ); forEach( new TObjectProcedure() { private boolean first = true; public boolean execute( Object value ) { if ( first ) { first = false; } else { buf.append( ", " ); } buf.append( value ); return true; } } ); buf.append( "}" ); return buf.toString(); } public void writeExternal( ObjectOutput out ) throws IOException { // VERSION out.writeByte( 1 ); // NOTE: Super was not written in version 0 super.writeExternal( out ); // NUMBER OF ENTRIES out.writeInt( _size ); // ENTRIES for ( int i = _set.length; i-- > 0; ) { if ( _set[i] != REMOVED && _set[i] != FREE ) { out.writeObject( _set[i] ); } } } @SuppressWarnings({"unchecked"}) public void readExternal( ObjectInput in ) throws IOException, ClassNotFoundException { // VERSION byte version = in.readByte(); // NOTE: super was not written in version 0 if ( version != 0 ) { super.readExternal( in ); } // NUMBER OF ENTRIES int size = in.readInt(); setUp( size ); // ENTRIES while ( size-- > 0 ) { E val = (E) in.readObject(); add( val ); } } } trove-3.0.3/src/gnu/trove/set/hash/THashSet.java0000644000175000017500000002720011763017634020416 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001, Eric D. Friedman All Rights Reserved. // Copyright (c) 2009, Rob Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.set.hash; import gnu.trove.impl.hash.TObjectHash; import gnu.trove.impl.HashFunctions; import gnu.trove.procedure.TObjectProcedure; import gnu.trove.procedure.array.ToObjectArrayProceedure; import gnu.trove.iterator.hash.TObjectHashIterator; import java.io.*; import java.util.Collection; import java.util.Iterator; import java.util.Set; import java.util.Arrays; import java.lang.reflect.Array; /** * An implementation of the Set interface that uses an * open-addressed hash table to store its contents. * * @author Eric D. Friedman * @author Rob Eden * @author Jeff Randall * @version $Id: THashSet.java,v 1.1.2.8 2010/03/02 04:09:50 robeden Exp $ */ public class THashSet extends TObjectHash implements Set, Iterable, Externalizable { static final long serialVersionUID = 1L; /** * Creates a new THashSet instance with the default * capacity and load factor. */ public THashSet() { super(); } /** * Creates a new THashSet instance with a prime * capacity equal to or greater than initialCapacity and * with the default load factor. * * @param initialCapacity an int value */ public THashSet(int initialCapacity) { super(initialCapacity); } /** * Creates a new THashSet instance with a prime * capacity equal to or greater than initialCapacity and * with the specified load factor. * * @param initialCapacity an int value * @param loadFactor a float value */ public THashSet(int initialCapacity, float loadFactor) { super(initialCapacity, loadFactor); } /** * Creates a new THashSet instance containing the * elements of collection. * * @param collection a Collection value */ public THashSet(Collection collection) { this(collection.size()); addAll(collection); } /** * Inserts a value into the set. * * @param obj an Object value * @return true if the set was modified by the add operation */ public boolean add(E obj) { int index = insertKey(obj); if (index < 0) { return false; // already present in set, nothing to add } postInsertHook(consumeFreeSlot); return true; // yes, we added something } @SuppressWarnings({"SimplifiableIfStatement"}) public boolean equals(Object other) { if (!(other instanceof Set)) { return false; } Set that = (Set) other; if (that.size() != this.size()) { return false; } return containsAll(that); } public int hashCode() { HashProcedure p = new HashProcedure(); forEach(p); return p.getHashCode(); } private final class HashProcedure implements TObjectProcedure { private int h = 0; public int getHashCode() { return h; } public final boolean execute(E key) { h += HashFunctions.hash(key); return true; } } /** * Expands the set to accommodate new values. * * @param newCapacity an int value */ @SuppressWarnings({"unchecked"}) protected void rehash(int newCapacity) { int oldCapacity = _set.length; int oldSize = size(); Object oldSet[] = _set; _set = new Object[newCapacity]; Arrays.fill(_set, FREE); int count = 0; for (int i = oldCapacity; i-- > 0;) { E o = (E) oldSet[i]; if (o != FREE && o != REMOVED) { int index = insertKey(o); if (index < 0) { // everyone pays for this because some people can't RTFM throwObjectContractViolation(_set[(-index - 1)], o, size(), oldSize, oldSet); } // count++; } } // Last check: size before and after should be the same reportPotentialConcurrentMod(size(), oldSize); } /** * Returns a new array containing the objects in the set. * * @return an Object[] value */ @SuppressWarnings({"unchecked"}) public Object[] toArray() { Object[] result = new Object[size()]; forEach(new ToObjectArrayProceedure(result)); return result; } /** * Returns a typed array of the objects in the set. * * @param a an Object[] value * @return an Object[] value */ @SuppressWarnings({"unchecked"}) public T[] toArray(T[] a) { int size = size(); if (a.length < size) { a = (T[]) Array.newInstance(a.getClass().getComponentType(), size); } forEach(new ToObjectArrayProceedure(a)); // If this collection fits in the specified array with room to // spare (i.e., the array has more elements than this // collection), the element in the array immediately following // the end of the collection is set to null. This is useful in // determining the length of this collection only if the // caller knows that this collection does not contain any null // elements.) if (a.length > size) { a[size] = null; } return a; } /** * Empties the set. */ public void clear() { super.clear(); Arrays.fill(_set, 0, _set.length, FREE); } /** * Removes obj from the set. * * @param obj an Object value * @return true if the set was modified by the remove operation. */ @SuppressWarnings({"unchecked"}) public boolean remove(Object obj) { int index = index(obj); if (index >= 0) { removeAt(index); return true; } return false; } /** * Creates an iterator over the values of the set. The iterator * supports element deletion. * * @return an Iterator value */ @SuppressWarnings({"unchecked"}) public TObjectHashIterator iterator() { return new TObjectHashIterator(this); } /** * Tests the set to determine if all of the elements in * collection are present. * * @param collection a Collection value * @return true if all elements were present in the set. */ @SuppressWarnings("ForLoopReplaceableByForEach") public boolean containsAll(Collection collection) { for (Iterator i = collection.iterator(); i.hasNext();) { if (!contains(i.next())) { return false; } } return true; } /** * Adds all of the elements in collection to the set. * * @param collection a Collection value * @return true if the set was modified by the add all operation. */ public boolean addAll(Collection collection) { boolean changed = false; int size = collection.size(); ensureCapacity(size); Iterator it = collection.iterator(); while (size-- > 0) { if (add(it.next())) { changed = true; } } return changed; } /** * Removes all of the elements in collection from the set. * * @param collection a Collection value * @return true if the set was modified by the remove all operation. */ public boolean removeAll(Collection collection) { boolean changed = false; int size = collection.size(); Iterator it; it = collection.iterator(); while (size-- > 0) { if (remove(it.next())) { changed = true; } } return changed; } /** * Removes any values in the set which are not contained in * collection. * * @param collection a Collection value * @return true if the set was modified by the retain all operation */ @SuppressWarnings({"SuspiciousMethodCalls"}) public boolean retainAll(Collection collection) { boolean changed = false; int size = size(); Iterator it = iterator(); while (size-- > 0) { if (!collection.contains(it.next())) { it.remove(); changed = true; } } return changed; } public String toString() { final StringBuilder buf = new StringBuilder("{"); forEach(new TObjectProcedure() { private boolean first = true; public boolean execute(Object value) { if (first) { first = false; } else { buf.append(", "); } buf.append(value); return true; } }); buf.append("}"); return buf.toString(); } public void writeExternal(ObjectOutput out) throws IOException { // VERSION out.writeByte(1); // NOTE: Super was not written in version 0 super.writeExternal(out); // NUMBER OF ENTRIES out.writeInt(_size); // ENTRIES writeEntries(out); } protected void writeEntries(ObjectOutput out) throws IOException { for (int i = _set.length; i-- > 0;) { if (_set[i] != REMOVED && _set[i] != FREE) { out.writeObject(_set[i]); } } } @SuppressWarnings({"unchecked"}) public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { // VERSION byte version = in.readByte(); // NOTE: super was not written in version 0 if (version != 0) { super.readExternal(in); } // NUMBER OF ENTRIES int size = in.readInt(); setUp(size); // ENTRIES while (size-- > 0) { E val = (E) in.readObject(); add(val); } } } // THashSet trove-3.0.3/src/gnu/trove/function/0000755000175000017500000000000012000515264016161 5ustar ericherichtrove-3.0.3/src/gnu/trove/function/TObjectFunction.java0000644000175000017500000000277411763017634022113 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001, Eric D. Friedman All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.function; /** * Interface for functions that accept and return one Object reference. *

* Created: Mon Nov 5 22:19:36 2001 * * @author Eric D. Friedman * @version $Id: TObjectFunction.java,v 1.1.2.1 2009/09/06 17:02:19 upholderoftruth Exp $ */ public interface TObjectFunction { /** * Execute this function with value * * @param value an Object input * @return an Object result */ public R execute( T value ); }// TObjectFunction trove-3.0.3/src/gnu/trove/map/0000755000175000017500000000000012000515264015111 5ustar ericherichtrove-3.0.3/src/gnu/trove/map/hash/0000755000175000017500000000000012000515264016034 5ustar ericherichtrove-3.0.3/src/gnu/trove/map/hash/THashMap.java0000644000175000017500000006342211763017634020370 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001, Eric D. Friedman All Rights Reserved. // Copyright (c) 2009, Rob Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.map.hash; import gnu.trove.function.TObjectFunction; import gnu.trove.impl.HashFunctions; import gnu.trove.impl.hash.TObjectHash; import gnu.trove.iterator.hash.TObjectHashIterator; import gnu.trove.map.TMap; import gnu.trove.procedure.TObjectObjectProcedure; import gnu.trove.procedure.TObjectProcedure; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.*; /** * An implementation of the Map interface which uses an open addressed * hash table to store its contents. *

* Created: Sun Nov 4 08:52:45 2001 * * @author Eric D. Friedman * @author Rob Eden * @author Jeff Randall * @version $Id: THashMap.java,v 1.1.2.8 2010/03/02 04:09:50 robeden Exp $ */ public class THashMap extends TObjectHash implements TMap, Externalizable { static final long serialVersionUID = 1L; /** * the values of the map */ protected transient V[] _values; /** * Creates a new THashMap instance with the default * capacity and load factor. */ public THashMap() { super(); } /** * Creates a new THashMap instance with a prime * capacity equal to or greater than initialCapacity and * with the default load factor. * * @param initialCapacity an int value */ public THashMap(int initialCapacity) { super(initialCapacity); } /** * Creates a new THashMap instance with a prime * capacity equal to or greater than initialCapacity and * with the specified load factor. * * @param initialCapacity an int value * @param loadFactor a float value */ public THashMap(int initialCapacity, float loadFactor) { super(initialCapacity, loadFactor); } /** * Creates a new THashMap instance which contains the * key/value pairs in map. * * @param map a Map value */ public THashMap(Map map) { this(map.size()); putAll(map); } /** * Creates a new THashMap instance which contains the * key/value pairs in map. * * @param map a Map value */ public THashMap(THashMap map) { this(map.size()); putAll(map); } /** * initialize the value array of the map. * * @param initialCapacity an int value * @return an int value */ public int setUp(int initialCapacity) { int capacity; capacity = super.setUp(initialCapacity); //noinspection unchecked _values = (V[]) new Object[capacity]; return capacity; } /** * Inserts a key/value pair into the map. * * @param key an Object value * @param value an Object value * @return the previous value associated with key, * or {@code null} if none was found. */ public V put(K key, V value) { // insertKey() inserts the key if a slot if found and returns the index int index = insertKey(key); return doPut(value, index); } /** * Inserts a key/value pair into the map if the specified key is not already * associated with a value. * * @param key an Object value * @param value an Object value * @return the previous value associated with key, * or {@code null} if none was found. */ public V putIfAbsent(K key, V value) { // insertKey() inserts the key if a slot if found and returns the index int index = insertKey(key); if (index < 0) { return _values[-index - 1]; } return doPut(value, index); } private V doPut(V value, int index) { V previous = null; boolean isNewMapping = true; if (index < 0) { index = -index - 1; previous = _values[index]; isNewMapping = false; } _values[index] = value; if (isNewMapping) { postInsertHook(consumeFreeSlot); } return previous; } /** * Compares this map with another map for equality of their stored * entries. * * @param other an Object value * @return a boolean value */ @SuppressWarnings({"unchecked", "SimplifiableIfStatement"}) public boolean equals(Object other) { if (!(other instanceof Map)) { return false; } Map that = (Map) other; if (that.size() != this.size()) { return false; } return forEachEntry(new EqProcedure(that)); } public int hashCode() { HashProcedure p = new HashProcedure(); forEachEntry(p); return p.getHashCode(); } public String toString() { final StringBuilder buf = new StringBuilder("{"); forEachEntry(new TObjectObjectProcedure() { private boolean first = true; public boolean execute(K key, V value) { if (first) { first = false; } else { buf.append(", "); } buf.append(key); buf.append("="); buf.append(value); return true; } }); buf.append("}"); return buf.toString(); } private final class HashProcedure implements TObjectObjectProcedure { private int h = 0; public int getHashCode() { return h; } public final boolean execute(K key, V value) { h += HashFunctions.hash(key) ^ (value == null ? 0 : value.hashCode()); return true; } } private final class EqProcedure implements TObjectObjectProcedure { private final Map _otherMap; EqProcedure(Map otherMap) { _otherMap = otherMap; } public final boolean execute(K key, V value) { // Check to make sure the key is there. This avoids problems that come up with // null values. Since it is only caused in that cause, only do this when the // value is null (to avoid extra work). if (value == null && !_otherMap.containsKey(key)) { return false; } V oValue = _otherMap.get(key); return oValue == value || (oValue != null && THashMap.this.equals(oValue, value)); } } /** * Executes procedure for each key in the map. * * @param procedure a TObjectProcedure value * @return false if the loop over the keys terminated because * the procedure returned false for some key. */ public boolean forEachKey(TObjectProcedure procedure) { return forEach(procedure); } /** * Executes procedure for each value in the map. * * @param procedure a TObjectProcedure value * @return false if the loop over the values terminated because * the procedure returned false for some value. */ public boolean forEachValue(TObjectProcedure procedure) { V[] values = _values; Object[] set = _set; for (int i = values.length; i-- > 0;) { if (set[i] != FREE && set[i] != REMOVED && !procedure.execute(values[i])) { return false; } } return true; } /** * Executes procedure for each key/value entry in the * map. * * @param procedure a TObjectObjectProcedure value * @return false if the loop over the entries terminated because * the procedure returned false for some entry. */ @SuppressWarnings({"unchecked"}) public boolean forEachEntry(TObjectObjectProcedure procedure) { Object[] keys = _set; V[] values = _values; for (int i = keys.length; i-- > 0;) { if (keys[i] != FREE && keys[i] != REMOVED && !procedure.execute((K) keys[i], values[i])) { return false; } } return true; } /** * Retains only those entries in the map for which the procedure * returns a true value. * * @param procedure determines which entries to keep * @return true if the map was modified. */ @SuppressWarnings({"unchecked"}) public boolean retainEntries(TObjectObjectProcedure procedure) { boolean modified = false; Object[] keys = _set; V[] values = _values; // Temporarily disable compaction. This is a fix for bug #1738760 tempDisableAutoCompaction(); try { for (int i = keys.length; i-- > 0;) { if (keys[i] != FREE && keys[i] != REMOVED && !procedure.execute((K) keys[i], values[i])) { removeAt(i); modified = true; } } } finally { reenableAutoCompaction(true); } return modified; } /** * Transform the values in this map using function. * * @param function a TObjectFunction value */ public void transformValues(TObjectFunction function) { V[] values = _values; Object[] set = _set; for (int i = values.length; i-- > 0;) { if (set[i] != FREE && set[i] != REMOVED) { values[i] = function.execute(values[i]); } } } /** * rehashes the map to the new capacity. * * @param newCapacity an int value */ @SuppressWarnings({"unchecked"}) protected void rehash(int newCapacity) { int oldCapacity = _set.length; int oldSize = size(); Object oldKeys[] = _set; V oldVals[] = _values; _set = new Object[newCapacity]; Arrays.fill(_set, FREE); _values = (V[]) new Object[newCapacity]; // Process entries from the old array, skipping free and removed slots. Put the // values into the appropriate place in the new array. int count = 0; for (int i = oldCapacity; i-- > 0;) { Object o = oldKeys[i]; if (o == FREE || o == REMOVED) continue; int index = insertKey((K) o); if (index < 0) { throwObjectContractViolation(_set[(-index - 1)], o, size(), oldSize, oldKeys); } _values[index] = oldVals[i]; // count++; } // Last check: size before and after should be the same reportPotentialConcurrentMod(size(), oldSize); } /** * retrieves the value for key * * @param key an Object value * @return the value of key or null if no such mapping exists. */ @SuppressWarnings({"unchecked"}) public V get(Object key) { int index = index(key); return index < 0 ? null : _values[index]; } /** * Empties the map. */ public void clear() { if (size() == 0) { return; // optimization } super.clear(); Arrays.fill(_set, 0, _set.length, FREE); Arrays.fill(_values, 0, _values.length, null); } /** * Deletes a key/value pair from the map. * * @param key an Object value * @return an Object value */ @SuppressWarnings({"unchecked"}) public V remove(Object key) { V prev = null; int index = index(key); if (index >= 0) { prev = _values[index]; removeAt(index); // clear key,state; adjust size } return prev; } /** * removes the mapping at index from the map. * * @param index an int value */ public void removeAt(int index) { _values[index] = null; super.removeAt(index); // clear key, state; adjust size } /** * Returns a view on the values of the map. * * @return a Collection value */ public Collection values() { return new ValueView(); } /** * returns a Set view on the keys of the map. * * @return a Set value */ public Set keySet() { return new KeyView(); } /** * Returns a Set view on the entries of the map. * * @return a Set value */ public Set> entrySet() { return new EntryView(); } /** * checks for the presence of val in the values of the map. * * @param val an Object value * @return a boolean value */ public boolean containsValue(Object val) { Object[] set = _set; V[] vals = _values; // special case null values so that we don't have to // perform null checks before every call to equals() if (null == val) { for (int i = vals.length; i-- > 0;) { if ((set[i] != FREE && set[i] != REMOVED) && val == vals[i]) { return true; } } } else { for (int i = vals.length; i-- > 0;) { if ((set[i] != FREE && set[i] != REMOVED) && (val == vals[i] || equals(val, vals[i]))) { return true; } } } // end of else return false; } /** * checks for the present of key in the keys of the map. * * @param key an Object value * @return a boolean value */ public boolean containsKey(Object key) { //noinspection unchecked return contains(key); } /** * copies the key/value mappings in map into this map. * * @param map a Map value */ public void putAll(Map map) { ensureCapacity(map.size()); // could optimize this for cases when map instanceof THashMap for (Map.Entry e : map.entrySet()) { put(e.getKey(), e.getValue()); } } /** * a view onto the values of the map. */ protected class ValueView extends MapBackedView { @SuppressWarnings({"unchecked"}) public Iterator iterator() { return new TObjectHashIterator(THashMap.this) { protected V objectAtIndex(int index) { return _values[index]; } }; } public boolean containsElement(V value) { return containsValue(value); } public boolean removeElement(V value) { Object[] values = _values; Object[] set = _set; for (int i = values.length; i-- > 0;) { if ((set[i] != FREE && set[i] != REMOVED) && value == values[i] || (null != values[i] && THashMap.this.equals(values[i], value))) { removeAt(i); return true; } } return false; } } /** * a view onto the entries of the map. */ protected class EntryView extends MapBackedView> { private final class EntryIterator extends TObjectHashIterator { EntryIterator(THashMap map) { super(map); } @SuppressWarnings({"unchecked"}) public Entry objectAtIndex(final int index) { return new Entry((K) _set[index], _values[index], index); } } @SuppressWarnings({"unchecked"}) public Iterator> iterator() { return new EntryIterator(THashMap.this); } public boolean removeElement(Map.Entry entry) { if (entry == null) return false; // have to effectively reimplement Map.remove here // because we need to return true/false depending on // whether the removal took place. Since the Entry's // value can be null, this means that we can't rely // on the value of the object returned by Map.remove() // to determine whether a deletion actually happened. // // Note also that the deletion is only legal if // both the key and the value match. V val; int index; K key = keyForEntry(entry); index = index(key); if (index >= 0) { val = valueForEntry(entry); if (val == _values[index] || (null != val && THashMap.this.equals(val, _values[index]))) { removeAt(index); // clear key,state; adjust size return true; } } return false; } public boolean containsElement(Map.Entry entry) { V val = get(keyForEntry(entry)); V entryValue = entry.getValue(); return entryValue == val || (null != val && THashMap.this.equals(val, entryValue)); } protected V valueForEntry(Map.Entry entry) { return entry.getValue(); } protected K keyForEntry(Map.Entry entry) { return entry.getKey(); } } private abstract class MapBackedView extends AbstractSet implements Set, Iterable { public abstract Iterator iterator(); public abstract boolean removeElement(E key); public abstract boolean containsElement(E key); @SuppressWarnings({"unchecked"}) public boolean contains(Object key) { return containsElement((E) key); } @SuppressWarnings({"unchecked"}) public boolean remove(Object o) { try { return removeElement((E) o); } catch (ClassCastException ex) { return false; } } // public boolean containsAll( Collection collection ) { // for ( Object element : collection ) { // if ( !contains( element ) ) { // return false; // } // } // return true; // } public void clear() { THashMap.this.clear(); } public boolean add(E obj) { throw new UnsupportedOperationException(); } public int size() { return THashMap.this.size(); } public Object[] toArray() { Object[] result = new Object[size()]; Iterator e = iterator(); for (int i = 0; e.hasNext(); i++) { result[i] = e.next(); } return result; } @SuppressWarnings({"unchecked"}) public T[] toArray(T[] a) { int size = size(); if (a.length < size) { a = (T[]) java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), size); } Iterator it = iterator(); Object[] result = a; for (int i = 0; i < size; i++) { result[i] = it.next(); } if (a.length > size) { a[size] = null; } return a; } public boolean isEmpty() { return THashMap.this.isEmpty(); } public boolean addAll(Collection collection) { throw new UnsupportedOperationException(); } @SuppressWarnings({"SuspiciousMethodCalls"}) public boolean retainAll(Collection collection) { boolean changed = false; Iterator i = iterator(); while (i.hasNext()) { if (!collection.contains(i.next())) { i.remove(); changed = true; } } return changed; } public String toString() { Iterator i = iterator(); if (!i.hasNext()) return "{}"; StringBuilder sb = new StringBuilder(); sb.append('{'); for (; ;) { E e = i.next(); sb.append(e == this ? "(this Collection)" : e); if (!i.hasNext()) return sb.append('}').toString(); sb.append(", "); } } } /** * a view onto the keys of the map. */ protected class KeyView extends MapBackedView { @SuppressWarnings({"unchecked"}) public Iterator iterator() { return new TObjectHashIterator(THashMap.this); } public boolean removeElement(K key) { return null != THashMap.this.remove(key); } public boolean containsElement(K key) { return THashMap.this.contains(key); } } final class Entry implements Map.Entry { private K key; private V val; private final int index; Entry(final K key, V value, final int index) { this.key = key; this.val = value; this.index = index; } public K getKey() { return key; } public V getValue() { return val; } public V setValue(V o) { if (_values[index] != val) { throw new ConcurrentModificationException(); } // need to return previous value V retval = val; // update this entry's value, in case setValue is called again _values[index] = o; val = o; return retval; } public boolean equals(Object o) { if (o instanceof Map.Entry) { Map.Entry e1 = this; Map.Entry e2 = (Map.Entry) o; return (THashMap.this.equals(e1.getKey(), e2.getKey())) && (THashMap.this.equals(e1.getValue(), e1.getValue())); } return false; } public int hashCode() { return (getKey() == null ? 0 : getKey().hashCode()) ^ (getValue() == null ? 0 : getValue().hashCode()); } @Override public String toString() { return key + "=" + val; } } public void writeExternal(ObjectOutput out) throws IOException { // VERSION out.writeByte(1); // NOTE: Super was not written in version 0 super.writeExternal(out); // NUMBER OF ENTRIES out.writeInt(_size); // ENTRIES for (int i = _set.length; i-- > 0;) { if (_set[i] != REMOVED && _set[i] != FREE) { out.writeObject(_set[i]); out.writeObject(_values[i]); } } } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { // VERSION byte version = in.readByte(); // NOTE: super was not written in version 0 if (version != 0) { super.readExternal(in); } // NUMBER OF ENTRIES int size = in.readInt(); setUp(size); // ENTRIES while (size-- > 0) { //noinspection unchecked K key = (K) in.readObject(); //noinspection unchecked V val = (V) in.readObject(); put(key, val); } } } // THashMap trove-3.0.3/src/gnu/trove/map/hash/TCustomHashMap.java0000644000175000017500000006347611763017634021574 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2009, Rob Eden All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.map.hash; import gnu.trove.function.TObjectFunction; import gnu.trove.impl.HashFunctions; import gnu.trove.impl.hash.TCustomObjectHash; import gnu.trove.iterator.hash.TObjectHashIterator; import gnu.trove.map.TMap; import gnu.trove.procedure.TObjectObjectProcedure; import gnu.trove.procedure.TObjectProcedure; import gnu.trove.strategy.HashingStrategy; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.*; /** * An implementation of the Map interface which uses an open addressed * hash table to store its contents. * * @author Rob Eden */ public class TCustomHashMap extends TCustomObjectHash implements TMap, Externalizable { static final long serialVersionUID = 1L; /** the values of the map */ protected transient V[] _values; /** FOR EXTERNALIZATION ONLY!!! */ public TCustomHashMap() { super(); } /** * Creates a new TCustomHashMap instance with the default * capacity and load factor. */ public TCustomHashMap( HashingStrategy strategy ) { super( strategy ); } /** * Creates a new TCustomHashMap instance with a prime * capacity equal to or greater than initialCapacity and * with the default load factor. * * @param initialCapacity an int value */ public TCustomHashMap( HashingStrategy strategy, int initialCapacity ) { super( strategy, initialCapacity ); } /** * Creates a new TCustomHashMap instance with a prime * capacity equal to or greater than initialCapacity and * with the specified load factor. * * @param initialCapacity an int value * @param loadFactor a float value */ public TCustomHashMap( HashingStrategy strategy, int initialCapacity, float loadFactor ) { super( strategy, initialCapacity, loadFactor ); } /** * Creates a new TCustomHashMap instance which contains the * key/value pairs in map. * * @param map a Map value */ public TCustomHashMap( HashingStrategy strategy, Map map ) { this( strategy, map.size() ); putAll( map ); } /** * Creates a new TCustomHashMap instance which contains the * key/value pairs in map. * * @param map a Map value */ public TCustomHashMap( HashingStrategy strategy, TCustomHashMap map ) { this( strategy, map.size() ); putAll( map ); } /** * initialize the value array of the map. * * @param initialCapacity an int value * @return an int value */ public int setUp( int initialCapacity ) { int capacity; capacity = super.setUp( initialCapacity ); //noinspection unchecked _values = (V[]) new Object[capacity]; return capacity; } /** * Inserts a key/value pair into the map. * * @param key an Object value * @param value an Object value * @return the previous value associated with key, * or {@code null} if none was found. */ public V put( K key, V value ) { int index = insertKey( key ); return doPut( value, index ); } /** * Inserts a key/value pair into the map if the specified key is not already * associated with a value. * * @param key an Object value * @param value an Object value * @return the previous value associated with key, * or {@code null} if none was found. */ public V putIfAbsent( K key, V value ) { int index = insertKey( key ); if ( index < 0 ) { return _values[-index - 1]; } return doPut(value, index ); } private V doPut( V value, int index ) { V previous = null; boolean isNewMapping = true; if ( index < 0 ) { index = -index - 1; previous = _values[index]; isNewMapping = false; } _values[index] = value; if ( isNewMapping ) { postInsertHook( consumeFreeSlot ); } return previous; } /** * Compares this map with another map for equality of their stored * entries. * * @param other an Object value * @return a boolean value */ @SuppressWarnings({"unchecked", "SimplifiableIfStatement"}) public boolean equals( Object other ) { if ( !( other instanceof Map ) ) { return false; } Map that = (Map) other; if ( that.size() != this.size() ) { return false; } return forEachEntry( new EqProcedure( that ) ); } public int hashCode() { HashProcedure p = new HashProcedure(); forEachEntry( p ); return p.getHashCode(); } public String toString() { final StringBuilder buf = new StringBuilder( "{" ); forEachEntry( new TObjectObjectProcedure() { private boolean first = true; public boolean execute( K key, V value ) { if ( first ) { first = false; } else { buf.append( ", " ); } buf.append( key ); buf.append( "=" ); buf.append( value ); return true; } } ); buf.append( "}" ); return buf.toString(); } private final class HashProcedure implements TObjectObjectProcedure { private int h = 0; public int getHashCode() { return h; } public final boolean execute( K key, V value ) { h += HashFunctions.hash( key ) ^ ( value == null ? 0 : value.hashCode() ); return true; } } private static final class EqProcedure implements TObjectObjectProcedure { private final Map _otherMap; EqProcedure( Map otherMap ) { _otherMap = otherMap; } public final boolean execute( K key, V value ) { // Check to make sure the key is there. This avoids problems that come up with // null values. Since it is only caused in that cause, only do this when the // value is null (to avoid extra work). if ( value == null && !_otherMap.containsKey( key ) ) { return false; } V oValue = _otherMap.get( key ); return oValue == value || ( oValue != null && oValue.equals( value ) ); } } /** * Executes procedure for each key in the map. * * @param procedure a TObjectProcedure value * @return false if the loop over the keys terminated because * the procedure returned false for some key. */ public boolean forEachKey( TObjectProcedure procedure ) { return forEach( procedure ); } /** * Executes procedure for each value in the map. * * @param procedure a TObjectProcedure value * @return false if the loop over the values terminated because * the procedure returned false for some value. */ public boolean forEachValue( TObjectProcedure procedure ) { V[] values = _values; Object[] set = _set; for ( int i = values.length; i-- > 0; ) { if ( set[i] != FREE && set[i] != REMOVED && !procedure.execute( values[i] ) ) { return false; } } return true; } /** * Executes procedure for each key/value entry in the * map. * * @param procedure a TObjectObjectProcedure value * @return false if the loop over the entries terminated because * the procedure returned false for some entry. */ @SuppressWarnings({"unchecked"}) public boolean forEachEntry( TObjectObjectProcedure procedure ) { Object[] keys = _set; V[] values = _values; for ( int i = keys.length; i-- > 0; ) { if ( keys[i] != FREE && keys[i] != REMOVED && !procedure.execute( (K) keys[i], values[i] ) ) { return false; } } return true; } /** * Retains only those entries in the map for which the procedure * returns a true value. * * @param procedure determines which entries to keep * @return true if the map was modified. */ @SuppressWarnings({"unchecked"}) public boolean retainEntries( TObjectObjectProcedure procedure ) { boolean modified = false; Object[] keys = _set; V[] values = _values; // Temporarily disable compaction. This is a fix for bug #1738760 tempDisableAutoCompaction(); try { for ( int i = keys.length; i-- > 0; ) { if ( keys[i] != FREE && keys[i] != REMOVED && !procedure.execute( (K) keys[i], values[i] ) ) { removeAt( i ); modified = true; } } } finally { reenableAutoCompaction( true ); } return modified; } /** * Transform the values in this map using function. * * @param function a TObjectFunction value */ public void transformValues( TObjectFunction function ) { V[] values = _values; Object[] set = _set; for ( int i = values.length; i-- > 0; ) { if ( set[i] != FREE && set[i] != REMOVED ) { values[i] = function.execute( values[i] ); } } } /** * rehashes the map to the new capacity. * * @param newCapacity an int value */ @SuppressWarnings({"unchecked"}) protected void rehash( int newCapacity ) { int oldCapacity = _set.length; int oldSize = size(); Object oldKeys[] = _set; V oldVals[] = _values; _set = new Object[ newCapacity ]; Arrays.fill( _set, FREE ); _values = ( V[] ) new Object[ newCapacity ]; // Process entries from the old array, skipping free and removed slots. Put the // values into the appropriate place in the new array. for ( int i = oldCapacity; i-- > 0; ) { Object o = oldKeys[ i ]; if ( o == FREE || o == REMOVED ) continue; int index = insertKey( ( K ) o ); if ( index < 0 ) { throwObjectContractViolation( _set[ ( -index - 1 ) ], o, size(), oldSize, oldKeys); } _values[ index ] = oldVals[ i ]; } } /** * retrieves the value for key * * @param key an Object value * @return the value of key or null if no such mapping exists. */ @SuppressWarnings({"unchecked"}) public V get( Object key ) { int index = index( key ); if ( index < 0 || ! strategy.equals( ( K ) _set[index], ( K ) key ) ) { return null; } return _values[index]; } /** Empties the map. */ public void clear() { if ( size() == 0 ) { return; // optimization } super.clear(); Arrays.fill( _set, 0, _set.length, FREE ); Arrays.fill( _values, 0, _values.length, null ); } /** * Deletes a key/value pair from the map. * * @param key an Object value * @return an Object value */ @SuppressWarnings({"unchecked"}) public V remove( Object key ) { V prev = null; int index = index( key ); if ( index >= 0 ) { prev = _values[index]; removeAt( index ); // clear key,state; adjust size } return prev; } /** * removes the mapping at index from the map. * * @param index an int value */ public void removeAt( int index ) { _values[index] = null; super.removeAt( index ); // clear key, state; adjust size } /** * Returns a view on the values of the map. * * @return a Collection value */ public Collection values() { return new ValueView(); } /** * returns a Set view on the keys of the map. * * @return a Set value */ public Set keySet() { return new KeyView(); } /** * Returns a Set view on the entries of the map. * * @return a Set value */ public Set> entrySet() { return new EntryView(); } /** * checks for the presence of val in the values of the map. * * @param val an Object value * @return a boolean value */ public boolean containsValue( Object val ) { Object[] set = _set; V[] vals = _values; // special case null values so that we don't have to // perform null checks before every call to equals() if ( null == val ) { for ( int i = vals.length; i-- > 0; ) { if ( ( set[i] != FREE && set[i] != REMOVED ) && val == vals[i] ) { return true; } } } else { for ( int i = vals.length; i-- > 0; ) { if ( ( set[i] != FREE && set[i] != REMOVED ) && ( val == vals[i] || strategy.equals( ( K ) val, ( K ) vals[i] ) ) ) { return true; } } } // end of else return false; } /** * checks for the present of key in the keys of the map. * * @param key an Object value * @return a boolean value */ public boolean containsKey( Object key ) { return contains( key ); } /** * copies the key/value mappings in map into this map. * * @param map a Map value */ public void putAll( Map map ) { ensureCapacity( map.size() ); // could optimize this for cases when map instanceof TCustomHashMap for ( Map.Entry e : map.entrySet() ) { put( e.getKey(), e.getValue() ); } } /** a view onto the values of the map. */ protected class ValueView extends MapBackedView { @SuppressWarnings({"unchecked"}) public Iterator iterator() { return new TObjectHashIterator( TCustomHashMap.this ) { protected V objectAtIndex( int index ) { return _values[index]; } }; } public boolean containsElement( V value ) { return containsValue( value ); } public boolean removeElement( V value ) { Object[] values = _values; Object[] set = _set; for ( int i = values.length; i-- > 0; ) { if ( ( set[i] != FREE && set[i] != REMOVED ) && value == values[i] || ( null != values[i] && strategy.equals( ( K ) values[i], ( K ) value ) ) ) { removeAt( i ); return true; } } return false; } } /** a view onto the entries of the map. */ protected class EntryView extends MapBackedView> { private final class EntryIterator extends TObjectHashIterator { EntryIterator( TCustomHashMap map ) { super( map ); } @SuppressWarnings({"unchecked"}) public Entry objectAtIndex( final int index ) { return new Entry( (K) _set[index], _values[index], index ); } } @SuppressWarnings({"unchecked"}) public Iterator> iterator() { return new EntryIterator( TCustomHashMap.this ); } public boolean removeElement( Map.Entry entry ) { // have to effectively reimplement Map.remove here // because we need to return true/false depending on // whether the removal took place. Since the Entry's // value can be null, this means that we can't rely // on the value of the object returned by Map.remove() // to determine whether a deletion actually happened. // // Note also that the deletion is only legal if // both the key and the value match. Object val; int index; K key = keyForEntry( entry ); index = index( key ); if ( index >= 0 ) { val = valueForEntry( entry ); if ( val == _values[index] || ( null != val && strategy.equals( ( K ) val, ( K ) _values[index] ) ) ) { removeAt( index ); // clear key,state; adjust size return true; } } return false; } public boolean containsElement( Map.Entry entry ) { Object val = get( keyForEntry( entry ) ); Object entryValue = entry.getValue(); return entryValue == val || ( null != val && strategy.equals( ( K ) val, ( K ) entryValue ) ); } protected V valueForEntry( Map.Entry entry ) { return entry.getValue(); } protected K keyForEntry( Map.Entry entry ) { return entry.getKey(); } } private abstract class MapBackedView extends AbstractSet implements Set, Iterable { public abstract Iterator iterator(); public abstract boolean removeElement( E key ); public abstract boolean containsElement( E key ); @SuppressWarnings({"unchecked"}) public boolean contains( Object key ) { return containsElement( (E) key ); } @SuppressWarnings({"unchecked"}) public boolean remove( Object o ) { return removeElement( (E) o ); } // public boolean containsAll( Collection collection ) { // for ( Object element : collection ) { // if ( !contains( element ) ) { // return false; // } // } // return true; // } public void clear() { TCustomHashMap.this.clear(); } public boolean add( E obj ) { throw new UnsupportedOperationException(); } public int size() { return TCustomHashMap.this.size(); } public Object[] toArray() { Object[] result = new Object[size()]; Iterator e = iterator(); for ( int i = 0; e.hasNext(); i++ ) { result[i] = e.next(); } return result; } @SuppressWarnings({"unchecked"}) public T[] toArray( T[] a ) { int size = size(); if ( a.length < size ) { a = (T[]) java.lang.reflect.Array.newInstance( a.getClass().getComponentType(), size ); } Iterator it = iterator(); Object[] result = a; for ( int i = 0; i < size; i++ ) { result[i] = it.next(); } if ( a.length > size ) { a[size] = null; } return a; } public boolean isEmpty() { return TCustomHashMap.this.isEmpty(); } public boolean addAll( Collection collection ) { throw new UnsupportedOperationException(); } @SuppressWarnings({"SuspiciousMethodCalls"}) public boolean retainAll( Collection collection ) { boolean changed = false; Iterator i = iterator(); while ( i.hasNext() ) { if ( !collection.contains( i.next() ) ) { i.remove(); changed = true; } } return changed; } public String toString() { Iterator i = iterator(); if ( !i.hasNext() ) return "{}"; StringBuilder sb = new StringBuilder(); sb.append( '{' ); for (; ; ) { E e = i.next(); sb.append( e == this ? "(this Collection)" : e ); if ( !i.hasNext() ) return sb.append( '}' ).toString(); sb.append( ", " ); } } } /** a view onto the keys of the map. */ protected class KeyView extends MapBackedView { @SuppressWarnings({"unchecked"}) public Iterator iterator() { return new TObjectHashIterator( TCustomHashMap.this ); } public boolean removeElement( K key ) { return null != TCustomHashMap.this.remove( key ); } public boolean containsElement( K key ) { return TCustomHashMap.this.contains( key ); } } final class Entry implements Map.Entry { private K key; private V val; private final int index; Entry( final K key, V value, final int index ) { this.key = key; this.val = value; this.index = index; } public K getKey() { return key; } public V getValue() { return val; } public V setValue( V o ) { if ( _values[index] != val ) { throw new ConcurrentModificationException(); } // need to return previous value V retval = val; // update this entry's value, in case setValue is called again _values[index] = o; val = o; return retval; } public boolean equals( Object o ) { if ( o instanceof Map.Entry ) { Map.Entry e1 = this; Map.Entry e2 = (Map.Entry) o; return ( e1.getKey() == null ? e2.getKey() == null : strategy.equals( e1.getKey(), ( K ) e2.getKey() ) ) && ( e1.getValue() == null ? e2.getValue() == null : e1.getValue().equals( e2.getValue() ) ); } return false; } public int hashCode() { return ( getKey() == null ? 0 : getKey().hashCode() ) ^ ( getValue() == null ? 0 : getValue().hashCode() ); } @Override public String toString() { return key + "=" + val; } } public void writeExternal( ObjectOutput out ) throws IOException { // VERSION out.writeByte( 1 ); // NOTE: Super was not written in version 0 super.writeExternal( out ); // NUMBER OF ENTRIES out.writeInt( _size ); // ENTRIES for ( int i = _set.length; i-- > 0; ) { if ( _set[i] != REMOVED && _set[i] != FREE ) { out.writeObject( _set[i] ); out.writeObject( _values[i] ); } } } public void readExternal( ObjectInput in ) throws IOException, ClassNotFoundException { // VERSION byte version = in.readByte(); // NOTE: super was not written in version 0 if ( version != 0 ) { super.readExternal( in ); } // NUMBER OF ENTRIES int size = in.readInt(); setUp( size ); // ENTRIES while ( size-- > 0 ) { //noinspection unchecked K key = (K) in.readObject(); //noinspection unchecked V val = (V) in.readObject(); put( key, val ); } } } // TCustomHashMap trove-3.0.3/src/gnu/trove/map/TMap.java0000644000175000017500000000641511763017634016640 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2011, Rob Eden All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.map; import gnu.trove.function.TObjectFunction; import gnu.trove.procedure.TObjectObjectProcedure; import gnu.trove.procedure.TObjectProcedure; import java.util.Map; /** * Interface extension to {@link Map} which adds Trove-specific features. */ public interface TMap extends Map { /** * Inserts a key/value pair into the map if the specified key is not already * associated with a value. * * @param key an Object value * @param value an Object value * @return the previous value associated with key, * or {@code null} if none was found. */ public V putIfAbsent(K key, V value); /** * Executes procedure for each key in the map. * * @param procedure a TObjectProcedure value * @return false if the loop over the keys terminated because * the procedure returned false for some key. */ public boolean forEachKey(TObjectProcedure procedure); /** * Executes procedure for each value in the map. * * @param procedure a TObjectProcedure value * @return false if the loop over the values terminated because * the procedure returned false for some value. */ public boolean forEachValue(TObjectProcedure procedure); /** * Executes procedure for each key/value entry in the * map. * * @param procedure a TObjectObjectProcedure value * @return false if the loop over the entries terminated because * the procedure returned false for some entry. */ @SuppressWarnings({"unchecked"}) public boolean forEachEntry(TObjectObjectProcedure procedure); /** * Retains only those entries in the map for which the procedure * returns a true value. * * @param procedure determines which entries to keep * @return true if the map was modified. */ @SuppressWarnings({"unchecked"}) public boolean retainEntries(TObjectObjectProcedure procedure); /** * Transform the values in this map using function. * * @param function a TObjectFunction value */ public void transformValues(TObjectFunction function); } trove-3.0.3/src/gnu/trove/Version.java0000644000175000017500000000446511763017634016652 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001, Eric D. Friedman All Rights Reserved. // Copyright (c) 2009, Rob Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove; /** * Simple class meant as a possible main class (via manifest) to report the * implementation version of the trove4j jar. *

* This may be useful to ask feedback WITH build version information *

* The Main-Class entry in the manifest.mf should be set during the build as well * as the Implementation-Version manifest attribute should be set as well. *

* Created by IntelliJ IDEA. * User: Johan Parent * Date: 3/03/11 * Time: 22:10 */ public class Version { public static void main(String[] args) { System.out.println(getVersion()); } /** * Returns the implementation version of trove4j. Intended for applications * wanting to return the version of trove4j they are using *

* NOTE: this method will only return a useful version when working * with a trove4j jar as it requires a manifest file * * @return */ public static String getVersion() { String version = Version.class.getPackage().getImplementationVersion(); // if (version != null) { return "trove4j version " + version; } return "Sorry no Implementation-Version manifest attribute available"; } } trove-3.0.3/src/gnu/trove/iterator/0000755000175000017500000000000012000515264016165 5ustar ericherichtrove-3.0.3/src/gnu/trove/iterator/TPrimitiveIterator.java0000644000175000017500000000443111763017634022655 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001, Eric D. Friedman All Rights Reserved. // Copyright (c) 2009, Rob Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.iterator; /** * Implements all iterator functions for the hashed object set. * Subclasses may override objectAtIndex to vary the object * returned by calls to next() (e.g. for values, and Map.Entry * objects). *

*

Note that iteration is fastest if you forego the calls to * hasNext in favor of checking the size of the structure * yourself and then call next() that many times: *

*

 * Iterator i = collection.iterator();
 * for (int size = collection.size(); size-- > 0;) {
 *   Object o = i.next();
 * }
 * 
*

*

You may, of course, use the hasNext(), next() idiom too if * you aren't in a performance critical spot.

*/ public interface TPrimitiveIterator extends TIterator { /** * Returns true if the iterator can be advanced past its current * location. * * @return a boolean value */ public boolean hasNext(); /** * Removes the last entry returned by the iterator. * Invoking this method more than once for a single entry * will leave the underlying data structure in a confused * state. */ public void remove(); } // TPrimitiveIterator trove-3.0.3/src/gnu/trove/iterator/TIterator.java0000644000175000017500000000300511763017634020760 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2009, Rob Eden All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.iterator; /** * Common interface for all iterators used in Trove. */ public interface TIterator { /** * Returns true if the iterator can be advanced past its current location. * * @return a boolean value */ public boolean hasNext(); /** * Removes the last entry returned by the iterator. The result of invoking this method * more than once for a single entry is undefined and can leave the underlying data * structure in a confused state. */ public void remove(); } trove-3.0.3/src/gnu/trove/iterator/hash/0000755000175000017500000000000012000515264017110 5ustar ericherichtrove-3.0.3/src/gnu/trove/iterator/hash/TObjectHashIterator.java0000644000175000017500000000372111763017634023643 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001, Eric D. Friedman All Rights Reserved. // Copyright (c) 2009, Rob Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.iterator.hash; import gnu.trove.impl.hash.TObjectHash; import gnu.trove.impl.hash.THashIterator; /** * Iterator for hashtables that use open addressing to resolve collisions. * * @author Eric D. Friedman * @author Rob Eden * @author Jeff Randall * @version $Id: TObjectHashIterator.java,v 1.1.2.4 2009/10/09 01:44:34 robeden Exp $ */ public class TObjectHashIterator extends THashIterator { protected final TObjectHash _objectHash; public TObjectHashIterator( TObjectHash hash ) { super( hash ); _objectHash = hash; } @SuppressWarnings("unchecked") protected E objectAtIndex( int index ) { Object obj = _objectHash._set[index]; if ( obj == TObjectHash.FREE || obj == TObjectHash.REMOVED ) { return null; } return (E) obj; } } // TObjectHashIterator trove-3.0.3/src/gnu/trove/iterator/TAdvancingIterator.java0000644000175000017500000000254311763017634022601 0ustar ericherich// //////////////////////////////////////////////////////////////////////////// // Copyright (c) 2009, Rob Eden All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // //////////////////////////////////////////////////////////////////////////// package gnu.trove.iterator; /** * Common interface for iterators that operate via the "advance" method for moving the * cursor to the next element. */ public interface TAdvancingIterator extends TIterator { /** * Moves the iterator forward to the next entry. * * @throws java.util.NoSuchElementException if the iterator is already exhausted */ public void advance(); } trove-3.0.3/src/gnu/trove/strategy/0000755000175000017500000000000012000515265016177 5ustar ericherichtrove-3.0.3/src/gnu/trove/strategy/HashingStrategy.java0000644000175000017500000000414211763017634022163 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2002, Eric D. Friedman All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.strategy; import java.io.Serializable; /** * Interface to support pluggable hashing strategies in maps and sets. * Implementers can use this interface to make the trove hashing * algorithms use object values, values provided by the java runtime, * or a custom strategy when computing hashcodes. * * @author Eric Friedman * @author Rob Eden */ public interface HashingStrategy extends Serializable { static final long serialVersionUID = 5674097166776615540L; /** * Computes a hash code for the specified object. Implementers * can use the object's own hashCode method, the Java * runtime's identityHashCode, or a custom scheme. * * @param object for which the hashcode is to be computed * @return the hashCode */ int computeHashCode( T object ); /** * Compares o1 and o2 for equality. Strategy implementers may use * the objects' own equals() methods, compare object references, * or implement some custom scheme. * * @param o1 an Object value * @param o2 an Object value * @return true if the objects are equal according to this strategy. */ boolean equals( T o1, T o2 ); } trove-3.0.3/src/gnu/trove/strategy/IdentityHashingStrategy.java0000644000175000017500000000137111763017634023676 0ustar ericherichpackage gnu.trove.strategy; /** * A {@link gnu.trove.strategy.HashingStrategy} that does identity comparisons * (==) and uses {@link System#identityHashCode(Object)} for hashCode generation. */ public class IdentityHashingStrategy implements HashingStrategy { static final long serialVersionUID = -5188534454583764904L; /** * A single instance that can be shared with multiple collections. * This instance is thread safe. */ public static final IdentityHashingStrategy INSTANCE = new IdentityHashingStrategy(); public int computeHashCode( K object ) { return System.identityHashCode( object ); } public boolean equals( K o1, K o2 ) { return o1 == o2; } } trove-3.0.3/src/gnu/trove/procedure/0000755000175000017500000000000012000515264016324 5ustar ericherichtrove-3.0.3/src/gnu/trove/procedure/TObjectProcedure.java0000644000175000017500000000321011763017634022403 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001, Eric D. Friedman All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.procedure; /** * Interface for procedures with one Object parameter. * * Created: Mon Nov 5 21:45:49 2001 * * @author Eric D. Friedman * @version $Id: TObjectProcedure.java,v 1.1.2.1 2009/09/02 21:52:33 upholderoftruth Exp $ */ public interface TObjectProcedure { /** * Executes this procedure. A false return value indicates that * the application executing this procedure should not invoke this * procedure again. * * @param object an Object value * @return true if additional invocations of the procedure are * allowed. */ public boolean execute(T object); }// TObjectProcedure trove-3.0.3/src/gnu/trove/procedure/array/0000755000175000017500000000000012000515265017443 5ustar ericherichtrove-3.0.3/src/gnu/trove/procedure/array/ToObjectArrayProceedure.java0000644000175000017500000000325211763017634025052 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001, Eric D. Friedman All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.procedure.array; import gnu.trove.procedure.TObjectProcedure; /** * A procedure which stores each value it receives into a target array. *

* Created: Sat Jan 12 10:13:42 2002 * * @author Eric D. Friedman * @version $Id: ToObjectArrayProceedure.java,v 1.1.2.1 2009/09/02 21:52:33 upholderoftruth Exp $ */ public final class ToObjectArrayProceedure implements TObjectProcedure { private final T[] target; private int pos = 0; public ToObjectArrayProceedure( final T[] target ) { this.target = target; } public final boolean execute( T value ) { target[pos++] = value; return true; } } // ToObjectArrayProceduretrove-3.0.3/src/gnu/trove/procedure/TObjectObjectProcedure.java0000644000175000017500000000333311763017634023540 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001, Eric D. Friedman All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.procedure; /** * Interface for procedures that take two Object parameters. *

* Created: Mon Nov 5 22:03:30 2001 * * @author Eric D. Friedman * @version $Id: TObjectObjectProcedure.java,v 1.1.2.1 2009/09/06 17:02:20 upholderoftruth Exp $ */ public interface TObjectObjectProcedure { /** * Executes this procedure. A false return value indicates that * the application executing this procedure should not invoke this * procedure again. * * @param a an Object value * @param b an Object value * @return true if additional invocations of the procedure are * allowed. */ public boolean execute( K a, V b ); }// TObjectObjectProcedure trove-3.0.3/src/gnu/trove/list/0000755000175000017500000000000012000515264015307 5ustar ericherichtrove-3.0.3/src/gnu/trove/list/linked/0000755000175000017500000000000012000515264016555 5ustar ericherichtrove-3.0.3/src/gnu/trove/list/linked/TLinkedList.java0000644000175000017500000006242111763017634021630 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001, Eric D. Friedman All Rights Reserved. // Copyright (c) 2009, Rob Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.list.linked; import gnu.trove.list.TLinkable; import gnu.trove.procedure.TObjectProcedure; import java.io.*; import java.util.AbstractSequentialList; import java.util.ListIterator; import java.util.NoSuchElementException; import java.lang.reflect.Array; /** *

A LinkedList implementation which holds instances of type * TLinkable. *

* Using this implementation allows you to get java.util.LinkedList * behavior (a doubly linked list, with Iterators that support insert * and delete operations) without incurring the overhead of creating * Node wrapper objects for every element in your list. *

* The requirement to achieve this time/space gain is that the * Objects stored in the List implement the TLinkable * interface. *

* The limitations are:

    *
  • the same object cannot be put into more than one list at the same time. *
  • the same object cannot be put into the same list more than once at the same time. *
  • objects must only be removed from list they are in. That is, * if you have an object A and lists l1 and l2, you must ensure that * you invoke List.remove(A) on the correct list. *
  • It is also forbidden to invoke List.remove() with an unaffiliated * TLinkable (one that belongs to no list): this will destroy the list * you invoke it on. *
* * @author Eric D. Friedman * @author Rob Eden * @author Jeff Randall * @version $Id: TLinkedList.java,v 1.1.2.3 2010/09/27 17:23:07 robeden Exp $ * @see gnu.trove.list.TLinkable */ public class TLinkedList> extends AbstractSequentialList implements Externalizable { static final long serialVersionUID = 1L; /** the head of the list */ protected T _head; /** the tail of the list */ protected T _tail; /** the number of elements in the list */ protected int _size = 0; /** Creates a new TLinkedList instance. */ public TLinkedList() { super(); } /** * Returns an iterator positioned at index. Assuming * that the list has a value at that index, calling next() will * retrieve and advance the iterator. Assuming that there is a * value before index in the list, calling previous() * will retrieve it (the value at index - 1) and move the iterator * to that position. So, iterating from front to back starts at * 0; iterating from back to front starts at size(). * * @param index an int value * @return a ListIterator value */ public ListIterator listIterator( int index ) { return new IteratorImpl( index ); } /** * Returns the number of elements in the list. * * @return an int value */ public int size() { return _size; } /** * Inserts linkable at index index in the list. * All values > index are shifted over one position to accommodate * the new addition. * * @param index an int value * @param linkable an object of type TLinkable */ public void add( int index, T linkable ) { if ( index < 0 || index > size() ) { throw new IndexOutOfBoundsException( "index:" + index ); } insert( index, linkable ); } /** * Appends linkable to the end of the list. * * @param linkable an object of type TLinkable * @return always true */ public boolean add( T linkable ) { insert( _size, linkable ); return true; } /** * Inserts linkable at the head of the list. * * @param linkable an object of type TLinkable */ public void addFirst( T linkable ) { insert( 0, linkable ); } /** * Adds linkable to the end of the list. * * @param linkable an object of type TLinkable */ public void addLast( T linkable ) { insert( size(), linkable ); } /** Empties the list. */ public void clear() { if ( null != _head ) { for ( TLinkable link = _head.getNext(); link != null; link = link.getNext() ) { TLinkable prev = link.getPrevious(); prev.setNext( null ); link.setPrevious( null ); } _head = _tail = null; } _size = 0; } /** * Copies the list's contents into a native array. This will be a * shallow copy: the Tlinkable instances in the Object[] array * have links to one another: changing those will put this list * into an unpredictable state. Holding a reference to one * element in the list will prevent the others from being garbage * collected unless you clear the next/previous links. Caveat * programmer! * * @return an Object[] value */ public Object[] toArray() { Object[] o = new Object[_size]; int i = 0; for ( TLinkable link = _head; link != null; link = link.getNext() ) { o[i++] = link; } return o; } /** * Copies the list to a native array, destroying the next/previous * links as the copy is made. This list will be emptied after the * copy (as if clear() had been invoked). The Object[] array * returned will contain TLinkables that do not hold * references to one another and so are less likely to be the * cause of memory leaks. * * @return an Object[] value */ public Object[] toUnlinkedArray() { Object[] o = new Object[_size]; int i = 0; for ( TLinkable link = _head, tmp; link != null; i++ ) { o[i] = link; tmp = link; link = link.getNext(); tmp.setNext( null ); // clear the links tmp.setPrevious( null ); } _size = 0; // clear the list _head = _tail = null; return o; } /** * Returns a typed array of the objects in the set. * * @param a an Object[] value * @return an Object[] value */ @SuppressWarnings({"unchecked"}) public T[] toUnlinkedArray( T[] a ) { int size = size(); if ( a.length < size ) { a = (T[]) Array.newInstance( a.getClass().getComponentType(), size ); } int i = 0; for ( T link = _head, tmp; link != null; i++ ) { a[i] = link; tmp = link; link = link.getNext(); tmp.setNext( null ); // clear the links tmp.setPrevious( null ); } _size = 0; // clear the list _head = _tail = null; return a; } /** * A linear search for o in the list. * * @param o an Object value * @return a boolean value */ public boolean contains( Object o ) { for ( TLinkable link = _head; link != null; link = link.getNext() ) { if ( o.equals( link ) ) { return true; } } return false; } /** {@inheritDoc} */ @Override @SuppressWarnings({"unchecked"}) public T get( int index ) { // Blow out for bogus values if ( index < 0 || index >= _size ) { throw new IndexOutOfBoundsException( "Index: " + index + ", Size: " + _size ); } // Determine if it's better to get there from the front or the back if ( index > ( _size >> 1 ) ) { int position = _size - 1; T node = _tail; while ( position > index ) { node = node.getPrevious(); position--; } return node; } else { int position = 0; T node = _head; while ( position < index ) { node = node.getNext(); position++; } return node; } } /** * Returns the head of the list * * @return an Object value */ public T getFirst() { return _head; } /** * Returns the tail of the list. * * @return an Object value */ public T getLast() { return _tail; } /** * Return the node following the given node. This method exists for two reasons: *
    *
  1. It's really not recommended that the methods implemented by TLinkable be * called directly since they're used internally by this class.
  2. *
  3. This solves problems arising from generics when working with the linked * objects directly.
  4. *
*

* NOTE: this should only be used with nodes contained in the list. The results are * undefined with anything else. * * @param current The current node * @return the node after the current node */ @SuppressWarnings({"unchecked"}) public T getNext( T current ) { return current.getNext(); } /** * Return the node preceding the given node. This method exists for two reasons: *

    *
  1. It's really not recommended that the methods implemented by TLinkable be * called directly since they're used internally by this class.
  2. *
  3. This solves problems arising from generics when working with the linked * objects directly.
  4. *
*

* NOTE: this should only be used with nodes contained in the list. The results are * undefined with anything else. * * @param current The current node * @return the node after the current node */ @SuppressWarnings({"unchecked"}) public T getPrevious( T current ) { return current.getPrevious(); } /** * Remove and return the first element in the list. * * @return an Object value */ @SuppressWarnings({"unchecked"}) public T removeFirst() { T o = _head; if ( o == null ) { return null; } T n = o.getNext(); o.setNext( null ); if ( null != n ) { n.setPrevious( null ); } _head = n; if ( --_size == 0 ) { _tail = null; } return o; } /** * Remove and return the last element in the list. * * @return an Object value */ @SuppressWarnings({"unchecked"}) public T removeLast() { T o = _tail; if ( o == null ) { return null; } T prev = o.getPrevious(); o.setPrevious( null ); if ( null != prev ) { prev.setNext( null ); } _tail = prev; if ( --_size == 0 ) { _head = null; } return o; } /** * Implementation of index-based list insertions. * * @param index an int value * @param linkable an object of type TLinkable */ @SuppressWarnings({"unchecked"}) protected void insert( int index, T linkable ) { if ( _size == 0 ) { _head = _tail = linkable; // first insertion } else if ( index == 0 ) { linkable.setNext( _head ); // insert at front _head.setPrevious( linkable ); _head = linkable; } else if ( index == _size ) { // insert at back _tail.setNext( linkable ); linkable.setPrevious( _tail ); _tail = linkable; } else { T node = get( index ); T before = node.getPrevious(); if ( before != null ) { before.setNext( linkable ); } linkable.setPrevious( before ); linkable.setNext( node ); node.setPrevious( linkable ); } _size++; } /** * Removes the specified element from the list. Note that * it is the caller's responsibility to ensure that the * element does, in fact, belong to this list and not another * instance of TLinkedList. * * @param o a TLinkable element already inserted in this list. * @return true if the element was a TLinkable and removed */ @SuppressWarnings({"unchecked"}) public boolean remove( Object o ) { if ( o instanceof TLinkable ) { T p, n; TLinkable link = (TLinkable) o; p = link.getPrevious(); n = link.getNext(); if ( n == null && p == null ) { // emptying the list // It's possible this object is not something that's in the list. So, // make sure it's the head if it doesn't point to anything. This solves // problems caused by removing something multiple times. if ( o != _head ) { return false; } _head = _tail = null; } else if ( n == null ) { // this is the tail // make previous the new tail link.setPrevious( null ); p.setNext( null ); _tail = p; } else if ( p == null ) { // this is the head // make next the new head link.setNext( null ); n.setPrevious( null ); _head = n; } else { // somewhere in the middle p.setNext( n ); n.setPrevious( p ); link.setNext( null ); link.setPrevious( null ); } _size--; // reduce size of list return true; } else { return false; } } /** * Inserts newElement into the list immediately before current. * All elements to the right of and including current are shifted * over. * * @param current a TLinkable value currently in the list. * @param newElement a TLinkable value to be added to * the list. */ public void addBefore( T current, T newElement ) { if ( current == _head ) { addFirst( newElement ); } else if ( current == null ) { addLast( newElement ); } else { T p = current.getPrevious(); newElement.setNext( current ); p.setNext( newElement ); newElement.setPrevious( p ); current.setPrevious( newElement ); _size++; } } /** * Inserts newElement into the list immediately after current. * All elements to the left of and including current are shifted * over. * * @param current a TLinkable value currently in the list. * @param newElement a TLinkable value to be added to * the list. */ public void addAfter( T current, T newElement ) { if ( current == _tail ) { addLast( newElement ); } else if ( current == null ) { addFirst( newElement ); } else { T n = current.getNext(); newElement.setPrevious( current ); newElement.setNext( n ); current.setNext( newElement ); n.setPrevious( newElement ); _size++; } } /** * Executes procedure for each entry in the list. * * @param procedure a TObjectProcedure value * @return false if the loop over the values terminated because * the procedure returned false for some value. */ @SuppressWarnings({"unchecked"}) public boolean forEachValue( TObjectProcedure procedure ) { T node = _head; while ( node != null ) { boolean keep_going = procedure.execute( node ); if ( !keep_going ) { return false; } node = node.getNext(); } return true; } public void writeExternal( ObjectOutput out ) throws IOException { // VERSION out.writeByte( 0 ); // NUMBER OF ENTRIES out.writeInt( _size ); // HEAD out.writeObject( _head ); // TAIL out.writeObject( _tail ); } @SuppressWarnings({"unchecked"}) public void readExternal( ObjectInput in ) throws IOException, ClassNotFoundException { // VERSION in.readByte(); // NUMBER OF ENTRIED _size = in.readInt(); // HEAD _head = (T) in.readObject(); // TAIL _tail = (T) in.readObject(); } /** A ListIterator that supports additions and deletions. */ protected final class IteratorImpl implements ListIterator { private int _nextIndex = 0; private T _next; private T _lastReturned; /** * Creates a new Iterator instance positioned at * index. * * @param position an int value */ @SuppressWarnings({"unchecked"}) IteratorImpl( int position ) { if ( position < 0 || position > _size ) { throw new IndexOutOfBoundsException(); } _nextIndex = position; if ( position == 0 ) { _next = _head; } else if ( position == _size ) { _next = null; } else if ( position < ( _size >> 1 ) ) { int pos = 0; for ( _next = _head; pos < position; pos++ ) { _next = _next.getNext(); } } else { int pos = _size - 1; for ( _next = _tail; pos > position; pos-- ) { _next = _next.getPrevious(); } } } /** * Insert linkable at the current position of the iterator. * Calling next() after add() will return the added object. * * @param linkable an object of type TLinkable */ public final void add( T linkable ) { _lastReturned = null; _nextIndex++; if ( _size == 0 ) { TLinkedList.this.add( linkable ); } else { TLinkedList.this.addBefore( _next, linkable ); } } /** * True if a call to next() will return an object. * * @return a boolean value */ public final boolean hasNext() { return _nextIndex != _size; } /** * True if a call to previous() will return a value. * * @return a boolean value */ public final boolean hasPrevious() { return _nextIndex != 0; } /** * Returns the value at the Iterator's index and advances the * iterator. * * @return an Object value * @throws NoSuchElementException if there is no next element */ @SuppressWarnings({"unchecked"}) public final T next() { if ( _nextIndex == _size ) { throw new NoSuchElementException(); } _lastReturned = _next; _next = _next.getNext(); _nextIndex++; return _lastReturned; } /** * returns the index of the next node in the list (the * one that would be returned by a call to next()). * * @return an int value */ public final int nextIndex() { return _nextIndex; } /** * Returns the value before the Iterator's index and moves the * iterator back one index. * * @return an Object value * @throws NoSuchElementException if there is no previous element. */ @SuppressWarnings({"unchecked"}) public final T previous() { if ( _nextIndex == 0 ) { throw new NoSuchElementException(); } if ( _nextIndex == _size ) { _lastReturned = _next = _tail; } else { _lastReturned = _next = _next.getPrevious(); } _nextIndex--; return _lastReturned; } /** * Returns the previous element's index. * * @return an int value */ public final int previousIndex() { return _nextIndex - 1; } /** * Removes the current element in the list and shrinks its * size accordingly. * * @throws IllegalStateException neither next nor previous * have been invoked, or remove or add have been invoked after * the last invocation of next or previous. */ @SuppressWarnings({"unchecked"}) public final void remove() { if ( _lastReturned == null ) { throw new IllegalStateException( "must invoke next or previous before invoking remove" ); } if ( _lastReturned != _next ) { _nextIndex--; } _next = _lastReturned.getNext(); TLinkedList.this.remove( _lastReturned ); _lastReturned = null; } /** * Replaces the current element in the list with * linkable * * @param linkable an object of type TLinkable */ public final void set( T linkable ) { if ( _lastReturned == null ) { throw new IllegalStateException(); } swap( _lastReturned, linkable ); _lastReturned = linkable; } /** * Replace from with to in the list. * * @param from a TLinkable value * @param to a TLinkable value */ private void swap( T from, T to ) { T from_p = from.getPrevious(); T from_n = from.getNext(); T to_p = to.getPrevious(); T to_n = to.getNext(); // NOTE: 'to' cannot be null at this point if ( from_n == to ) { if ( from_p != null ) from_p.setNext( to ); to.setPrevious( from_p ); to.setNext( from ); from.setPrevious( to ); from.setNext( to_n ); if ( to_n != null ) to_n.setPrevious( from ); } // NOTE: 'from' cannot be null at this point else if ( to_n == from ) { if ( to_p != null ) to_p.setNext( to ); to.setPrevious( from ); to.setNext( from_n ); from.setPrevious( to_p ); from.setNext( to ); if ( from_n != null ) from_n.setPrevious( to ); } else { from.setNext( to_n ); from.setPrevious( to_p ); if ( to_p != null ) to_p.setNext( from ); if ( to_n != null ) to_n.setPrevious( from ); to.setNext( from_n ); to.setPrevious( from_p ); if ( from_p != null ) from_p.setNext( to ); if ( from_n != null ) from_n.setPrevious( to ); } if ( _head == from ) _head = to; else if ( _head == to ) _head = from; if ( _tail == from ) _tail = to; else if ( _tail == to ) _tail = from; if ( _lastReturned == from ) _lastReturned = to; else if ( _lastReturned == to ) _lastReturned = from; if ( _next == from ) _next = to; else if ( _next == to ) _next = from; } } } // TLinkedList trove-3.0.3/src/gnu/trove/list/TLinkable.java0000644000175000017500000000405511763017634020040 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001, Eric D. Friedman All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.list; import java.io.Serializable; /** * Interface for Objects which can be inserted into a TLinkedList. * * @author Eric D. Friedman * @version $Id: TLinkable.java,v 1.1.2.2 2009/09/04 12:32:33 upholderoftruth Exp $ * @see gnu.trove.list.linked.TLinkedList */ public interface TLinkable extends Serializable { static final long serialVersionUID = 997545054865482562L; /** * Returns the linked list node after this one. * * @return a TLinkable value */ public T getNext(); /** * Returns the linked list node before this one. * * @return a TLinkable value */ public T getPrevious(); /** * Sets the linked list node after this one. * * @param linkable a TLinkable value */ public void setNext( T linkable ); /** * Sets the linked list node before this one. * * @param linkable a TLinkable value */ public void setPrevious( T linkable ); }// TLinkable trove-3.0.3/src/gnu/trove/list/TLinkableAdapter.java0000644000175000017500000000133311763017634021335 0ustar ericherichpackage gnu.trove.list; /** * Simple adapter class implementing {@link TLinkable}, so you don't have to. Example: *

	private class MyObject extends TLinkableAdapter {
		private final String value;

		MyObject( String value ) {
			this.value = value;
		}
		
		public String getValue() {
			return value;
		}
	}
 * 
*/ public abstract class TLinkableAdapter implements TLinkable { private volatile T next; private volatile T prev; @Override public T getNext() { return next; } @Override public void setNext( T next ) { this.next = next; } @Override public T getPrevious() { return prev; } @Override public void setPrevious( T prev ) { this.prev = prev; } } trove-3.0.3/src/gnu/trove/impl/0000755000175000017500000000000012000515264015275 5ustar ericherichtrove-3.0.3/src/gnu/trove/impl/sync/0000755000175000017500000000000012000515264016251 5ustar ericherichtrove-3.0.3/src/gnu/trove/impl/sync/SynchronizedSet.java0000644000175000017500000000272211763017634022267 0ustar ericherich// //////////////////////////////////////////////////////////////////////////// // Copyright (c) 2009, Rob Eden All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // //////////////////////////////////////////////////////////////////////////// package gnu.trove.impl.sync; import java.util.Set; /** Local implementation of SynchronizedSet so we can set the mutex explicitly. */ class SynchronizedSet extends SynchronizedCollection implements Set { private static final long serialVersionUID = 487447009682186044L; SynchronizedSet( Set s, Object mutex ) { super( s, mutex ); } public boolean equals( Object o ) { synchronized( mutex ) { return c.equals( o ); } } public int hashCode() { synchronized( mutex ) { return c.hashCode(); } } }trove-3.0.3/src/gnu/trove/impl/sync/SynchronizedCollection.java0000644000175000017500000000571211763017634023631 0ustar ericherich// //////////////////////////////////////////////////////////////////////////// // Copyright (c) 2009, Rob Eden All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // //////////////////////////////////////////////////////////////////////////// package gnu.trove.impl.sync; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Collection; import java.util.Iterator; /** * */ class SynchronizedCollection implements Collection, Serializable { private static final long serialVersionUID = 3053995032091335093L; final Collection c; // Backing Collection final Object mutex; // Object on which to synchronize SynchronizedCollection( Collection c, Object mutex ) { this.c = c; this.mutex = mutex; } public int size() { synchronized( mutex ) { return c.size(); } } public boolean isEmpty() { synchronized( mutex ) { return c.isEmpty(); } } public boolean contains( Object o ) { synchronized( mutex ) { return c.contains( o ); } } public Object[] toArray() { synchronized( mutex ) { return c.toArray(); } } @SuppressWarnings({"SuspiciousToArrayCall"}) public T[] toArray( T[] a ) { synchronized( mutex ) { return c.toArray( a ); } } public Iterator iterator() { return c.iterator(); // Must be manually synched by user! } public boolean add( E e ) { synchronized( mutex ) { return c.add( e ); } } public boolean remove( Object o ) { synchronized( mutex ) { return c.remove( o ); } } public boolean containsAll( Collection coll ) { synchronized( mutex ) { return c.containsAll( coll ); } } public boolean addAll( Collection coll ) { synchronized( mutex ) { return c.addAll( coll ); } } public boolean removeAll( Collection coll ) { synchronized( mutex ) { return c.removeAll( coll ); } } public boolean retainAll( Collection coll ) { synchronized( mutex ) { return c.retainAll( coll ); } } public void clear() { synchronized( mutex ) { c.clear(); } } public String toString() { synchronized( mutex ) { return c.toString(); } } private void writeObject( ObjectOutputStream s ) throws IOException { synchronized( mutex ) { s.defaultWriteObject(); } } }trove-3.0.3/src/gnu/trove/impl/hash/0000755000175000017500000000000012000515264016220 5ustar ericherichtrove-3.0.3/src/gnu/trove/impl/hash/TPrimitiveHash.java0000644000175000017500000001077311763017634022010 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001, Eric D. Friedman All Rights Reserved. // Copyright (c) 2009, Rob Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.impl.hash; import gnu.trove.impl.HashFunctions; /** * The base class for hashtables of primitive values. Since there is * no notion of object equality for primitives, it isn't possible to * use a `REMOVED' object to track deletions in an open-addressed table. * So, we have to resort to using a parallel `bookkeeping' array of bytes, * in which flags can be set to indicate that a particular slot in the * hash table is FREE, FULL, or REMOVED. * * @author Eric D. Friedman, Rob Eden, Jeff Randall * @version $Id: TPrimitiveHash.java,v 1.1.2.6 2010/03/01 23:39:07 robeden Exp $ */ abstract public class TPrimitiveHash extends THash { @SuppressWarnings( { "UnusedDeclaration" } ) static final long serialVersionUID = 1L; /** * flags indicating whether each position in the hash is * FREE, FULL, or REMOVED */ public transient byte[] _states; /* constants used for state flags */ /** flag indicating that a slot in the hashtable is available */ public static final byte FREE = 0; /** flag indicating that a slot in the hashtable is occupied */ public static final byte FULL = 1; /** * flag indicating that the value of a slot in the hashtable * was deleted */ public static final byte REMOVED = 2; /** * Creates a new THash instance with the default * capacity and load factor. */ public TPrimitiveHash() { super(); } /** * Creates a new TPrimitiveHash instance with a prime * capacity at or near the specified capacity and with the default * load factor. * * @param initialCapacity an int value */ public TPrimitiveHash( int initialCapacity ) { this( initialCapacity, DEFAULT_LOAD_FACTOR ); } /** * Creates a new TPrimitiveHash instance with a prime * capacity at or near the minimum needed to hold * initialCapacity elements with load factor * loadFactor without triggering a rehash. * * @param initialCapacity an int value * @param loadFactor a float value */ public TPrimitiveHash( int initialCapacity, float loadFactor ) { super(); initialCapacity = Math.max( 1, initialCapacity ); _loadFactor = loadFactor; setUp( HashFunctions.fastCeil( initialCapacity / loadFactor ) ); } /** * Returns the capacity of the hash table. This is the true * physical capacity, without adjusting for the load factor. * * @return the physical capacity of the hash table. */ public int capacity() { return _states.length; } /** * Delete the record at index. * * @param index an int value */ protected void removeAt( int index ) { _states[index] = REMOVED; super.removeAt( index ); } /** * initializes the hashtable to a prime capacity which is at least * initialCapacity + 1. * * @param initialCapacity an int value * @return the actual capacity chosen */ protected int setUp( int initialCapacity ) { int capacity; capacity = super.setUp( initialCapacity ); _states = new byte[capacity]; return capacity; } } // TPrimitiveHashtrove-3.0.3/src/gnu/trove/impl/hash/THashIterator.java0000644000175000017500000001273211763017634021626 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001, Eric D. Friedman All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.impl.hash; import gnu.trove.iterator.TIterator; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.NoSuchElementException; /** * Implements all iterator functions for the hashed object set. * Subclasses may override objectAtIndex to vary the object * returned by calls to next() (e.g. for values, and Map.Entry * objects). *

*

Note that iteration is fastest if you forego the calls to * hasNext in favor of checking the size of the structure * yourself and then call next() that many times: *

*

 * Iterator i = collection.iterator();
 * for (int size = collection.size(); size-- > 0;) {
 *   Object o = i.next();
 * }
 * 
*

*

You may, of course, use the hasNext(), next() idiom too if * you aren't in a performance critical spot.

*/ public abstract class THashIterator implements TIterator, Iterator { private final TObjectHash _object_hash; /** the data structure this iterator traverses */ protected final THash _hash; /** * the number of elements this iterator believes are in the * data structure it accesses. */ protected int _expectedSize; /** the index used for iteration. */ protected int _index; /** * Create an instance of THashIterator over the values of the TObjectHash * * @param hash the object */ protected THashIterator( TObjectHash hash ) { _hash = hash; _expectedSize = _hash.size(); _index = _hash.capacity(); _object_hash = hash; } /** * Moves the iterator to the next Object and returns it. * * @return an Object value * @throws ConcurrentModificationException * if the structure * was changed using a method that isn't on this iterator. * @throws NoSuchElementException if this is called on an * exhausted iterator. */ public V next() { moveToNextIndex(); return objectAtIndex( _index ); } /** * Returns true if the iterator can be advanced past its current * location. * * @return a boolean value */ public boolean hasNext() { return nextIndex() >= 0; } /** * Removes the last entry returned by the iterator. * Invoking this method more than once for a single entry * will leave the underlying data structure in a confused * state. */ public void remove() { if ( _expectedSize != _hash.size() ) { throw new ConcurrentModificationException(); } // Disable auto compaction during the remove. This is a workaround for bug 1642768. try { _hash.tempDisableAutoCompaction(); _hash.removeAt( _index ); } finally { _hash.reenableAutoCompaction( false ); } _expectedSize--; } /** * Sets the internal index so that the `next' object * can be returned. */ protected final void moveToNextIndex() { // doing the assignment && < 0 in one line shaves // 3 opcodes... if ( ( _index = nextIndex() ) < 0 ) { throw new NoSuchElementException(); } } /** * Returns the index of the next value in the data structure * or a negative value if the iterator is exhausted. * * @return an int value * @throws ConcurrentModificationException * if the underlying * collection's size has been modified since the iterator was * created. */ protected final int nextIndex() { if ( _expectedSize != _hash.size() ) { throw new ConcurrentModificationException(); } Object[] set = _object_hash._set; int i = _index; while ( i-- > 0 && ( set[i] == TObjectHash.FREE || set[i] == TObjectHash.REMOVED ) ) { ; } return i; } /** * Returns the object at the specified index. Subclasses should * implement this to return the appropriate object for the given * index. * * @param index the index of the value to return. * @return an Object value */ abstract protected V objectAtIndex( int index ); } // THashIterator trove-3.0.3/src/gnu/trove/impl/hash/THash.java0000644000175000017500000003342311763017634020114 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001, Eric D. Friedman All Rights Reserved. // Copyright (c) 2009, Rob Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.impl.hash; import gnu.trove.impl.Constants; import gnu.trove.impl.HashFunctions; import gnu.trove.impl.PrimeFinder; import java.io.Externalizable; import java.io.ObjectOutput; import java.io.IOException; import java.io.ObjectInput; /** * Base class for hashtables that use open addressing to resolve * collisions. * * Created: Wed Nov 28 21:11:16 2001 * * @author Eric D. Friedman * @author Rob Eden (auto-compaction) * @author Jeff Randall * * @version $Id: THash.java,v 1.1.2.4 2010/03/02 00:55:34 robeden Exp $ */ abstract public class THash implements Externalizable { @SuppressWarnings( { "UnusedDeclaration" } ) static final long serialVersionUID = -1792948471915530295L; /** the load above which rehashing occurs. */ protected static final float DEFAULT_LOAD_FACTOR = Constants.DEFAULT_LOAD_FACTOR; /** * the default initial capacity for the hash table. This is one * less than a prime value because one is added to it when * searching for a prime capacity to account for the free slot * required by open addressing. Thus, the real default capacity is * 11. */ protected static final int DEFAULT_CAPACITY = Constants.DEFAULT_CAPACITY; /** the current number of occupied slots in the hash. */ protected transient int _size; /** the current number of free slots in the hash. */ protected transient int _free; /** * Determines how full the internal table can become before * rehashing is required. This must be a value in the range: 0.0 < * loadFactor < 1.0. The default value is 0.5, which is about as * large as you can get in open addressing without hurting * performance. Cf. Knuth, Volume 3., Chapter 6. */ protected float _loadFactor; /** * The maximum number of elements allowed without allocating more * space. */ protected int _maxSize; /** The number of removes that should be performed before an auto-compaction occurs. */ protected int _autoCompactRemovesRemaining; /** * The auto-compaction factor for the table. * * @see #setAutoCompactionFactor */ protected float _autoCompactionFactor; /** @see #tempDisableAutoCompaction */ protected transient boolean _autoCompactTemporaryDisable = false; /** * Creates a new THash instance with the default * capacity and load factor. */ public THash() { this( DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR ); } /** * Creates a new THash instance with a prime capacity * at or near the specified capacity and with the default load * factor. * * @param initialCapacity an int value */ public THash( int initialCapacity ) { this( initialCapacity, DEFAULT_LOAD_FACTOR ); } /** * Creates a new THash instance with a prime capacity * at or near the minimum needed to hold initialCapacity * elements with load factor loadFactor without triggering * a rehash. * * @param initialCapacity an int value * @param loadFactor a float value */ public THash( int initialCapacity, float loadFactor ) { super(); _loadFactor = loadFactor; // Through testing, the load factor (especially the default load factor) has been // found to be a pretty good starting auto-compaction factor. _autoCompactionFactor = loadFactor; setUp( HashFunctions.fastCeil( initialCapacity / loadFactor ) ); } /** * Tells whether this set is currently holding any elements. * * @return a boolean value */ public boolean isEmpty() { return 0 == _size; } /** * Returns the number of distinct elements in this collection. * * @return an int value */ public int size() { return _size; } /** @return the current physical capacity of the hash table. */ abstract public int capacity(); /** * Ensure that this hashtable has sufficient capacity to hold * desiredCapacity additional elements without * requiring a rehash. This is a tuning method you can call * before doing a large insert. * * @param desiredCapacity an int value */ public void ensureCapacity( int desiredCapacity ) { if ( desiredCapacity > ( _maxSize - size() ) ) { rehash( PrimeFinder.nextPrime( Math.max( size() + 1, HashFunctions.fastCeil( ( desiredCapacity + size() ) / _loadFactor ) + 1 ) ) ); computeMaxSize( capacity() ); } } /** * Compresses the hashtable to the minimum prime size (as defined * by PrimeFinder) that will hold all of the elements currently in * the table. If you have done a lot of remove * operations and plan to do a lot of queries or insertions or * iteration, it is a good idea to invoke this method. Doing so * will accomplish two things: *

*

    *
  1. You'll free memory allocated to the table but no * longer needed because of the remove()s.
  2. *

    *

  3. You'll get better query/insert/iterator performance * because there won't be any REMOVED slots to skip * over when probing for indices in the table.
  4. *
*/ public void compact() { // need at least one free spot for open addressing rehash( PrimeFinder.nextPrime( Math.max( _size + 1, HashFunctions.fastCeil( size() / _loadFactor ) + 1 ) ) ); computeMaxSize( capacity() ); // If auto-compaction is enabled, re-determine the compaction interval if ( _autoCompactionFactor != 0 ) { computeNextAutoCompactionAmount( size() ); } } /** * The auto-compaction factor controls whether and when a table performs a * {@link #compact} automatically after a certain number of remove operations. * If the value is non-zero, the number of removes that need to occur for * auto-compaction is the size of table at the time of the previous compaction * (or the initial capacity) multiplied by this factor. *

* Setting this value to zero will disable auto-compaction. * * @param factor a float that indicates the auto-compaction factor */ public void setAutoCompactionFactor( float factor ) { if ( factor < 0 ) { throw new IllegalArgumentException( "Factor must be >= 0: " + factor ); } _autoCompactionFactor = factor; } /** * @see #setAutoCompactionFactor * * @return a <float that represents the auto-compaction factor. */ public float getAutoCompactionFactor() { return _autoCompactionFactor; } /** * This simply calls {@link #compact compact}. It is included for * symmetry with other collection classes. Note that the name of this * method is somewhat misleading (which is why we prefer * compact) as the load factor may require capacity above * and beyond the size of this collection. * * @see #compact */ public final void trimToSize() { compact(); } /** * Delete the record at index. Reduces the size of the * collection by one. * * @param index an int value */ protected void removeAt( int index ) { _size--; // If auto-compaction is enabled, see if we need to compact if ( _autoCompactionFactor != 0 ) { _autoCompactRemovesRemaining--; if ( !_autoCompactTemporaryDisable && _autoCompactRemovesRemaining <= 0 ) { // Do the compact // NOTE: this will cause the next compaction interval to be calculated compact(); } } } /** Empties the collection. */ public void clear() { _size = 0; _free = capacity(); } /** * initializes the hashtable to a prime capacity which is at least * initialCapacity + 1. * * @param initialCapacity an int value * @return the actual capacity chosen */ protected int setUp( int initialCapacity ) { int capacity; capacity = PrimeFinder.nextPrime( initialCapacity ); computeMaxSize( capacity ); computeNextAutoCompactionAmount( initialCapacity ); return capacity; } /** * Rehashes the set. * * @param newCapacity an int value */ protected abstract void rehash( int newCapacity ); /** * Temporarily disables auto-compaction. MUST be followed by calling * {@link #reenableAutoCompaction}. */ public void tempDisableAutoCompaction() { _autoCompactTemporaryDisable = true; } /** * Re-enable auto-compaction after it was disabled via * {@link #tempDisableAutoCompaction()}. * * @param check_for_compaction True if compaction should be performed if needed * before returning. If false, no compaction will be * performed. */ public void reenableAutoCompaction( boolean check_for_compaction ) { _autoCompactTemporaryDisable = false; if ( check_for_compaction && _autoCompactRemovesRemaining <= 0 && _autoCompactionFactor != 0 ) { // Do the compact // NOTE: this will cause the next compaction interval to be calculated compact(); } } /** * Computes the values of maxSize. There will always be at least * one free slot required. * * @param capacity an int value */ protected void computeMaxSize( int capacity ) { // need at least one free slot for open addressing _maxSize = Math.min( capacity - 1, (int) ( capacity * _loadFactor ) ); _free = capacity - _size; // reset the free element count } /** * Computes the number of removes that need to happen before the next auto-compaction * will occur. * * @param size an int that sets the auto-compaction limit. */ protected void computeNextAutoCompactionAmount( int size ) { if ( _autoCompactionFactor != 0 ) { // NOTE: doing the round ourselves has been found to be faster than using // Math.round. _autoCompactRemovesRemaining = (int) ( ( size * _autoCompactionFactor ) + 0.5f ); } } /** * After an insert, this hook is called to adjust the size/free * values of the set and to perform rehashing if necessary. * * @param usedFreeSlot the slot */ protected final void postInsertHook( boolean usedFreeSlot ) { if ( usedFreeSlot ) { _free--; } // rehash whenever we exhaust the available space in the table if ( ++_size > _maxSize || _free == 0 ) { // choose a new capacity suited to the new state of the table // if we've grown beyond our maximum size, double capacity; // if we've exhausted the free spots, rehash to the same capacity, // which will free up any stale removed slots for reuse. int newCapacity = _size > _maxSize ? PrimeFinder.nextPrime( capacity() << 1 ) : capacity(); rehash( newCapacity ); computeMaxSize( capacity() ); } } protected int calculateGrownCapacity() { return capacity() << 1; } public void writeExternal( ObjectOutput out ) throws IOException { // VERSION out.writeByte( 0 ); // LOAD FACTOR out.writeFloat( _loadFactor ); // AUTO COMPACTION LOAD FACTOR out.writeFloat( _autoCompactionFactor ); } public void readExternal( ObjectInput in ) throws IOException, ClassNotFoundException { // VERSION in.readByte(); // LOAD FACTOR float old_factor = _loadFactor; _loadFactor = in.readFloat(); // AUTO COMPACTION LOAD FACTOR _autoCompactionFactor = in.readFloat(); // If we change the laod factor from the default, re-setup if ( old_factor != _loadFactor ) { setUp( (int) Math.ceil( DEFAULT_CAPACITY / _loadFactor ) ); } } }// THashtrove-3.0.3/src/gnu/trove/impl/hash/TCustomObjectHash.java0000644000175000017500000000763111763017634022440 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001, Eric D. Friedman All Rights Reserved. // Copyright (c) 2009, Rob Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.impl.hash; import gnu.trove.strategy.HashingStrategy; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; /** * An open addressed hashing implementation for Object types. * * @author Rob Eden * @author Eric D. Friedman * @author Jeff Randall * @version $Id: TObjectHash.java,v 1.1.2.6 2009/11/07 03:36:44 robeden Exp $ */ @SuppressWarnings( { "UnusedDeclaration" } ) abstract public class TCustomObjectHash extends TObjectHash { static final long serialVersionUID = 8766048185963756400L; protected HashingStrategy strategy; /** FOR EXTERNALIZATION ONLY!!! */ public TCustomObjectHash() {} /** * Creates a new TManualObjectHash instance with the * default capacity and load factor. */ public TCustomObjectHash( HashingStrategy strategy ) { super(); this.strategy = strategy; } /** * Creates a new TManualObjectHash instance whose capacity * is the next highest prime above initialCapacity + 1 * unless that value is already prime. * * @param initialCapacity an int value */ public TCustomObjectHash( HashingStrategy strategy, int initialCapacity ) { super( initialCapacity ); this.strategy = strategy; } /** * Creates a new TManualObjectHash instance with a prime * value at or near the specified capacity and load factor. * * @param initialCapacity used to find a prime capacity for the table. * @param loadFactor used to calculate the threshold over which * rehashing takes place. */ public TCustomObjectHash( HashingStrategy strategy, int initialCapacity, float loadFactor ) { super( initialCapacity, loadFactor ); this.strategy = strategy; } @Override protected int hash( Object obj ) { //noinspection unchecked return strategy.computeHashCode( ( T ) obj ); } @Override protected boolean equals( Object one, Object two ) { //noinspection unchecked return two != REMOVED && strategy.equals( ( T ) one, ( T ) two ); } @Override public void writeExternal( ObjectOutput out ) throws IOException { // VERSION out.writeByte( 0 ); // SUPER super.writeExternal( out ); // STRATEGY out.writeObject( strategy ); } @Override public void readExternal( ObjectInput in ) throws IOException, ClassNotFoundException { // VERSION in.readByte(); // SUPER super.readExternal( in ); // STRATEGY //noinspection unchecked strategy = ( HashingStrategy ) in.readObject(); } } // TCustomObjectHash trove-3.0.3/src/gnu/trove/impl/hash/TObjectHash.java0000644000175000017500000005012111763017634021235 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001, Eric D. Friedman All Rights Reserved. // Copyright (c) 2009, Rob Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.impl.hash; import gnu.trove.procedure.TObjectProcedure; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Arrays; import java.util.HashSet; import java.util.Set; /** * An open addressed hashing implementation for Object types. *

* Created: Sun Nov 4 08:56:06 2001 * * @author Eric D. Friedman * @author Rob Eden * @author Jeff Randall * @version $Id: TObjectHash.java,v 1.1.2.6 2009/11/07 03:36:44 robeden Exp $ */ abstract public class TObjectHash extends THash { @SuppressWarnings({"UnusedDeclaration"}) static final long serialVersionUID = -3461112548087185871L; /** * the set of Objects */ public transient Object[] _set; public static final Object REMOVED = new Object(), FREE = new Object(); /** * Indicates whether the last insertKey() call used a FREE slot. This field * should be inspected right after call insertKey() */ protected boolean consumeFreeSlot; /** * Creates a new TObjectHash instance with the * default capacity and load factor. */ public TObjectHash() { super(); } /** * Creates a new TObjectHash instance whose capacity * is the next highest prime above initialCapacity + 1 * unless that value is already prime. * * @param initialCapacity an int value */ public TObjectHash(int initialCapacity) { super(initialCapacity); } /** * Creates a new TObjectHash instance with a prime * value at or near the specified capacity and load factor. * * @param initialCapacity used to find a prime capacity for the table. * @param loadFactor used to calculate the threshold over which * rehashing takes place. */ public TObjectHash(int initialCapacity, float loadFactor) { super(initialCapacity, loadFactor); } public int capacity() { return _set.length; } protected void removeAt(int index) { _set[index] = REMOVED; super.removeAt(index); } /** * initializes the Object set of this hash table. * * @param initialCapacity an int value * @return an int value */ public int setUp(int initialCapacity) { int capacity; capacity = super.setUp(initialCapacity); _set = new Object[capacity]; Arrays.fill(_set, FREE); return capacity; } /** * Executes procedure for each element in the set. * * @param procedure a TObjectProcedure value * @return false if the loop over the set terminated because * the procedure returned false for some value. */ @SuppressWarnings({"unchecked"}) public boolean forEach(TObjectProcedure procedure) { Object[] set = _set; for (int i = set.length; i-- > 0;) { if (set[i] != FREE && set[i] != REMOVED && !procedure.execute((T) set[i])) { return false; } } return true; } /** * Searches the set for obj * * @param obj an Object value * @return a boolean value */ @SuppressWarnings({"unchecked"}) public boolean contains(Object obj) { return index(obj) >= 0; } /** * Locates the index of obj. * * @param obj an Object value * @return the index of obj or -1 if it isn't in the set. */ protected int index(Object obj) { if (obj == null) return indexForNull(); // From here on we know obj to be non-null final int hash = hash(obj) & 0x7fffffff; int index = hash % _set.length; Object cur = _set[index]; if (cur == FREE) { return -1; } if (cur == obj || equals(obj, cur)) { return index; } return indexRehashed(obj, index, hash, cur); } /** * Locates the index of non-null obj. * * @param obj target key, know to be non-null * @param index we start from * @param hash * @param cur * @return */ private int indexRehashed(Object obj, int index, int hash, Object cur) { final Object[] set = _set; final int length = set.length; // NOTE: here it has to be REMOVED or FULL (some user-given value) // see Knuth, p. 529 int probe = 1 + (hash % (length - 2)); final int loopIndex = index; do { index -= probe; if (index < 0) { index += length; } cur = set[index]; // if (cur == FREE) return -1; // if ((cur == obj || equals(obj, cur))) return index; } while (index != loopIndex); return -1; } /** * Locates the index null. *

* null specific loop exploiting several properties to simplify the iteration logic * - the null value hashes to 0 we so we can iterate from the beginning. * - the probe value is 1 for this case * - object identity can be used to match this case *

* --> this result a simpler loop * * @return */ private int indexForNull() { int index = 0; for (Object o : _set) { if (o == null) return index; if (o == FREE) return -1; index++; } return -1; } /** * Alias introduced to avoid breaking the API. The new method name insertKey() reflects the * changes made to the logic. * * @param obj * @return * @deprecated use {@link #insertKey} instead */ @Deprecated protected int insertionIndex(T obj) { return insertKey(obj); } /** * Locates the index at which key can be inserted. if * there is already a value equal()ing key in the set, * returns that value's index as -index - 1. *

* If a slot is found the value is inserted. When a FREE slot is used the consumeFreeSlot field is * set to true. This field should be used in the method invoking insertKey() to pass to postInsertHook() * * @param key an Object value * @return the index of a FREE slot at which key can be inserted * or, if key is already stored in the hash, the negative value of * that index, minus 1: -index -1. */ protected int insertKey(T key) { consumeFreeSlot = false; if (key == null) return insertKeyForNull(); final int hash = hash(key) & 0x7fffffff; int index = hash % _set.length; Object cur = _set[index]; if (cur == FREE) { consumeFreeSlot = true; _set[index] = key; // insert value return index; // empty, all done } if (cur == key || equals(key, cur)) { return -index - 1; // already stored } return insertKeyRehash(key, index, hash, cur); } /** * Looks for a slot using double hashing for a non-null key values and inserts the value * in the slot * * @param key non-null key value * @param index natural index * @param hash * @param cur value of first matched slot * @return */ private int insertKeyRehash(T key, int index, int hash, Object cur) { final Object[] set = _set; final int length = set.length; // already FULL or REMOVED, must probe // compute the double hash final int probe = 1 + (hash % (length - 2)); final int loopIndex = index; int firstRemoved = -1; /** * Look until FREE slot or we start to loop */ do { // Identify first removed slot if (cur == REMOVED && firstRemoved == -1) firstRemoved = index; index -= probe; if (index < 0) { index += length; } cur = set[index]; // A FREE slot stops the search if (cur == FREE) { if (firstRemoved != -1) { _set[firstRemoved] = key; return firstRemoved; } else { consumeFreeSlot = true; _set[index] = key; // insert value return index; } } if (cur == key || equals(key, cur)) { return -index - 1; } // Detect loop } while (index != loopIndex); // We inspected all reachable slots and did not find a FREE one // If we found a REMOVED slot we return the first one found if (firstRemoved != -1) { _set[firstRemoved] = key; return firstRemoved; } // Can a resizing strategy be found that resizes the set? throw new IllegalStateException("No free or removed slots available. Key set full?!!"); } /** * Looks for a slot using double hashing for a null key value and inserts the value. *

* null specific loop exploiting several properties to simplify the iteration logic * - the null value hashes to 0 we so we can iterate from the beginning. * - the probe value is 1 for this case * - object identity can be used to match this case * * @return */ private int insertKeyForNull() { int index = 0; int firstRemoved = -1; // Look for a slot containing the 'null' value as key for (Object o : _set) { // Locate first removed if (o == REMOVED && firstRemoved == -1) firstRemoved = index; if (o == FREE) { if (firstRemoved != -1) { _set[firstRemoved] = null; return firstRemoved; } else { consumeFreeSlot = true; _set[index] = null; // insert value return index; } } if (o == null) { return -index - 1; } index++; } // We inspected all reachable slots and did not find a FREE one // If we found a REMOVED slot we return the first one found if (firstRemoved != -1) { _set[firstRemoved] = null; return firstRemoved; } // We scanned the entire key set and found nothing, is set full? // Can a resizing strategy be found that resizes the set? throw new IllegalStateException("Could not find insertion index for null key. Key set full!?!!"); } /** * Convenience methods for subclasses to use in throwing exceptions about * badly behaved user objects employed as keys. We have to throw an * IllegalArgumentException with a rather verbose message telling the * user that they need to fix their object implementation to conform * to the general contract for java.lang.Object. * * * @param o1 the first of the equal elements with unequal hash codes. * @param o2 the second of the equal elements with unequal hash codes. * @throws IllegalArgumentException the whole point of this method. */ protected final void throwObjectContractViolation(Object o1, Object o2) throws IllegalArgumentException { throw buildObjectContractViolation(o1, o2, ""); } /** * Convenience methods for subclasses to use in throwing exceptions about * badly behaved user objects employed as keys. We have to throw an * IllegalArgumentException with a rather verbose message telling the * user that they need to fix their object implementation to conform * to the general contract for java.lang.Object. * * * @param o1 the first of the equal elements with unequal hash codes. * @param o2 the second of the equal elements with unequal hash codes. * @param size *@param oldSize * @param oldKeys @throws IllegalArgumentException the whole point of this method. */ protected final void throwObjectContractViolation(Object o1, Object o2, int size, int oldSize, Object[] oldKeys) throws IllegalArgumentException { String extra = dumpExtraInfo(o1, o2, size(), oldSize, oldKeys); throw buildObjectContractViolation(o1, o2, extra); } /** * Convenience methods for subclasses to use in throwing exceptions about * badly behaved user objects employed as keys. We have to throw an * IllegalArgumentException with a rather verbose message telling the * user that they need to fix their object implementation to conform * to the general contract for java.lang.Object. * * * @param o1 the first of the equal elements with unequal hash codes. * @param o2 the second of the equal elements with unequal hash codes. * @throws IllegalArgumentException the whole point of this method. */ protected final IllegalArgumentException buildObjectContractViolation(Object o1, Object o2, String extra ) { return new IllegalArgumentException("Equal objects must have equal hashcodes. " + "During rehashing, Trove discovered that the following two objects claim " + "to be equal (as in java.lang.Object.equals()) but their hashCodes (or " + "those calculated by your TObjectHashingStrategy) are not equal." + "This violates the general contract of java.lang.Object.hashCode(). See " + "bullet point two in that method's documentation. object #1 =" + objectInfo(o1) + "; object #2 =" + objectInfo(o2) + "\n" + extra); } protected boolean equals(Object notnull, Object two) { if (two == null || two == REMOVED) return false; return notnull.equals(two); } protected int hash(Object notnull) { return notnull.hashCode(); } protected static String reportPotentialConcurrentMod(int newSize, int oldSize) { // Note that we would not be able to detect concurrent paired of put()-remove() // operations with this simple check if (newSize != oldSize) return "[Warning] apparent concurrent modification of the key set. " + "Size before and after rehash() do not match " + oldSize + " vs " + newSize; return ""; } /** * * @param newVal the key being inserted * @param oldVal the key already stored at that position * @param currentSize size of the key set during rehashing * @param oldSize size of the key set before rehashing * @param oldKeys the old key set */ protected String dumpExtraInfo(Object newVal, Object oldVal, int currentSize, int oldSize, Object[] oldKeys) { StringBuilder b = new StringBuilder(); // b.append(dumpKeyTypes(newVal, oldVal)); b.append(reportPotentialConcurrentMod(currentSize, oldSize)); b.append(detectKeyLoss(oldKeys, oldSize)); // Is de same object already present? Double insert? if (newVal == oldVal) { b.append("Inserting same object twice, rehashing bug. Object= ").append(oldVal); } return b.toString(); } /** * Detect inconsistent hashCode() and/or equals() methods * * @param keys * @param oldSize * @return */ private static String detectKeyLoss(Object[] keys, int oldSize) { StringBuilder buf = new StringBuilder(); Set k = makeKeySet(keys); if (k.size() != oldSize) { buf.append("\nhashCode() and/or equals() have inconsistent implementation"); buf.append("\nKey set lost entries, now got ").append(k.size()).append(" instead of ").append(oldSize); buf.append(". This can manifest itself as an apparent duplicate key."); } return buf.toString(); } private static Set makeKeySet(Object[] keys) { Set types = new HashSet(); for (Object o : keys) { if (o != FREE && o != REMOVED) { types.add(o); } } return types; } private static String equalsSymmetryInfo(Object a, Object b) { StringBuilder buf = new StringBuilder(); if (a == b) { return "a == b"; } if (a.getClass() != b.getClass()) { buf.append("Class of objects differ a=").append(a.getClass()).append(" vs b=").append(b.getClass()); boolean aEb = a.equals(b); boolean bEa = b.equals(a); if (aEb != bEa) { buf.append("\nequals() of a or b object are asymmetric"); buf.append("\na.equals(b) =").append(aEb); buf.append("\nb.equals(a) =").append(bEa); } } return buf.toString(); } protected static String objectInfo(Object o) { return (o == null ? "class null" : o.getClass()) + " id= " + System.identityHashCode(o) + " hashCode= " + (o == null ? 0 : o.hashCode()) + " toString= " + String.valueOf(o); } private String dumpKeyTypes(Object newVal, Object oldVal) { StringBuilder buf = new StringBuilder(); Set> types = new HashSet>(); for (Object o : _set) { if (o != FREE && o != REMOVED) { if (o != null) types.add(o.getClass()); else types.add(null); } } if (types.size() > 1) { buf.append("\nMore than one type used for keys. Watch out for asymmetric equals(). " + "Read about the 'Liskov substitution principle' and the implications for equals() in java."); buf.append("\nKey types: ").append(types); buf.append(equalsSymmetryInfo(newVal, oldVal)); } return buf.toString(); } @Override public void writeExternal(ObjectOutput out) throws IOException { // VERSION out.writeByte(0); // SUPER super.writeExternal(out); } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { // VERSION in.readByte(); // SUPER super.readExternal(in); } } // TObjectHash trove-3.0.3/src/gnu/trove/impl/hash/THashPrimitiveIterator.java0000644000175000017500000001077411763017634023523 0ustar ericherich// //////////////////////////////////////////////////////////////////////////// // Copyright (c) 2009, Rob Eden All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // //////////////////////////////////////////////////////////////////////////// package gnu.trove.impl.hash; import gnu.trove.iterator.TPrimitiveIterator; import java.util.ConcurrentModificationException; import java.util.NoSuchElementException; /** * Implements all iterator functions for the hashed object set. * Subclasses may override objectAtIndex to vary the object * returned by calls to next() (e.g. for values, and Map.Entry * objects). *

*

Note that iteration is fastest if you forego the calls to * hasNext in favor of checking the size of the structure * yourself and then call next() that many times: *

*

 * Iterator i = collection.iterator();
 * for (int size = collection.size(); size-- > 0;) {
 *   Object o = i.next();
 * }
 * 
*

*

You may, of course, use the hasNext(), next() idiom too if * you aren't in a performance critical spot.

*/ public abstract class THashPrimitiveIterator implements TPrimitiveIterator { /** the data structure this iterator traverses */ protected final TPrimitiveHash _hash; /** * the number of elements this iterator believes are in the * data structure it accesses. */ protected int _expectedSize; /** the index used for iteration. */ protected int _index; /** * Creates a TPrimitiveIterator for the specified collection. * * @param hash the TPrimitiveHash we want to iterate over. */ public THashPrimitiveIterator( TPrimitiveHash hash ) { _hash = hash; _expectedSize = _hash.size(); _index = _hash.capacity(); } /** * Returns the index of the next value in the data structure * or a negative value if the iterator is exhausted. * * @return an int value * @throws java.util.ConcurrentModificationException * if the underlying collection's * size has been modified since the iterator was created. */ protected final int nextIndex() { if ( _expectedSize != _hash.size() ) { throw new ConcurrentModificationException(); } byte[] states = _hash._states; int i = _index; while ( i-- > 0 && ( states[i] != TPrimitiveHash.FULL ) ) { ; } return i; } /** * Returns true if the iterator can be advanced past its current * location. * * @return a boolean value */ public boolean hasNext() { return nextIndex() >= 0; } /** * Removes the last entry returned by the iterator. * Invoking this method more than once for a single entry * will leave the underlying data structure in a confused * state. */ public void remove() { if (_expectedSize != _hash.size()) { throw new ConcurrentModificationException(); } // Disable auto compaction during the remove. This is a workaround for bug 1642768. try { _hash.tempDisableAutoCompaction(); _hash.removeAt(_index); } finally { _hash.reenableAutoCompaction( false ); } _expectedSize--; } /** * Sets the internal index so that the `next' object * can be returned. */ protected final void moveToNextIndex() { // doing the assignment && < 0 in one line shaves // 3 opcodes... if ( ( _index = nextIndex() ) < 0 ) { throw new NoSuchElementException(); } } } // TPrimitiveIteratortrove-3.0.3/src/gnu/trove/impl/PrimeFinder.java0000644000175000017500000001427011763017634020365 0ustar ericherich// 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 gnu.trove.impl; import java.util.Arrays; /* * Modified for Trove to use the java.util.Arrays sort/search * algorithms instead of those provided with colt. */ /** * Used to keep hash table capacities prime numbers. * Not of interest for users; only for implementors of hashtables. * *

Choosing prime numbers as hash table capacities is a good idea * to keep them working fast, particularly under hash table * expansions. * *

However, JDK 1.2, JGL 3.1 and many other toolkits do nothing to * keep capacities prime. This class provides efficient means to * choose prime capacities. * *

Choosing a prime is O(log 300) (binary search in a list * of 300 ints). Memory requirements: 1 KB static memory. * * @author wolfgang.hoschek@cern.ch * @version 1.0, 09/24/99 */ public final class PrimeFinder { /** * The largest prime this class can generate; currently equal to * Integer.MAX_VALUE. */ public static final int largestPrime = Integer.MAX_VALUE; //yes, it is prime. /** * The prime number list consists of 11 chunks. * * Each chunk contains prime numbers. * * A chunk starts with a prime P1. The next element is a prime * P2. P2 is the smallest prime for which holds: P2 >= 2*P1. * * The next element is P3, for which the same holds with respect * to P2, and so on. * * Chunks are chosen such that for any desired capacity >= 1000 * the list includes a prime number <= desired capacity * 1.11. * * Therefore, primes can be retrieved which are quite close to any * desired capacity, which in turn avoids wasting memory. * * For example, the list includes * 1039,1117,1201,1277,1361,1439,1523,1597,1759,1907,2081. * * So if you need a prime >= 1040, you will find a prime <= * 1040*1.11=1154. * * Chunks are chosen such that they are optimized for a hashtable * growthfactor of 2.0; * * If your hashtable has such a growthfactor then, after initially * "rounding to a prime" upon hashtable construction, it will * later expand to prime capacities such that there exist no * better primes. * * In total these are about 32*10=320 numbers -> 1 KB of static * memory needed. * * If you are stingy, then delete every second or fourth chunk. */ private static final int[] primeCapacities = { //chunk #0 largestPrime, //chunk #1 5,11,23,47,97,197,397,797,1597,3203,6421,12853,25717,51437,102877,205759, 411527,823117,1646237,3292489,6584983,13169977,26339969,52679969,105359939, 210719881,421439783,842879579,1685759167, //chunk #2 433,877,1759,3527,7057,14143,28289,56591,113189,226379,452759,905551,1811107, 3622219,7244441,14488931,28977863,57955739,115911563,231823147,463646329,927292699, 1854585413, //chunk #3 953,1907,3821,7643,15287,30577,61169,122347,244703,489407,978821,1957651,3915341, 7830701,15661423,31322867,62645741,125291483,250582987,501165979,1002331963, 2004663929, //chunk #4 1039,2081,4177,8363,16729,33461,66923,133853,267713,535481,1070981,2141977,4283963, 8567929,17135863,34271747,68543509,137087021,274174111,548348231,1096696463, //chunk #5 31,67,137,277,557,1117,2237,4481,8963,17929,35863,71741,143483,286973,573953, 1147921,2295859,4591721,9183457,18366923,36733847,73467739,146935499,293871013, 587742049,1175484103, //chunk #6 599,1201,2411,4831,9677,19373,38747,77509,155027,310081,620171,1240361,2480729, 4961459,9922933,19845871,39691759,79383533,158767069,317534141,635068283,1270136683, //chunk #7 311,631,1277,2557,5119,10243,20507,41017,82037,164089,328213,656429,1312867, 2625761,5251529,10503061,21006137,42012281,84024581,168049163,336098327,672196673, 1344393353, //chunk #8 3,7,17,37,79,163,331,673,1361,2729,5471,10949,21911,43853,87719,175447,350899, 701819,1403641,2807303,5614657,11229331,22458671,44917381,89834777,179669557, 359339171,718678369,1437356741, //chunk #9 43,89,179,359,719,1439,2879,5779,11579,23159,46327,92657,185323,370661,741337, 1482707,2965421,5930887,11861791,23723597,47447201,94894427,189788857,379577741, 759155483,1518310967, //chunk #10 379,761,1523,3049,6101,12203,24407,48817,97649,195311,390647,781301,1562611, 3125257,6250537,12501169,25002389,50004791,100009607,200019221,400038451,800076929, 1600153859 }; static { //initializer // The above prime numbers are formatted for human readability. // To find numbers fast, we sort them once and for all. Arrays.sort(primeCapacities); } /** * Returns a prime number which is >= desiredCapacity * and very close to desiredCapacity (within 11% if * desiredCapacity >= 1000). * * @param desiredCapacity the capacity desired by the user. * @return the capacity which should be used for a hashtable. */ public static final int nextPrime(int desiredCapacity) { int i = Arrays.binarySearch(primeCapacities, desiredCapacity); if (i<0) { // desired capacity not found, choose next prime greater // than desired capacity i = -i -1; // remember the semantics of binarySearch... } return primeCapacities[i]; } } trove-3.0.3/src/gnu/trove/impl/package.html0000644000175000017500000000234511763017634017577 0ustar ericherich This package (and its sub-packages) contain internal implementations used in Trove. These classes should not be accessed directly (treat them like com.sun classes. trove-3.0.3/src/gnu/trove/impl/HashFunctions.java0000644000175000017500000000533511763017634020737 0ustar ericherich// 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 gnu.trove.impl; /** * Provides various hash functions. * * @author wolfgang.hoschek@cern.ch * @version 1.0, 09/24/99 */ public final class HashFunctions { /** * Returns a hashcode for the specified value. * * @return a hash code value for the specified value. */ public static int hash(double value) { assert !Double.isNaN(value) : "Values of NaN are not supported."; long bits = Double.doubleToLongBits(value); return (int)(bits ^ (bits >>> 32)); //return (int) Double.doubleToLongBits(value*663608941.737); //this avoids excessive hashCollisions in the case values are //of the form (1.0, 2.0, 3.0, ...) } /** * Returns a hashcode for the specified value. * * @return a hash code value for the specified value. */ public static int hash(float value) { assert !Float.isNaN(value) : "Values of NaN are not supported."; return Float.floatToIntBits(value*663608941.737f); // this avoids excessive hashCollisions in the case values are // of the form (1.0, 2.0, 3.0, ...) } /** * Returns a hashcode for the specified value. * * @return a hash code value for the specified value. */ public static int hash(int value) { return value; } /** * Returns a hashcode for the specified value. * * @return a hash code value for the specified value. */ public static int hash(long value) { return ((int)(value ^ (value >>> 32))); } /** * Returns a hashcode for the specified object. * * @return a hash code value for the specified object. */ public static int hash(Object object) { return object==null ? 0 : object.hashCode(); } /** * In profiling, it has been found to be faster to have our own local implementation * of "ceil" rather than to call to {@link Math#ceil(double)}. */ public static int fastCeil( float v ) { int possible_result = ( int ) v; if ( v - possible_result > 0 ) possible_result++; return possible_result; } } trove-3.0.3/src/gnu/trove/impl/Constants.java0000644000175000017500000001671711763017634020145 0ustar ericherich// //////////////////////////////////////////////////////////////////////////// // Copyright (c) 2009, Rob Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // //////////////////////////////////////////////////////////////////////////// package gnu.trove.impl; /** * Central location for constants needed by various implementations. */ public class Constants { private static final boolean VERBOSE = System.getProperty( "gnu.trove.verbose", null ) != null; /** the default capacity for new collections */ public static final int DEFAULT_CAPACITY = 10; /** the load above which rehashing occurs. */ public static final float DEFAULT_LOAD_FACTOR = 0.5f; /** the default value that represents for byte types. */ public static final byte DEFAULT_BYTE_NO_ENTRY_VALUE; static { byte value; String property = System.getProperty( "gnu.trove.no_entry.byte", "0" ); if ( "MAX_VALUE".equalsIgnoreCase( property ) ) value = Byte.MAX_VALUE; else if ( "MIN_VALUE".equalsIgnoreCase( property ) ) value = Byte.MIN_VALUE; else value = Byte.valueOf( property ); if ( value > Byte.MAX_VALUE ) value = Byte.MAX_VALUE; else if ( value < Byte.MIN_VALUE ) value = Byte.MIN_VALUE; DEFAULT_BYTE_NO_ENTRY_VALUE = value; if ( VERBOSE ) { System.out.println( "DEFAULT_BYTE_NO_ENTRY_VALUE: " + DEFAULT_BYTE_NO_ENTRY_VALUE ); } } /** the default value that represents for short types. */ public static final short DEFAULT_SHORT_NO_ENTRY_VALUE; static { short value; String property = System.getProperty( "gnu.trove.no_entry.short", "0" ); if ( "MAX_VALUE".equalsIgnoreCase( property ) ) value = Short.MAX_VALUE; else if ( "MIN_VALUE".equalsIgnoreCase( property ) ) value = Short.MIN_VALUE; else value = Short.valueOf( property ); if ( value > Short.MAX_VALUE ) value = Short.MAX_VALUE; else if ( value < Short.MIN_VALUE ) value = Short.MIN_VALUE; DEFAULT_SHORT_NO_ENTRY_VALUE = value; if ( VERBOSE ) { System.out.println( "DEFAULT_SHORT_NO_ENTRY_VALUE: " + DEFAULT_SHORT_NO_ENTRY_VALUE ); } } /** the default value that represents for char types. */ public static final char DEFAULT_CHAR_NO_ENTRY_VALUE; static { char value; String property = System.getProperty( "gnu.trove.no_entry.char", "\0" ); if ( "MAX_VALUE".equalsIgnoreCase( property ) ) value = Character.MAX_VALUE; else if ( "MIN_VALUE".equalsIgnoreCase( property ) ) value = Character.MIN_VALUE; else value = property.toCharArray()[0]; if ( value > Character.MAX_VALUE ) value = Character.MAX_VALUE; else if ( value < Character.MIN_VALUE ) value = Character.MIN_VALUE; DEFAULT_CHAR_NO_ENTRY_VALUE = value; if ( VERBOSE ) { System.out.println( "DEFAULT_CHAR_NO_ENTRY_VALUE: " + Integer.valueOf( value ) ); } } /** the default value that represents for int types. */ public static final int DEFAULT_INT_NO_ENTRY_VALUE; static { int value; String property = System.getProperty( "gnu.trove.no_entry.int", "0" ); if ( "MAX_VALUE".equalsIgnoreCase( property ) ) value = Integer.MAX_VALUE; else if ( "MIN_VALUE".equalsIgnoreCase( property ) ) value = Integer.MIN_VALUE; else value = Integer.valueOf( property ); DEFAULT_INT_NO_ENTRY_VALUE = value; if ( VERBOSE ) { System.out.println( "DEFAULT_INT_NO_ENTRY_VALUE: " + DEFAULT_INT_NO_ENTRY_VALUE ); } } /** the default value that represents for long types. */ public static final long DEFAULT_LONG_NO_ENTRY_VALUE; static { long value; String property = System.getProperty( "gnu.trove.no_entry.long", "0" ); if ( "MAX_VALUE".equalsIgnoreCase( property ) ) value = Long.MAX_VALUE; else if ( "MIN_VALUE".equalsIgnoreCase( property ) ) value = Long.MIN_VALUE; else value = Long.valueOf( property ); DEFAULT_LONG_NO_ENTRY_VALUE = value; if ( VERBOSE ) { System.out.println( "DEFAULT_LONG_NO_ENTRY_VALUE: " + DEFAULT_LONG_NO_ENTRY_VALUE ); } } /** the default value that represents for float types. */ public static final float DEFAULT_FLOAT_NO_ENTRY_VALUE; static { float value; String property = System.getProperty( "gnu.trove.no_entry.float", "0" ); if ( "MAX_VALUE".equalsIgnoreCase( property ) ) value = Float.MAX_VALUE; else if ( "MIN_VALUE".equalsIgnoreCase( property ) ) value = Float.MIN_VALUE; // Value from Float.MIN_NORMAL (introduced in 1.6) else if ( "MIN_NORMAL".equalsIgnoreCase( property ) ) value = 0x1.0p-126f; else if ( "NEGATIVE_INFINITY".equalsIgnoreCase( property ) ) value = Float.NEGATIVE_INFINITY; else if ( "POSITIVE_INFINITY".equalsIgnoreCase( property ) ) value = Float.POSITIVE_INFINITY; // else if ( "NaN".equalsIgnoreCase( property ) ) value = Float.NaN; else value = Float.valueOf( property ); DEFAULT_FLOAT_NO_ENTRY_VALUE = value; if ( VERBOSE ) { System.out.println( "DEFAULT_FLOAT_NO_ENTRY_VALUE: " + DEFAULT_FLOAT_NO_ENTRY_VALUE ); } } /** the default value that represents for double types. */ public static final double DEFAULT_DOUBLE_NO_ENTRY_VALUE; static { double value; String property = System.getProperty( "gnu.trove.no_entry.double", "0" ); if ( "MAX_VALUE".equalsIgnoreCase( property ) ) value = Double.MAX_VALUE; else if ( "MIN_VALUE".equalsIgnoreCase( property ) ) value = Double.MIN_VALUE; // Value from Double.MIN_NORMAL (introduced in 1.6) else if ( "MIN_NORMAL".equalsIgnoreCase( property ) ) value = 0x1.0p-1022; else if ( "NEGATIVE_INFINITY".equalsIgnoreCase( property ) ) value = Double.NEGATIVE_INFINITY; else if ( "POSITIVE_INFINITY".equalsIgnoreCase( property ) ) value = Double.POSITIVE_INFINITY; // else if ( "NaN".equalsIgnoreCase( property ) ) value = Double.NaN; else value = Double.valueOf( property ); DEFAULT_DOUBLE_NO_ENTRY_VALUE = value; if ( VERBOSE ) { System.out.println( "DEFAULT_DOUBLE_NO_ENTRY_VALUE: " + DEFAULT_DOUBLE_NO_ENTRY_VALUE ); } } } trove-3.0.3/lib/0000755000175000017500000000000012000515263012362 5ustar ericherichtrove-3.0.3/generator_src/0000755000175000017500000000000011763017634014467 5ustar ericherichtrove-3.0.3/generator_src/gnu/0000755000175000017500000000000011763017634015260 5ustar ericherichtrove-3.0.3/generator_src/gnu/trove/0000755000175000017500000000000011763017634016417 5ustar ericherichtrove-3.0.3/generator_src/gnu/trove/generator/0000755000175000017500000000000012000515241020363 5ustar ericherichtrove-3.0.3/generator_src/gnu/trove/generator/Generator.java0000644000175000017500000006045711763017634023212 0ustar ericherich/* * /////////////////////////////////////////////////////////////////////////////// * // Copyright (c) 2009, Rob Eden All Rights Reserved. * // Copyright (c) 2009, Jeff Randall All Rights Reserved. * // * // This library is free software; you can redistribute it and/or * // modify it under the terms of the GNU Lesser General Public * // License as published by the Free Software Foundation; either * // version 2.1 of the License, or (at your option) any later version. * // * // This library is distributed in the hope that it will be useful, * // but WITHOUT ANY WARRANTY; without even the implied warranty of * // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * // GNU General Public License for more details. * // * // You should have received a copy of the GNU Lesser General Public * // License along with this program; if not, write to the Free Software * // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * /////////////////////////////////////////////////////////////////////////////// */ package gnu.trove.generator; import java.io.*; import java.io.BufferedInputStream; import java.io.BufferedWriter; import java.nio.channels.FileChannel; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.regex.Pattern; /** *

Generator class that builds final source files from templates. It does so by * replacing patterns in the template files.

* *

Patterns

* *

In map-like classes, the letters "k" and "v" are used to indicate "key" and "value". * In classes with a single element type, "e" is used. The patterns start and end with a * hash sign and come in these variants: *

    *
  • lowercase (eg: "#e#")- the primitive type (eg: "int" or "float")
  • *
  • T (eg: "#ET#")- the class type (eg: "Integer" or "Float")
  • *
  • uppercase (eg: "#E#")- the abbreviated class type (eg: "Int" or "Float")
  • *
  • C (eg: "#EC#") - uppercase primitive (eg: "INT" or "FLOAT")
  • *
  • MAX (eg: "#EMAX#") - max value for the type (eg: "Integer.MAX_VALUE" or * Float.POSITIVE_INFINITY")
  • *
  • MIN (eg: "#EMIN#") - min value for the type (eg: "Integer.MIN_VALUE" or * Float.NEGATIVE_INFINITY")
  • *
  • underbar (eg: "_E_") - Only applicable in file names, same as "uppercase".
  • *
*

* *

Block Replication

* *

In addition to regular patterns, some classes use block replication. This allows * replicating a block of code for each type. A block starts with * ====START_REPLICATED_CONTENT #<number>==== and ends with * =====END_REPLICATED_CONTENT #<number>===== (each on a new line) where * "<number>" is an integer. Then, that content is replicated for each type where * the pattern "#REPLICATED#" is found.

* */ public class Generator { private static final WrapperInfo[] WRAPPERS = new WrapperInfo[]{ new WrapperInfo("double", "Double", "POSITIVE_INFINITY", "NEGATIVE_INFINITY"), new WrapperInfo("float", "Float", "POSITIVE_INFINITY", "NEGATIVE_INFINITY"), new WrapperInfo("int", "Integer", "MAX_VALUE", "MIN_VALUE"), new WrapperInfo("long", "Long", "MAX_VALUE", "MIN_VALUE"), new WrapperInfo("byte", "Byte", "MAX_VALUE", "MIN_VALUE"), new WrapperInfo("short", "Short", "MAX_VALUE", "MIN_VALUE"), new WrapperInfo("char", "Character", "MAX_VALUE", "MIN_VALUE")}; private static final Pattern PATTERN_v; private static final Pattern PATTERN_V; private static final Pattern PATTERN_VC; private static final Pattern PATTERN_VT; private static final Pattern PATTERN_VMAX; private static final Pattern PATTERN_VMIN; private static final Pattern PATTERN_V_UNDERBAR; private static final Pattern PATTERN_k; private static final Pattern PATTERN_K; private static final Pattern PATTERN_KC; private static final Pattern PATTERN_KT; private static final Pattern PATTERN_KMAX; private static final Pattern PATTERN_KMIN; private static final Pattern PATTERN_K_UNDERBAR; private static final Pattern PATTERN_e; private static final Pattern PATTERN_E; private static final Pattern PATTERN_EC; private static final Pattern PATTERN_ET; private static final Pattern PATTERN_EMAX; private static final Pattern PATTERN_EMIN; private static final Pattern PATTERN_E_UNDERBAR; static { PATTERN_v = Pattern.compile("#v#"); PATTERN_V = Pattern.compile("#V#"); PATTERN_VC = Pattern.compile("#VC#"); PATTERN_VT = Pattern.compile("#VT#"); PATTERN_VMAX = Pattern.compile("#VMAX#"); PATTERN_VMIN = Pattern.compile("#VMIN#"); PATTERN_V_UNDERBAR = Pattern.compile("_V_"); PATTERN_k = Pattern.compile("#k#"); PATTERN_K = Pattern.compile("#K#"); PATTERN_KC = Pattern.compile("#KC#"); PATTERN_KT = Pattern.compile("#KT#"); PATTERN_KMAX = Pattern.compile("#KMAX#"); PATTERN_KMIN = Pattern.compile("#KMIN#"); PATTERN_K_UNDERBAR = Pattern.compile("_K_"); PATTERN_e = Pattern.compile("#e#"); PATTERN_E = Pattern.compile("#E#"); PATTERN_EC = Pattern.compile("#EC#"); PATTERN_ET = Pattern.compile("#ET#"); PATTERN_EMAX = Pattern.compile("#EMAX#"); PATTERN_EMIN = Pattern.compile("#EMIN#"); PATTERN_E_UNDERBAR = Pattern.compile("_E_"); } private static File root_output_dir; public static void main(String[] args) throws Exception { if (args.length == 0) { System.out.println("Usage: Generator [-c] "); return; } int arg_index = 0; boolean clean_output = false; if (args[0].equalsIgnoreCase("-c")) { clean_output = true; arg_index++; } File input_directory = new File(args[arg_index++]); File output_directory = new File(args[arg_index++]); if (!input_directory.exists()) { System.err.println("Directory \"" + input_directory + "\" not found."); System.exit(-1); return; } if (!output_directory.exists()) { makeDirs(output_directory); } root_output_dir = output_directory; if (clean_output) { System.out.println("Removing contents of \"" + output_directory + "\"..."); cleanDir(output_directory); } scanForFiles(input_directory, output_directory); } /** * Creates dirs, throw IllegalArgumentException or IllegalStateException if * argument is invalid or creation fails * * @param directory */ private static void makeDirs(File directory) { if (directory.exists() && !directory.isDirectory()) throw new IllegalArgumentException(directory + " not a directory"); if (directory.exists()) return; if (!directory.mkdirs()) throw new IllegalStateException("Could not create directories " + directory); } private static void scanForFiles(File input_directory, File output_directory) throws IOException { File[] files = input_directory.listFiles(); for (File file : files) { // Ignore hidden files if (file.isHidden()) continue; if (file.isDirectory()) { // Ignore CVS directories if (file.getName().equals("CVS")) continue; scanForFiles(file, new File(output_directory, file.getName())); continue; } processFile(file, output_directory); } } private static void processFile(File input_file, File output_directory) throws IOException { System.out.println("Process file: " + input_file); String content = readFile(input_file); String file_name = input_file.getName(); file_name = file_name.replaceAll("\\.template", ".java"); File output_file = new File(output_directory, file_name); // See what kind of template markers it's using, either e or k/v. No marker // indicates a replication-only class. if (file_name.contains("_K_")) { processKVMarkers(content, output_directory, file_name); } else if (file_name.contains("_E_")) { processEMarkers(content, output_directory, file_name); } else { if (input_file.lastModified() < output_file.lastModified()) { System.out.println("File " + output_file + " up to date, not processing input"); return; } // Replication only StringBuilder processed_replication_output = new StringBuilder(); Map replicated_blocks = findReplicatedBlocks(content, processed_replication_output); if (replicated_blocks != null) { content = processReplication(processed_replication_output.toString(), replicated_blocks); } writeFile(content, output_file); } } private static void processKVMarkers(String content, File output_dir, String file_name) throws IOException { for (WrapperInfo info : WRAPPERS) { String k = info.primitive; String KT = info.class_name; String K = abbreviate(KT); String KC = K.toUpperCase(); String KMAX = info.max_value; String KMIN = info.min_value; String out = content; out = PATTERN_k.matcher(out).replaceAll(k); out = PATTERN_K.matcher(out).replaceAll(K); out = PATTERN_KC.matcher(out).replaceAll(KC); out = PATTERN_KT.matcher(out).replaceAll(KT); out = PATTERN_KMAX.matcher(out).replaceAll(KMAX); out = PATTERN_KMIN.matcher(out).replaceAll(KMIN); String out_file_name = "T" + file_name; out_file_name = PATTERN_K_UNDERBAR.matcher(out_file_name).replaceAll(K); for (WrapperInfo jinfo : WRAPPERS) { String v = jinfo.primitive; String VT = jinfo.class_name; String V = abbreviate(VT); String VC = V.toUpperCase(); String VMAX = jinfo.max_value; String VMIN = jinfo.min_value; String vout = out; vout = PATTERN_v.matcher(vout).replaceAll(v); vout = PATTERN_V.matcher(vout).replaceAll(V); vout = PATTERN_VC.matcher(vout).replaceAll(VC); vout = PATTERN_VT.matcher(vout).replaceAll(VT); vout = PATTERN_VMAX.matcher(vout).replaceAll(VMAX); String processed_output = PATTERN_VMIN.matcher(vout).replaceAll(VMIN); StringBuilder processed_replication_output = new StringBuilder(); Map replicated_blocks = findReplicatedBlocks(processed_output, processed_replication_output); if (replicated_blocks != null) { processed_output = processReplication( processed_replication_output.toString(), replicated_blocks); } String processed_filename = PATTERN_V_UNDERBAR.matcher(out_file_name).replaceAll(V); writeFile(processed_output, new File(output_dir, processed_filename)); } } } private static void processEMarkers(String content, File output_dir, String file_name) throws IOException { for (WrapperInfo info : WRAPPERS) { String e = info.primitive; String ET = info.class_name; String E = abbreviate(ET); String EC = E.toUpperCase(); String EMAX = info.max_value; String EMIN = info.min_value; String out = content; out = PATTERN_e.matcher(out).replaceAll(e); out = PATTERN_E.matcher(out).replaceAll(E); out = PATTERN_EC.matcher(out).replaceAll(EC); out = PATTERN_ET.matcher(out).replaceAll(ET); out = PATTERN_EMAX.matcher(out).replaceAll(EMAX); String processed_output = PATTERN_EMIN.matcher(out).replaceAll(EMIN); String out_file_name = "T" + file_name; out_file_name = PATTERN_E_UNDERBAR.matcher(out_file_name).replaceAll(E); StringBuilder processed_replication_output = new StringBuilder(); Map replicated_blocks = findReplicatedBlocks(processed_output, processed_replication_output); if (replicated_blocks != null) { processed_output = processReplication( processed_replication_output.toString(), replicated_blocks); } writeFile(processed_output, new File(output_dir, out_file_name)); } } static String processReplication(String content, Map replicated_blocks) { for (Map.Entry entry : replicated_blocks.entrySet()) { // Replace the markers in the replicated content StringBuilder entry_buffer = new StringBuilder(); boolean first_loop = true; for (int i = 0; i < WRAPPERS.length; i++) { WrapperInfo info = WRAPPERS[i]; String k = info.primitive; String KT = info.class_name; String K = abbreviate(KT); String KC = K.toUpperCase(); String KMAX = info.max_value; String KMIN = info.min_value; for (int j = 0; j < WRAPPERS.length; j++) { WrapperInfo jinfo = WRAPPERS[j]; String v = jinfo.primitive; String VT = jinfo.class_name; String V = abbreviate(VT); String VC = V.toUpperCase(); String VMAX = jinfo.max_value; String VMIN = jinfo.min_value; String out = entry.getValue(); String before_e = out; out = Pattern.compile("#e#").matcher(out).replaceAll(k); out = Pattern.compile("#E#").matcher(out).replaceAll(K); out = Pattern.compile("#ET#").matcher(out).replaceAll(KT); out = Pattern.compile("#EC#").matcher(out).replaceAll(KC); out = Pattern.compile("#EMAX#").matcher(out).replaceAll(KMAX); out = Pattern.compile("#EMIN#").matcher(out).replaceAll(KMIN); boolean uses_e = !out.equals(before_e); // If we use "e" (instead of "k" & "v", then we don't need the inner // map. Yeah, this is ugly I know... but it works. if (uses_e && j != 0) break; out = Pattern.compile("#v#").matcher(out).replaceAll(v); out = Pattern.compile("#V#").matcher(out).replaceAll(V); out = Pattern.compile("#VT#").matcher(out).replaceAll(VT); out = Pattern.compile("#VC#").matcher(out).replaceAll(VC); out = Pattern.compile("#VMAX#").matcher(out).replaceAll(VMAX); out = Pattern.compile("#VMIN#").matcher(out).replaceAll(VMIN); out = Pattern.compile("#k#").matcher(out).replaceAll(k); out = Pattern.compile("#K#").matcher(out).replaceAll(K); out = Pattern.compile("#KT#").matcher(out).replaceAll(KT); out = Pattern.compile("#KC#").matcher(out).replaceAll(KC); out = Pattern.compile("#KMAX#").matcher(out).replaceAll(KMAX); out = Pattern.compile("#KMIN#").matcher(out).replaceAll(KMIN); if (first_loop) first_loop = false; else { entry_buffer.append("\n\n"); } entry_buffer.append(out); } } content = Pattern.compile("#REPLICATED" + entry.getKey() + "#").matcher( content).replaceAll(entry_buffer.toString()); } return content; } private static void writeFile(String content, File output_file) throws IOException { File parent = output_file.getParentFile(); makeDirs(parent); // Write to a temporary file File temp = File.createTempFile("trove", "gentemp", new File(System.getProperty("java.io.tmpdir"))); Writer writer = new BufferedWriter(new FileWriter(temp)); writer.write(content); writer.close(); // Now determine if it should be moved to the final location final boolean need_to_move; if (output_file.exists()) { boolean matches; try { MessageDigest digest = MessageDigest.getInstance("MD5"); byte[] current_file = digest(output_file, digest); byte[] new_file = digest(temp, digest); matches = Arrays.equals(current_file, new_file); } catch (NoSuchAlgorithmException ex) { System.err.println( "WARNING: Couldn't load digest algorithm to compare " + "new and old template. Generation will be forced."); matches = false; } need_to_move = !matches; } else need_to_move = true; // Now move it if we need to move it if (need_to_move) { delete(output_file); copyFile( temp, output_file ); System.out.println(" Wrote: " + simplifyPath(output_file)); } else { System.out.println(" Skipped: " + simplifyPath(output_file)); delete(temp); } } /** * Delete the given file, throws IllegalStateException if delete operation fails * * @param output_file */ private static void delete(File output_file) { if (!output_file.exists()) return; if (!output_file.delete()) throw new IllegalStateException("Could not delete " + output_file); } private static byte[] digest(File file, MessageDigest digest) throws IOException { digest.reset(); byte[] buffer = new byte[1024]; InputStream in = new BufferedInputStream(new FileInputStream(file)); try { int read = in.read(buffer); while (read >= 0) { digest.update(buffer, 0, read); read = in.read(buffer); } return digest.digest(); } finally { try { in.close(); } catch (IOException ex) { // ignore } } } /** * Abbreviate the type for Integer and Character */ private static String abbreviate(String type) { if (type.equals("Integer")) { return "Int"; } else if (type.equals("Character")) { return "Char"; } return type; } private static String readFile(File input_file) throws IOException { if (!input_file.exists()) { throw new NullPointerException("Couldn't find: " + input_file); } BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(input_file)); StringBuilder out = new StringBuilder(); while (true) { String line = reader.readLine(); if (line == null) break; out.append(line); out.append("\n"); } return out.toString(); } finally { if (reader != null) { try { reader.close(); } catch (IOException ex) { // ignore } } } } /** * Find replicated block definitions at the end of content. * * @param content_in The content * @param content_out A StringBuffer into which the content (without the * definition blocks is placed). This will be untouched * if no definition blocks are found. * @return Null if no definition blocks are found, otherwise a map * containing the blocks, keyed by their number. */ static Map findReplicatedBlocks(String content_in, StringBuilder content_out) throws IOException { Map to_return = null; // Find the replicated content blocks in the template. For ease, read this line // by line. BufferedReader reader = new BufferedReader(new StringReader(content_in)); String line; StringBuilder buffer = new StringBuilder(); boolean in_replicated_block = false; boolean need_newline = false; while ((line = reader.readLine()) != null) { if (!in_replicated_block && line.startsWith("====START_REPLICATED_CONTENT #")) { in_replicated_block = true; need_newline = false; if (content_out.length() == 0) { content_out.append(buffer.toString()); } buffer = new StringBuilder(); } else if (in_replicated_block && line.startsWith("=====END_REPLICATED_CONTENT #")) { int number_start_index = "=====END_REPLICATED_CONTENT #".length(); int number_end_index = line.indexOf("=", number_start_index); String number = line.substring(number_start_index, number_end_index); Integer number_obj = Integer.valueOf(number); if (to_return == null) to_return = new HashMap(); to_return.put(number_obj, buffer.toString()); in_replicated_block = false; need_newline = false; } else { if (need_newline) buffer.append("\n"); else need_newline = true; buffer.append(line); } } return to_return; } private static String simplifyPath(File file) { String output_string = root_output_dir.toString(); String file_string = file.toString(); return file_string.substring(output_string.length() + 1); } private static void cleanDir(File directory) { for (File file : directory.listFiles()) { if (file.isDirectory()) { cleanDir(file); delete(file); } delete(file); } } private static void copyFile( File source, File dest ) throws IOException { FileChannel srcChannel = new FileInputStream( source ).getChannel(); // Create channel on the destination FileChannel dstChannel = new FileOutputStream( dest ).getChannel(); // Copy file contents from source to destination dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); // Close the channels srcChannel.close(); dstChannel.close(); } private static class WrapperInfo { final String primitive; final String class_name; final String max_value; final String min_value; WrapperInfo(String primitive, String class_name, String max_value, String min_value) { this.primitive = primitive; this.class_name = class_name; this.max_value = class_name + "." + max_value; this.min_value = class_name + "." + min_value; } } } trove-3.0.3/README.txt0000644000175000017500000001045111763017636013333 0ustar ericherich GNU Trove: High performance collections for Java. Objectives The GNU Trove library has two objectives: 1. Provide "free" (as in "free speech" and "free beer"), fast, lightweight implementations of the java.util Collections API. These implementations are designed to be pluggable replacements for their JDK equivalents. 2. Whenever possible, provide the same collections support for primitive types. This gap in the JDK is often addressed by using the "wrapper" classes (java.lang.Integer, java.lang.Float, etc.) with Object-based collections. For most applications, however, collections which store primitives directly will require less space and yield significant performance gains. Hashtable techniques The Trove maps/sets use open addressing instead of the chaining approach taken by the JDK hashtables. This eliminates the need to create Map.Entry wrappper objects for every item in a table and so reduces the O (big-oh) in the performance of the hashtable algorithm. The size of the tables used in Trove's maps/sets is always a prime number, improving the probability of an optimal distribution of entries across the table, and so reducing the likelihood of performance-degrading collisions. Trove sets are not backed by maps, and so using a THashSet does not result in the allocation of an unused "values" array. Hashing strategies Trove's maps/sets support the use of custom hashing strategies, allowing you to tune collections based on characteristics of the input data. This feature also allows you to define hash functions when it is not feasible to override Object.hashCode(). For example, the java.lang.String class is final, and its implementation of hashCode() takes O(n) time to complete. In some applications, however, it may be possible for a custom hashing function to save time by skipping portions of the string that are invariant. Using java.util.HashMap, it is not possible to use Java language arrays as keys. For example, this code: char[] foo, bar; foo = new char[] {'a','b','c'}; bar = new char[] {'a','b','c'}; System.out.println(foo.hashCode() == bar.hashCode() ? "equal" : "not equal"); System.out.println(foo.equals(bar) ? "equal" : "not equal"); produces this output: not equal not equal And so an entry stored in a java.util.HashMap with foo as a key could not be retrieved with bar, since there is no way to override hashCode() or equals() on language array objects. In a gnu.trove.map.hash.TCustomHashMap, however, you can implement a gnu.trove.strategy.HashingStrategy to enable hashing on arrays: class CharArrayStrategy implements HashingStrategy { public int computeHashCode(Object o) { char[] c = (char[])o; // use the shift-add-xor class of string hashing functions // cf. Ramakrishna and Zobel, // "Performance in Practice of String Hashing Functions" int h = 31; // seed chosen at random for (int i = 0; i < c.length; i++) { // could skip invariants // L=5, R=2 works well for ASCII input h = h ^ ((h << 5) + (h >> 2) + c[i]); } return h; } public boolean equals(Object o1, Object o2) { char[] c1 = (char[])o1; char[] c2 = (char[])o2; // could drop this check for fixed-length keys if (c1.length != c2.length) { return false; } // could skip invariants for (int i = 0, len = c1.length; i < len; i++) { if (c1[i] != c2[i]) { return false; } } return true; } } Iterators in primitive collections Trove's primitive mappings include access through Iterators as well as procedures and functions. The API documentation on those classes contains several examples showing how these can be used effectively and explaining why their semantics differ from those of java.util.Iterator. _________________________________________________________________ Last modified: Sep 9, 2011 trove-3.0.3/LICENSE.txt0000644000175000017500000006454011763017636013470 0ustar ericherich GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! trove-3.0.3/build.xml0000644000175000017500000004347511763017636013472 0ustar ericherich Builds the Trove4j library ${version} trove-3.0.3/templates/0000755000175000017500000000000011763017634013630 5ustar ericherichtrove-3.0.3/templates/gnu/0000755000175000017500000000000011763017634014421 5ustar ericherichtrove-3.0.3/templates/gnu/trove/0000755000175000017500000000000012000515265015544 5ustar ericherichtrove-3.0.3/templates/gnu/trove/TDecorators.template0000644000175000017500000000711411763017634021551 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2008, Robert D. Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove; import java.util.*; import gnu.trove.list.*; import gnu.trove.map.*; import gnu.trove.set.*; import gnu.trove.decorator.*; /** * This is a static utility class that provides functions for simplifying creation of * decorators. * * @author Robert D. Eden * @author Jeff Randall * @since Trove 2.1 */ public class TDecorators { // Hide the constructor private TDecorators() {} #REPLICATED1# #REPLICATED2# #REPLICATED3# #REPLICATED4# #REPLICATED5# } ====START_REPLICATED_CONTENT #1==== /** * Wrap the given map in a decorator that uses the standard {@link java.util.Map Map} * interface. * * @param map the T#K##V#ObjectMap to be wrapped * @return the wrapped map. */ public static Map<#KT#,#VT#> wrap( T#K##V#Map map ) { return new T#K##V#MapDecorator( map ); } =====END_REPLICATED_CONTENT #1===== ====START_REPLICATED_CONTENT #2==== /** * Wrap the given map in a decorator that uses the standard {@link java.util.Map Map} * interface. * * @param map the TObject#E#Map to be wrapped * @return the wrapped map. */ public static Map wrap( TObject#E#Map map ) { return new TObject#E#MapDecorator( map ); } =====END_REPLICATED_CONTENT #2===== ====START_REPLICATED_CONTENT #3==== /** * Wrap the given map in a decorator that uses the standard {@link java.util.Map Map} * interface. * * @param map the T#E#ObjectMap to be wrapped * @return the wrapped map. */ public static Map<#ET#,T> wrap( T#E#ObjectMap map ) { return new T#E#ObjectMapDecorator( map ); } =====END_REPLICATED_CONTENT #3===== ====START_REPLICATED_CONTENT #4==== /** * Wrap the given set in a decorator that uses the standard {@link java.util.Set Set} * interface. * * @param set the T#E#Set to be wrapped * @return the wrapped set. */ public static Set<#ET#> wrap( T#E#Set set ) { return new T#E#SetDecorator( set ); } =====END_REPLICATED_CONTENT #4===== ====START_REPLICATED_CONTENT #5==== /** * Wrap the given list in a decorator that uses the standard {@link java.util.List List} * interface. * * @param list the T#E#List to be wrapped * @return the wrapped list. */ public static List<#ET#> wrap( T#E#List list ) { return new T#E#ListDecorator( list ); } =====END_REPLICATED_CONTENT #5=====trove-3.0.3/templates/gnu/trove/set/0000755000175000017500000000000012000515265016337 5ustar ericherichtrove-3.0.3/templates/gnu/trove/set/hash/0000755000175000017500000000000012000515265017262 5ustar ericherichtrove-3.0.3/templates/gnu/trove/set/hash/_E_HashSet.template0000644000175000017500000003563311763017634023007 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001, Eric D. Friedman All Rights Reserved. // Copyright (c) 2009, Rob Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.set.hash; import gnu.trove.set.T#E#Set; import gnu.trove.iterator.T#E#Iterator; import gnu.trove.impl.*; import gnu.trove.impl.hash.*; import gnu.trove.T#E#Collection; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.io.Externalizable; import java.util.Arrays; import java.util.Collection; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// /** * An open addressed set implementation for #e# primitives. * * @author Eric D. Friedman * @author Rob Eden * @author Jeff Randall */ public class T#E#HashSet extends T#E#Hash implements T#E#Set, Externalizable { static final long serialVersionUID = 1L; /** * Creates a new T#E#HashSet instance with the default * capacity and load factor. */ public T#E#HashSet() { super(); } /** * Creates a new T#E#HashSet instance with a prime * capacity equal to or greater than initialCapacity and * with the default load factor. * * @param initialCapacity an int value */ public T#E#HashSet( int initialCapacity ) { super( initialCapacity ); } /** * Creates a new TIntHash instance with a prime * value at or near the specified capacity and load factor. * * @param initialCapacity used to find a prime capacity for the table. * @param load_factor used to calculate the threshold over which * rehashing takes place. */ public T#E#HashSet( int initialCapacity, float load_factor ) { super( initialCapacity, load_factor ); } /** * Creates a new T#E#HashSet instance with a prime * capacity equal to or greater than initial_capacity and * with the specified load factor. * * @param initial_capacity an int value * @param load_factor a float value * @param no_entry_value a #e# value that represents null. */ public T#E#HashSet( int initial_capacity, float load_factor, #e# no_entry_value ) { super( initial_capacity, load_factor, no_entry_value ); //noinspection RedundantCast if ( no_entry_value != ( #e# ) 0 ) { Arrays.fill( _set, no_entry_value ); } } /** * Creates a new T#E#HashSet instance that is a copy * of the existing Collection. * * @param collection a Collection that will be duplicated. */ public T#E#HashSet( Collection collection ) { this( Math.max( collection.size(), DEFAULT_CAPACITY ) ); addAll( collection ); } /** * Creates a new T#E#HashSet instance that is a copy * of the existing set. * * @param collection a T#E#Set that will be duplicated. */ public T#E#HashSet( T#E#Collection collection ) { this( Math.max( collection.size(), DEFAULT_CAPACITY ) ); if ( collection instanceof T#E#HashSet ) { T#E#HashSet hashset = ( T#E#HashSet ) collection; this._loadFactor = hashset._loadFactor; this.no_entry_value = hashset.no_entry_value; //noinspection RedundantCast if ( this.no_entry_value != ( #e# ) 0 ) { Arrays.fill( _set, this.no_entry_value ); } setUp( (int) Math.ceil( DEFAULT_CAPACITY / _loadFactor ) ); } addAll( collection ); } /** * Creates a new T#E#HashSet instance containing the * elements of array. * * @param array an array of #e# primitives */ public T#E#HashSet( #e#[] array ) { this( Math.max( array.length, DEFAULT_CAPACITY ) ); addAll( array ); } /** {@inheritDoc} */ public T#E#Iterator iterator() { return new T#E#HashIterator( this ); } /** {@inheritDoc} */ public #e#[] toArray() { #e#[] result = new #e#[ size() ]; #e#[] set = _set; byte[] states = _states; for ( int i = states.length, j = 0; i-- > 0; ) { if ( states[i] == FULL ) { result[j++] = set[i]; } } return result; } /** {@inheritDoc} */ public #e#[] toArray( #e#[] dest ) { #e#[] set = _set; byte[] states = _states; for ( int i = states.length, j = 0; i-- > 0; ) { if ( states[i] == FULL ) { dest[j++] = set[i]; } } if ( dest.length > _size ) { dest[_size] = no_entry_value; } return dest; } /** {@inheritDoc} */ public boolean add( #e# val ) { int index = insertKey(val); if ( index < 0 ) { return false; // already present in set, nothing to add } postInsertHook( consumeFreeSlot ); return true; // yes, we added something } /** {@inheritDoc} */ public boolean remove( #e# val ) { int index = index(val); if ( index >= 0 ) { removeAt( index ); return true; } return false; } /** {@inheritDoc} */ public boolean containsAll( Collection collection ) { for ( Object element : collection ) { if ( element instanceof #ET# ) { #e# c = ( ( #ET# ) element ).#e#Value(); if ( ! contains( c ) ) { return false; } } else { return false; } } return true; } /** {@inheritDoc} */ public boolean containsAll( T#E#Collection collection ) { T#E#Iterator iter = collection.iterator(); while ( iter.hasNext() ) { #e# element = iter.next(); if ( ! contains( element ) ) { return false; } } return true; } /** {@inheritDoc} */ public boolean containsAll( #e#[] array ) { for ( int i = array.length; i-- > 0; ) { if ( ! contains( array[i] ) ) { return false; } } return true; } /** {@inheritDoc} */ public boolean addAll( Collection collection ) { boolean changed = false; for ( #ET# element : collection ) { #e# e = element.#e#Value(); if ( add( e ) ) { changed = true; } } return changed; } /** {@inheritDoc} */ public boolean addAll( T#E#Collection collection ) { boolean changed = false; T#E#Iterator iter = collection.iterator(); while ( iter.hasNext() ) { #e# element = iter.next(); if ( add( element ) ) { changed = true; } } return changed; } /** {@inheritDoc} */ public boolean addAll( #e#[] array ) { boolean changed = false; for ( int i = array.length; i-- > 0; ) { if ( add( array[i] ) ) { changed = true; } } return changed; } /** {@inheritDoc} */ @SuppressWarnings({"SuspiciousMethodCalls"}) public boolean retainAll( Collection collection ) { boolean modified = false; T#E#Iterator iter = iterator(); while ( iter.hasNext() ) { if ( ! collection.contains( #ET#.valueOf ( iter.next() ) ) ) { iter.remove(); modified = true; } } return modified; } /** {@inheritDoc} */ public boolean retainAll( T#E#Collection collection ) { if ( this == collection ) { return false; } boolean modified = false; T#E#Iterator iter = iterator(); while ( iter.hasNext() ) { if ( ! collection.contains( iter.next() ) ) { iter.remove(); modified = true; } } return modified; } /** {@inheritDoc} */ public boolean retainAll( #e#[] array ) { boolean changed = false; Arrays.sort( array ); #e#[] set = _set; byte[] states = _states; _autoCompactTemporaryDisable = true; for ( int i = set.length; i-- > 0; ) { if ( states[i] == FULL && ( Arrays.binarySearch( array, set[i] ) < 0) ) { removeAt( i ); changed = true; } } _autoCompactTemporaryDisable = false; return changed; } /** {@inheritDoc} */ public boolean removeAll( Collection collection ) { boolean changed = false; for ( Object element : collection ) { if ( element instanceof #ET# ) { #e# c = ( ( #ET# ) element ).#e#Value(); if ( remove( c ) ) { changed = true; } } } return changed; } /** {@inheritDoc} */ public boolean removeAll( T#E#Collection collection ) { boolean changed = false; T#E#Iterator iter = collection.iterator(); while ( iter.hasNext() ) { #e# element = iter.next(); if ( remove( element ) ) { changed = true; } } return changed; } /** {@inheritDoc} */ public boolean removeAll( #e#[] array ) { boolean changed = false; for ( int i = array.length; i-- > 0; ) { if ( remove(array[i]) ) { changed = true; } } return changed; } /** {@inheritDoc} */ public void clear() { super.clear(); #e#[] set = _set; byte[] states = _states; for ( int i = set.length; i-- > 0; ) { set[i] = no_entry_value; states[i] = FREE; } } /** {@inheritDoc} */ protected void rehash( int newCapacity ) { int oldCapacity = _set.length; #e# oldSet[] = _set; byte oldStates[] = _states; _set = new #e#[newCapacity]; _states = new byte[newCapacity]; for ( int i = oldCapacity; i-- > 0; ) { if( oldStates[i] == FULL ) { #e# o = oldSet[i]; int index = insertKey(o); } } } /** {@inheritDoc} */ public boolean equals( Object other ) { if ( ! ( other instanceof T#E#Set ) ) { return false; } T#E#Set that = ( T#E#Set ) other; if ( that.size() != this.size() ) { return false; } for ( int i = _states.length; i-- > 0; ) { if ( _states[i] == FULL ) { if ( ! that.contains( _set[i] ) ) { return false; } } } return true; } /** {@inheritDoc} */ public int hashCode() { int hashcode = 0; for ( int i = _states.length; i-- > 0; ) { if ( _states[i] == FULL ) { hashcode += HashFunctions.hash( _set[i] ); } } return hashcode; } /** {@inheritDoc} */ public String toString() { StringBuilder buffy = new StringBuilder( _size * 2 + 2 ); buffy.append("{"); for ( int i = _states.length, j = 1; i-- > 0; ) { if ( _states[i] == FULL ) { buffy.append( _set[i] ); if ( j++ < _size ) { buffy.append( "," ); } } } buffy.append("}"); return buffy.toString(); } class T#E#HashIterator extends THashPrimitiveIterator implements T#E#Iterator { /** the collection on which the iterator operates */ private final T#E#Hash _hash; /** {@inheritDoc} */ public T#E#HashIterator( T#E#Hash hash ) { super( hash ); this._hash = hash; } /** {@inheritDoc} */ public #e# next() { moveToNextIndex(); return _hash._set[_index]; } } /** {@inheritDoc} */ public void writeExternal( ObjectOutput out ) throws IOException { // VERSION out.writeByte( 1 ); // SUPER super.writeExternal( out ); // NUMBER OF ENTRIES out.writeInt( _size ); // LOAD FACTOR -- Added version 1 out.writeFloat( _loadFactor ); // NO ENTRY VALUE -- Added version 1 out.write#E#( no_entry_value ); // ENTRIES for ( int i = _states.length; i-- > 0; ) { if ( _states[i] == FULL ) { out.write#E#( _set[i] ); } } } /** {@inheritDoc} */ public void readExternal( ObjectInput in ) throws IOException, ClassNotFoundException { // VERSION int version = in.readByte(); // SUPER super.readExternal( in ); // NUMBER OF ENTRIES int size = in.readInt(); if ( version >= 1 ) { // LOAD FACTOR _loadFactor = in.readFloat(); // NO ENTRY VALUE no_entry_value = in.read#E#(); //noinspection RedundantCast if ( no_entry_value != ( #e# ) 0 ) { Arrays.fill( _set, no_entry_value ); } } // ENTRIES setUp( size ); while ( size-- > 0 ) { #e# val = in.read#E#(); add( val ); } } } // TIntHashSet trove-3.0.3/templates/gnu/trove/set/_E_Set.template0000644000175000017500000002460211763017634021252 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001, Eric D. Friedman All Rights Reserved. // Copyright (c) 2009, Rob Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.set; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// import gnu.trove.iterator.T#E#Iterator; import gnu.trove.procedure.T#E#Procedure; import gnu.trove.T#E#Collection; import java.util.Collection; import java.util.Set; import java.io.Serializable; /** * An implementation of the Set interface that uses an * open-addressed hash table to store its contents. * * Created: Sat Nov 3 10:38:17 2001 * * @author Eric D. Friedman, Rob Eden, Jeff Randall * @version $Id: _E_Set.template,v 1.1.2.5 2009/09/15 02:38:31 upholderoftruth Exp $ */ public interface T#E#Set extends T#E#Collection { /** * Returns the value that is used to represent null. The default * value is generally zero, but can be changed during construction * of the collection. * * @return the value that represents null */ #e# getNoEntryValue(); /** * Returns the number of elements in this set (its cardinality). If this * set contains more than Integer.MAX_VALUE elements, returns * Integer.MAX_VALUE. * * @return the number of elements in this set (its cardinality) */ int size(); /** * Returns true if this set contains no elements. * * @return true if this set contains no elements */ boolean isEmpty(); /** * Returns true if this set contains the specified element. * * @param entry an #e# value * @return true if the set contains the specified element. */ boolean contains( #e# entry ); /** * Creates an iterator over the values of the set. The iterator * supports element deletion. * * @return an T#E#Iterator value */ T#E#Iterator iterator(); /** * Returns an array containing all of the elements in this set. * If this set makes any guarantees as to what order its elements * are returned by its iterator, this method must return the * elements in the same order. * *

The returned array will be "safe" in that no references to it * are maintained by this set. (In other words, this method must * allocate a new array even if this set is backed by an array). * The caller is thus free to modify the returned array. * *

This method acts as bridge between array-based and collection-based * APIs. * * @return an array containing all the elements in this set */ #e#[] toArray(); /** * Returns an array containing elements in this set. * *

If this set fits in the specified array with room to spare * (i.e., the array has more elements than this set), the element in * the array immediately following the end of the set is set to * {@link #getNoEntryValue()}. (This is useful in determining * the length of this set only if the caller knows that this * set does not contain any elements representing null.) * *

If the native array is smaller than the set size, * the array will be filled with elements in Iterator order * until it is full and exclude the remainder. * *

If this set makes any guarantees as to what order its elements * are returned by its iterator, this method must return the elements * in the same order. * * @param dest the array into which the elements of this set are to be * stored. * @return an #e#[] containing all the elements in this set * @throws NullPointerException if the specified array is null */ #e#[] toArray( #e#[] dest ); /** * Inserts a value into the set. * * @param entry a #e# value * @return true if the set was modified by the add operation */ boolean add( #e# entry ); /** * Removes entry from the set. * * @param entry an #e# value * @return true if the set was modified by the remove operation. */ boolean remove( #e# entry ); /** * Tests the set to determine if all of the elements in * collection are present. * * @param collection a Collection value * @return true if all elements were present in the set. */ boolean containsAll( Collection collection ); /** * Tests the set to determine if all of the elements in * T#E#Collection are present. * * @param collection a T#E#Collection value * @return true if all elements were present in the set. */ boolean containsAll( T#E#Collection collection ); /** * Tests the set to determine if all of the elements in * array are present. * * @param array as array of #e# primitives. * @return true if all elements were present in the set. */ boolean containsAll( #e#[] array ); /** * Adds all of the elements in collection to the set. * * @param collection a Collection value * @return true if the set was modified by the add all operation. */ boolean addAll( Collection collection ); /** * Adds all of the elements in the T#E#Collection to the set. * * @param collection a T#E#Collection value * @return true if the set was modified by the add all operation. */ boolean addAll( T#E#Collection collection ); /** * Adds all of the elements in the array to the set. * * @param array a array of #e# primitives. * @return true if the set was modified by the add all operation. */ boolean addAll( #e#[] array ); /** * Removes any values in the set which are not contained in * collection. * * @param collection a Collection value * @return true if the set was modified by the retain all operation */ boolean retainAll( Collection collection ); /** * Removes any values in the set which are not contained in * T#E#Collection. * * @param collection a T#E#Collection value * @return true if the set was modified by the retain all operation */ boolean retainAll( T#E#Collection collection ); /** * Removes any values in the set which are not contained in * array. * * @param array an array of #e# primitives. * @return true if the set was modified by the retain all operation */ boolean retainAll( #e#[] array ); /** * Removes all of the elements in collection from the set. * * @param collection a Collection value * @return true if the set was modified by the remove all operation. */ boolean removeAll( Collection collection ); /** * Removes all of the elements in T#E#Collection from the set. * * @param collection a T#E#Collection value * @return true if the set was modified by the remove all operation. */ boolean removeAll( T#E#Collection collection ); /** * Removes all of the elements in array from the set. * * @param array an array of #e# primitives. * @return true if the set was modified by the remove all operation. */ public boolean removeAll( #e#[] array ); /** * Empties the set. */ void clear(); /** * Executes procedure for each element in the set. * * @param procedure a T#E#Procedure value * @return false if the loop over the set terminated because * the procedure returned false for some value. */ boolean forEach( T#E#Procedure procedure ); // Comparison and hashing /** * Compares the specified object with this set for equality. Returns * true if the specified object is also a set, the two sets * have the same size, and every member of the specified set is * contained in this set (or equivalently, every member of this set is * contained in the specified set). This definition ensures that the * equals method works properly across different implementations of the * set interface. * * @param o object to be compared for equality with this set * @return true if the specified object is equal to this set */ boolean equals( Object o ); /** * Returns the hash code value for this set. The hash code of a set is * defined to be the sum of the hash codes of the elements in the set. * This ensures that s1.equals(s2) implies that * s1.hashCode()==s2.hashCode() for any two sets s1 * and s2, as required by the general contract of * {@link Object#hashCode}. * * @return the hash code value for this set * @see Object#equals(Object) * @see Set#equals(Object) */ int hashCode(); } // THashSet trove-3.0.3/templates/gnu/trove/stack/0000755000175000017500000000000012000515265016651 5ustar ericherichtrove-3.0.3/templates/gnu/trove/stack/_E_Stack.template0000644000175000017500000000527211763017634022100 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001, Eric D. Friedman All Rights Reserved. // Copyright (c) 2009, Rob Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.stack; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// import java.io.Serializable; /** * A stack of #e# primitives. */ public interface T#E#Stack { /** * Returns the value that is used to represent null. The default * value is generally zero, but can be changed during construction * of the collection. * * @return the value that represents null */ public #e# getNoEntryValue(); /** * Pushes the value onto the top of the stack. * * @param val an #e# value */ public void push( #e# val ); /** * Removes and returns the value at the top of the stack. * * @return an #e# value */ public #e# pop(); /** * Returns the value at the top of the stack. * * @return an #e# value */ public #e# peek(); /** * Returns the current depth of the stack. */ public int size(); /** * Clears the stack. */ public void clear(); /** * Copies the contents of the stack into a native array. Note that this will NOT * pop them out of the stack. * * @return an #e#[] value */ public #e#[] toArray(); /** * Copies a slice of the list into a native array. Note that this will NOT * pop them out of the stack. * * @param dest the array to copy into. */ public void toArray( #e#[] dest ); }trove-3.0.3/templates/gnu/trove/stack/array/0000755000175000017500000000000012000515265017767 5ustar ericherichtrove-3.0.3/templates/gnu/trove/stack/array/_E_ArrayStack.template0000644000175000017500000001756011763017634024220 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001, Eric D. Friedman All Rights Reserved. // Copyright (c) 2009, Rob Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.stack.array; import gnu.trove.stack.T#E#Stack; import gnu.trove.list.array.T#E#ArrayList; import gnu.trove.impl.*; import java.io.Externalizable; import java.io.ObjectInput; import java.io.ObjectOutput; import java.io.IOException; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// /** * A stack of #e# primitives, backed by a T#E#ArrayList */ public class T#E#ArrayStack implements T#E#Stack, Externalizable { static final long serialVersionUID = 1L; /** the list used to hold the stack values. */ protected T#E#ArrayList _list; public static final int DEFAULT_CAPACITY = Constants.DEFAULT_CAPACITY; /** * Creates a new T#E#ArrayStack instance with the default * capacity. */ public T#E#ArrayStack() { this( DEFAULT_CAPACITY ); } /** * Creates a new T#E#ArrayStack instance with the * specified capacity. * * @param capacity the initial depth of the stack */ public T#E#ArrayStack( int capacity ) { _list = new T#E#ArrayList( capacity ); } /** * Creates a new T#E#ArrayStack instance with the * specified capacity. * * @param capacity the initial depth of the stack * @param no_entry_value value that represents null */ public T#E#ArrayStack( int capacity, #e# no_entry_value ) { _list = new T#E#ArrayList( capacity, no_entry_value ); } /** * Creates a new T#E#ArrayStack instance that is * a copy of the instanced passed to us. * * @param stack the instance to copy */ public T#E#ArrayStack( T#E#Stack stack ) { if ( stack instanceof T#E#ArrayStack ) { T#E#ArrayStack array_stack = ( T#E#ArrayStack ) stack; this._list = new T#E#ArrayList( array_stack._list ); } else { throw new UnsupportedOperationException( "Only support T#E#ArrayStack" ); } } /** * Returns the value that is used to represent null. The default * value is generally zero, but can be changed during construction * of the collection. * * @return the value that represents null */ public #e# getNoEntryValue() { return _list.getNoEntryValue(); } /** * Pushes the value onto the top of the stack. * * @param val an #e# value */ public void push( #e# val ) { _list.add( val ); } /** * Removes and returns the value at the top of the stack. * * @return an #e# value */ public #e# pop() { return _list.removeAt( _list.size() - 1 ); } /** * Returns the value at the top of the stack. * * @return an #e# value */ public #e# peek() { return _list.get( _list.size() - 1 ); } /** * Returns the current depth of the stack. */ public int size() { return _list.size(); } /** * Clears the stack. */ public void clear() { _list.clear(); } /** * Copies the contents of the stack into a native array. Note that this will NOT * pop them out of the stack. The front of the list will be the top of the stack. * * @return an #e#[] value */ public #e#[] toArray() { #e#[] retval = _list.toArray(); reverse( retval, 0, size() ); return retval; } /** * Copies a slice of the list into a native array. Note that this will NOT * pop them out of the stack. The front of the list will be the top * of the stack. *

* If the native array is smaller than the stack depth, * the native array will be filled with the elements from the top * of the array until it is full and exclude the remainder. * * @param dest the array to copy into. */ public void toArray( #e#[] dest ) { int size = size(); int start = size - dest.length; if ( start < 0 ) { start = 0; } int length = Math.min( size, dest.length ); _list.toArray( dest, start, length ); reverse( dest, 0, length ); if ( dest.length > size ) { dest[size] = _list.getNoEntryValue(); } } /** * Reverse the order of the elements in the range of the list. * * @param dest the array of data * @param from the inclusive index at which to start reversing * @param to the exclusive index at which to stop reversing */ private void reverse( #e#[] dest, int from, int to ) { if ( from == to ) { return; // nothing to do } if ( from > to ) { throw new IllegalArgumentException( "from cannot be greater than to" ); } for ( int i = from, j = to - 1; i < j; i++, j-- ) { swap( dest, i, j ); } } /** * Swap the values at offsets i and j. * * @param dest the array of data * @param i an offset into the data array * @param j an offset into the data array */ private void swap( #e#[] dest, int i, int j ) { #e# tmp = dest[ i ]; dest[ i ] = dest[ j ]; dest[ j ] = tmp; } /** * Returns a String representation of the list, top to bottom. * * @return a String value */ public String toString() { final StringBuilder buf = new StringBuilder( "{" ); for ( int i = _list.size() - 1; i > 0; i-- ) { buf.append( _list.get( i ) ); buf.append( ", " ); } if ( size() > 0 ) { buf.append( _list.get( 0 ) ); } buf.append( "}" ); return buf.toString(); } public boolean equals( Object o ) { if ( this == o ) { return true; } if ( o == null || getClass() != o.getClass() ) { return false; } T#E#ArrayStack that = ( T#E#ArrayStack ) o; return _list.equals( that._list ); } public int hashCode() { return _list.hashCode(); } public void writeExternal( ObjectOutput out ) throws IOException { // VERSION out.writeByte( 0 ); // LIST out.writeObject( _list ); } public void readExternal( ObjectInput in ) throws IOException, ClassNotFoundException { // VERSION in.readByte(); // LIST _list = ( T#E#ArrayList ) in.readObject(); } } // T#E#ArrayStacktrove-3.0.3/templates/gnu/trove/function/0000755000175000017500000000000012000515265017371 5ustar ericherichtrove-3.0.3/templates/gnu/trove/function/_E_Function.template0000644000175000017500000000271311763017634023335 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001, Eric D. Friedman All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.function; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// /** * Interface for functions that accept and return one #e# primitive. */ public interface T#E#Function { /** * Execute this function with value * * @param value a #e# input * @return a #e# result */ public #e# execute( #e# value ); } trove-3.0.3/templates/gnu/trove/_E_Collection.template0000644000175000017500000002540511763017634022021 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001, Eric D. Friedman All Rights Reserved. // Copyright (c) 2009, Rob Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// import gnu.trove.iterator.T#E#Iterator; import gnu.trove.procedure.T#E#Procedure; import java.util.Collection; import java.io.Serializable; /** * An interface that mimics the Collection interface. * * @author Eric D. Friedman * @author Rob Eden * @author Jeff Randall * @version $Id: _E_Collection.template,v 1.1.2.2 2009/09/15 02:38:30 upholderoftruth Exp $ */ public interface T#E#Collection { static final long serialVersionUID = 1L; /** * Returns the value that is used to represent null. The default * value is generally zero, but can be changed during construction * of the collection. * * @return the value that represents null */ #e# getNoEntryValue(); /** * Returns the number of elements in this collection (its cardinality). If this * collection contains more than Integer.MAX_VALUE elements, returns * Integer.MAX_VALUE. * * @return the number of elements in this collection (its cardinality) */ int size(); /** * Returns true if this collection contains no elements. * * @return true if this collection contains no elements */ boolean isEmpty(); /** * Returns true if this collection contains the specified element. * * @param entry an #e# value * @return true if the collection contains the specified element. */ boolean contains( #e# entry ); /** * Creates an iterator over the values of the collection. The iterator * supports element deletion. * * @return an T#E#Iterator value */ T#E#Iterator iterator(); /** * Returns an array containing all of the elements in this collection. * If this collection makes any guarantees as to what order its elements * are returned by its iterator, this method must return the * elements in the same order. * *

The returned array will be "safe" in that no references to it * are maintained by this collection. (In other words, this method must * allocate a new array even if this collection is backed by an array). * The caller is thus free to modify the returned array. * *

This method acts as bridge between array-based and collection-based * APIs. * * @return an array containing all the elements in this collection */ #e#[] toArray(); /** * Returns an array containing elements in this collection. * *

If this collection fits in the specified array with room to spare * (i.e., the array has more elements than this collection), the element in * the array immediately following the end of the collection is collection to * {@link #getNoEntryValue()}. (This is useful in determining * the length of this collection only if the caller knows that this * collection does not contain any elements representing null.) * *

If the native array is smaller than the collection size, * the array will be filled with elements in Iterator order * until it is full and exclude the remainder. * *

If this collection makes any guarantees as to what order its elements * are returned by its iterator, this method must return the elements * in the same order. * * @param dest the array into which the elements of this collection are to be * stored. * @return an #e#[] containing all the elements in this collection * @throws NullPointerException if the specified array is null */ #e#[] toArray( #e#[] dest ); /** * Inserts a value into the collection. * * @param entry a #e# value * @return true if the collection was modified by the add operation */ boolean add( #e# entry ); /** * Removes entry from the collection. * * @param entry an #e# value * @return true if the collection was modified by the remove operation. */ boolean remove( #e# entry ); /** * Tests the collection to determine if all of the elements in * collection are present. * * @param collection a Collection value * @return true if all elements were present in the collection. */ boolean containsAll( Collection collection ); /** * Tests the collection to determine if all of the elements in * T#E#Collection are present. * * @param collection a T#E#Collection value * @return true if all elements were present in the collection. */ boolean containsAll( T#E#Collection collection ); /** * Tests the collection to determine if all of the elements in * array are present. * * @param array as array of #e# primitives. * @return true if all elements were present in the collection. */ boolean containsAll( #e#[] array ); /** * Adds all of the elements in collection to the collection. * * @param collection a Collection value * @return true if the collection was modified by the add all operation. */ boolean addAll( Collection collection ); /** * Adds all of the elements in the T#E#Collection to the collection. * * @param collection a T#E#Collection value * @return true if the collection was modified by the add all operation. */ boolean addAll( T#E#Collection collection ); /** * Adds all of the elements in the array to the collection. * * @param array a array of #e# primitives. * @return true if the collection was modified by the add all operation. */ boolean addAll( #e#[] array ); /** * Removes any values in the collection which are not contained in * collection. * * @param collection a Collection value * @return true if the collection was modified by the retain all operation */ boolean retainAll( Collection collection ); /** * Removes any values in the collection which are not contained in * T#E#Collection. * * @param collection a T#E#Collection value * @return true if the collection was modified by the retain all operation */ boolean retainAll( T#E#Collection collection ); /** * Removes any values in the collection which are not contained in * array. * * @param array an array of #e# primitives. * @return true if the collection was modified by the retain all operation */ boolean retainAll( #e#[] array ); /** * Removes all of the elements in collection from the collection. * * @param collection a Collection value * @return true if the collection was modified by the remove all operation. */ boolean removeAll( Collection collection ); /** * Removes all of the elements in T#E#Collection from the collection. * * @param collection a T#E#Collection value * @return true if the collection was modified by the remove all operation. */ boolean removeAll( T#E#Collection collection ); /** * Removes all of the elements in array from the collection. * * @param array an array of #e# primitives. * @return true if the collection was modified by the remove all operation. */ boolean removeAll( #e#[] array ); /** * Empties the collection. */ void clear(); /** * Executes procedure for each element in the collection. * * @param procedure a T#E#Procedure value * @return false if the loop over the collection terminated because * the procedure returned false for some value. */ boolean forEach( T#E#Procedure procedure ); // Comparison and hashing /** * Compares the specified object with this collection for equality. Returns * true if the specified object is also a collection, the two collection * have the same size, and every member of the specified collection is * contained in this collection (or equivalently, every member of this collection is * contained in the specified collection). This definition ensures that the * equals method works properly across different implementations of the * collection interface. * * @param o object to be compared for equality with this collection * @return true if the specified object is equal to this collection */ boolean equals( Object o ); /** * Returns the hash code value for this collection. The hash code of a collection is * defined to be the sum of the hash codes of the elements in the collection. * This ensures that s1.equals(s2) implies that * s1.hashCode()==s2.hashCode() for any two collection s1 * and s2, as required by the general contract of * {@link Object#hashCode}. * * @return the hash code value for this collection * @see Object#equals(Object) * @see Collection#equals(Object) */ int hashCode(); } // T#E#Collection trove-3.0.3/templates/gnu/trove/map/0000755000175000017500000000000012000515265016321 5ustar ericherichtrove-3.0.3/templates/gnu/trove/map/_K__V_Map.template0000644000175000017500000002247011763017634021651 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2009, Rob Eden All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.map; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// import gnu.trove.function.*; import gnu.trove.iterator.*; import gnu.trove.procedure.*; import gnu.trove.set.*; import gnu.trove.T#V#Collection; import java.util.Map; import java.io.Serializable; /** * Interface for a primitive map of #k# keys and #v# values. */ public interface T#K##V#Map { /** * Returns the value that will be returned from {@link #get} or {@link #put} if no * entry exists for a given key. The default value is generally zero, but can be * changed during construction of the collection. * * @return the value that represents a null key in this collection. */ public #k# getNoEntryKey(); /** * Returns the value that will be returned from {@link #get} or {@link #put} if no * entry exists for a given key. The default value is generally zero, but can be * changed during construction of the collection. * * @return the value that represents a null value in this collection. */ public #v# getNoEntryValue(); /** * Inserts a key/value pair into the map. * * @param key an #k# value * @param value an #v# value * * @return the previous value associated with key, or the "no entry" value * if none was found (see {@link #getNoEntryValue}). */ public #v# put( #k# key, #v# value ); /** * Inserts a key/value pair into the map if the specified key is not already * associated with a value. * * @param key an #k# value * @param value an #v# value * * @return the previous value associated with key, or the "no entry" value * if none was found (see {@link #getNoEntryValue}). */ public #v# putIfAbsent( #k# key, #v# value ); /** * Put all the entries from the given Map into this map. * * @param map The Map from which entries will be obtained to put into this map. */ public void putAll( Map map ); /** * Put all the entries from the given map into this map. * * @param map The map from which entries will be obtained to put into this map. */ public void putAll( T#K##V#Map map ); /** * Retrieves the value for key * * @param key an #k# value * * @return the previous value associated with key, or the "no entry" value * if none was found (see {@link #getNoEntryValue}). */ public #v# get( #k# key ); /** * Empties the map. */ public void clear(); /** * Returns true if this map contains no key-value mappings. * * @return true if this map contains no key-value mappings */ public boolean isEmpty(); /** * Deletes a key/value pair from the map. * * @param key an #k# value * * @return the previous value associated with key, or the "no entry" value * if none was found (see {@link #getNoEntryValue}). */ public #v# remove( #k# key ); /** * Returns an int value that is the number of elements in the map. * * @return an int value that is the number of elements in the map. */ public int size(); /** * Returns the keys of the map as a T#K#Set * * @return the keys of the map as a T#K#Set */ public T#K#Set keySet(); /** * Returns the keys of the map as an array of #k# values. * * @return the keys of the map as an array of #k# values. */ public #k#[] keys(); /** * Returns the keys of the map. * * @param array the array into which the elements of the list are to be stored, * if it is big enough; otherwise, a new array of the same type is * allocated for this purpose. * @return the keys of the map as an array. */ public #k#[] keys( #k#[] array ); /** * Returns the values of the map as a T#V#Collection * * @return the values of the map as a T#V#Collection */ public T#V#Collection valueCollection(); /** * Returns the values of the map as an array of #e# values. * * @return the values of the map as an array of #e# values. */ public #v#[] values(); /** * Returns the values of the map using an existing array. * * @param array the array into which the elements of the list are to be stored, * if it is big enough; otherwise, a new array of the same type is * allocated for this purpose. * @return the values of the map as an array of #e# values. */ public #v#[] values( #v#[] array ); /** * Checks for the presence of val in the values of the map. * * @param val an #v# value * @return a boolean value */ public boolean containsValue( #v# val ); /** * Checks for the present of key in the keys of the map. * * @param key an #k# value * @return a boolean value */ public boolean containsKey( #k# key ); /** * @return a T#K##V#Iterator with access to this map's keys and values */ public T#K##V#Iterator iterator(); /** * Executes procedure for each key in the map. * * @param procedure a T#K#Procedure value * @return false if the loop over the keys terminated because * the procedure returned false for some key. */ public boolean forEachKey( T#K#Procedure procedure ); /** * Executes procedure for each value in the map. * * @param procedure a T#F#Procedure value * @return false if the loop over the values terminated because * the procedure returned false for some value. */ public boolean forEachValue( T#V#Procedure procedure ); /** * Executes procedure for each key/value entry in the * map. * * @param procedure a TO#K##V#Procedure value * @return false if the loop over the entries terminated because * the procedure returned false for some entry. */ public boolean forEachEntry( T#K##V#Procedure procedure ); /** * Transform the values in this map using function. * * @param function a T#V#Function value */ public void transformValues( T#V#Function function ); /** * Retains only those entries in the map for which the procedure * returns a true value. * * @param procedure determines which entries to keep * @return true if the map was modified. */ public boolean retainEntries( T#K##V#Procedure procedure ); /** * Increments the primitive value mapped to key by 1 * * @param key the key of the value to increment * @return true if a mapping was found and modified. */ public boolean increment( #k# key ); /** * Adjusts the primitive value mapped to key. * * @param key the key of the value to increment * @param amount the amount to adjust the value by. * @return true if a mapping was found and modified. */ public boolean adjustValue( #k# key, #v# amount ); /** * Adjusts the primitive value mapped to the key if the key is present in the map. * Otherwise, the initial_value is put in the map. * * @param key the key of the value to increment * @param adjust_amount the amount to adjust the value by * @param put_amount the value put into the map if the key is not initial present * * @return the value present in the map after the adjustment or put operation */ public #v# adjustOrPutValue( #k# key, #v# adjust_amount, #v# put_amount ); } trove-3.0.3/templates/gnu/trove/map/Object_E_Map.template0000644000175000017500000004450211763017634022346 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001, Eric D. Friedman All Rights Reserved. // Copyright (c) 2009, Rob Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.map; import gnu.trove.T#E#Collection; import gnu.trove.function.T#E#Function; import gnu.trove.procedure.TObjectProcedure; import gnu.trove.procedure.T#E#Procedure; import gnu.trove.procedure.TObject#E#Procedure; import gnu.trove.iterator.TObject#E#Iterator; import java.util.Map; import java.util.Set; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// /** * Interface for a primitive map of Object keys and #e# values. */ public interface TObject#E#Map { // Query Operations /** * Returns the value that will be returned from {@link #get} or {@link #put} if no * entry exists for a given key. The default value is generally zero, but can be * changed during construction of the collection. * * @return the value that represents a null value in this collection. */ #e# getNoEntryValue(); /** * Returns the number of key-value mappings in this map. If the * map contains more than Integer.MAX_VALUE elements, returns * Integer.MAX_VALUE. * * @return the number of key-value mappings in this map */ int size(); /** * Returns true if this map contains no key-value mappings. * * @return true if this map contains no key-value mappings */ boolean isEmpty(); /** * Returns true if this map contains a mapping for the specified * key. More formally, returns true if and only if * this map contains a mapping for a key k such that * (key==null ? k==null : key.equals(k)). (There can be * at most one such mapping.) * * @param key key whose presence in this map is to be tested * @return true if this map contains a mapping for the specified * key * @throws ClassCastException if the key is of an inappropriate type for * this map (optional) * @throws NullPointerException if the specified key is null and this map * does not permit null keys (optional) */ boolean containsKey( Object key ); /** * Returns true if this map maps one or more keys to the * specified value. More formally, returns true if and only if * this map contains at least one mapping to a value v such that * (value==no_entry_value ? v==no_entry_value : value.equals(v)). This operation * will probably require time linear in the map size for most * implementations of the Map interface. *

* Note that no_entry_value is the result of {@link #getNoEntryValue()} and represents * null for this map instance. * * @param value #e# value whose presence in this map is to be tested * @return true if this map maps one or more keys to the * specified value * @throws ClassCastException if the value is of an inappropriate type for * this map (optional) * @throws NullPointerException if the specified value is null and this * map does not permit null values (optional) */ boolean containsValue( #e# value ); /** * Returns the value to which the specified key is mapped, * or {@code null} if this map contains no mapping for the key. * *

More formally, if this map contains a mapping from a key * {@code k} to a value {@code v} such that {@code (key==null ? k==null : * key.equals(k))}, then this method returns {@code v}; otherwise * it returns {@code null}. (There can be at most one such mapping.) * *

If this map permits null values, then a return value of * {@code null} does not necessarily indicate that the map * contains no mapping for the key; it's also possible that the map * explicitly maps the key to {@code null}. The {@link #containsKey * containsKey} operation may be used to distinguish these two cases. * * @param key the key whose associated value is to be returned * @return the #e# value to which the specified key is mapped, or * {@code null} if this map contains no mapping for the key * @throws ClassCastException if the key is of an inappropriate type for * this map (optional) * @throws NullPointerException if the specified key is null and this map * does not permit null keys (optional) */ #e# get( Object key ); // Modification Operations /** * Associates the specified value with the specified key in this map * (optional operation). If the map previously contained a mapping for * the key, the old value is replaced by the specified value. (A map * m is said to contain a mapping for a key k if and only * if {@link #containsKey(Object) m.containsKey(k)} would return * true.) * * @param key key with which the specified value is to be associated * @param value an #e# value value to be associated with the specified key * @return the previous value associated with key, or * no_entry_value if there was no mapping for key. * (A no_entry_value return can also indicate that the map * previously associated null with key, * if the implementation supports null values.) * @throws UnsupportedOperationException if the put operation * is not supported by this map * @throws ClassCastException if the class of the specified key or value * prevents it from being stored in this map * @throws NullPointerException if the specified key or value is null * and this map does not permit null keys or values * @throws IllegalArgumentException if some property of the specified key * or value prevents it from being stored in this map * @see #getNoEntryValue() */ #e# put( K key, #e# value); /** * Inserts a key/value pair into the map if the specified key is not already * associated with a value. * * @param key key with which the specified value is to be associated * @param value an #e# value to be associated with the specified key * * @return the previous value associated with key, or the "no entry" value * if none was found (see {@link #getNoEntryValue}). */ #e# putIfAbsent( K key, #e# value ); /** * Removes the mapping for a key from this map if it is present * (optional operation). More formally, if this map contains a mapping * from key k to value v such that * (key==null ? k==null : key.equals(k)), that mapping * is removed. (The map can contain at most one such mapping.) * *

Returns the value to which this map previously associated the key, * or null if the map contained no mapping for the key. * *

If this map permits null values, then a return value of * null does not necessarily indicate that the map * contained no mapping for the key; it's also possible that the map * explicitly mapped the key to null. * *

The map will not contain a mapping for the specified key once the * call returns. * * @param key key whose mapping is to be removed from the map * @return the previous #e# value associated with key, or * null if there was no mapping for key. * @throws UnsupportedOperationException if the remove operation * is not supported by this map * @throws ClassCastException if the key is of an inappropriate type for * this map (optional) * @throws NullPointerException if the specified key is null and this * map does not permit null keys (optional) */ #e# remove( Object key ); // Bulk Operations /** * Copies all of the mappings from the specified map to this map * (optional operation). The effect of this call is equivalent to that * of calling {@link #put(Object,#e#) put(k, v)} on this map once * for each mapping from key k to value v in the * specified map. The behavior of this operation is undefined if the * specified map is modified while the operation is in progress. * * @param m mappings to be stored in this map * @throws UnsupportedOperationException if the putAll operation * is not supported by this map * @throws ClassCastException if the class of a key or value in the * specified map prevents it from being stored in this map * @throws NullPointerException if the specified map is null, or if * this map does not permit null keys or values, and the * specified map contains null keys or values * @throws IllegalArgumentException if some property of a key or value in * the specified map prevents it from being stored in this map */ void putAll( Map m); /** * Put all the entries from the given map into this map. * * @param map The map from which entries will be obtained to put into this map. */ void putAll( TObject#E#Map map ); /** * Removes all of the mappings from this map (optional operation). * The map will be empty after this call returns. * * @throws UnsupportedOperationException if the clear operation * is not supported by this map */ void clear(); // Views /** * Returns a {@link Set} view of the keys contained in this map. * The set is backed by the map, so changes to the map are * reflected in the set, and vice-versa. If the map is modified * while an iteration over the set is in progress (except through * the iterator's own remove operation), the results of * the iteration are undefined. The set supports element removal, * which removes the corresponding mapping from the map, via the * Iterator.remove, Set.remove, * removeAll, retainAll, and clear * operations. It does not support the add or addAll * operations. * * @return a set view of the keys contained in this map */ Set keySet(); /** * Returns a copy of the keys of the map as an array. * Changes to the array of keys will not be reflected in the map * nor vice-versa. * * @return a copy of the keys of the map as an array. */ Object[] keys(); /** * Returns a copy of the keys of the map as an array. * Changes to the array of keys will not be reflected in the map * nor vice-versa. * * @param array the array into which the elements of the list are to be stored, * if it is big enough; otherwise, a new array of the same type is * allocated for this purpose. * @return the keys of the map as an array. */ K[] keys( K[] array ); /** * Returns a {@link T#E#Collection} view of the values contained in this map. * The collection is backed by the map, so changes to the map are * reflected in the collection, and vice-versa. If the map is * modified while an iteration over the collection is in progress * (except through the iterator's own remove operation), * the results of the iteration are undefined. The collection * supports element removal, which removes the corresponding * mapping from the map, via the T#E#Iterator.remove, * T#E#Collection.remove, removeAll, * retainAll and clear operations. It does not * support the add or addAll operations. * * @return a collection view of the values contained in this map */ T#E#Collection valueCollection(); /** * Returns the values of the map as an array of #e# values. * Changes to the array of values will not be reflected in the map * nor vice-versa. * * @return the values of the map as an array of #e# values. */ #e#[] values(); /** * Returns the values of the map using an existing array. * Changes to the array of values will not be reflected in the map * nor vice-versa. * * @param array the array into which the elements of the list are to be stored, * if it is big enough; otherwise, a new array of the same type is * allocated for this purpose. * @return the values of the map as an array of #e# values. */ #e#[] values( #e#[] array ); /** * Returns a TObject#E#Iterator with access to this map's keys and values. * * @return a TObject#E#Iterator with access to this map's keys and values. */ public TObject#E#Iterator iterator(); /** * Increments the primitive value mapped to key by 1 * * @param key the key of the value to increment * @return true if a mapping was found and modified. */ public boolean increment( K key ); /** * Adjusts the primitive value mapped to key. * * @param key the key of the value to increment * @param amount the amount to adjust the value by. * @return true if a mapping was found and modified. */ public boolean adjustValue( K key, #e# amount ); /** * Adjusts the primitive value mapped to the key if the key is present in the map. * Otherwise, the initial_value is put in the map. * * @param key the key of the value to increment * @param adjust_amount the amount to adjust the value by * @param put_amount the value put into the map if the key is not initial present * * @return the value present in the map after the adjustment or put operation */ public #e# adjustOrPutValue( K key, #e# adjust_amount, #e# put_amount ); /** * Executes procedure for each key in the map. * * @param procedure a TObjectProcedure value * @return false if the loop over the keys terminated because * the procedure returned false for some key. */ public boolean forEachKey( TObjectProcedure procedure ); /** * Executes procedure for each value in the map. * * @param procedure a T#E#Procedure value * @return false if the loop over the values terminated because * the procedure returned false for some value. */ public boolean forEachValue( T#E#Procedure procedure ); /** * Executes procedure for each key/value entry in the * map. * * @param procedure a TOObject#E#Procedure value * @return false if the loop over the entries terminated because * the procedure returned false for some entry. */ public boolean forEachEntry( TObject#E#Procedure procedure ); /** * Transform the values in this map using function. * * @param function a T#E#Function value */ public void transformValues( T#E#Function function ); /** * Retains only those entries in the map for which the procedure * returns a true value. * * @param procedure determines which entries to keep * @return true if the map was modified. */ public boolean retainEntries( TObject#E#Procedure procedure ); // Comparison and hashing /** * Compares the specified object with this map for equality. Returns * true if the given object is also a map and the two maps * represent the same mappings. More formally, two maps m1 and * m2 represent the same mappings if * m1.entrySet().equals(m2.entrySet()). This ensures that the * equals method works properly across different implementations * of the Map interface. * * @param o object to be compared for equality with this map * @return true if the specified object is equal to this map */ boolean equals( Object o ); /** * Returns the hash code value for this map. The hash code of a map is * defined to be the sum of the hash codes of each entry in the map's * entrySet() view. This ensures that m1.equals(m2) * implies that m1.hashCode()==m2.hashCode() for any two maps * m1 and m2, as required by the general contract of * {@link Object#hashCode}. * * @return the hash code value for this map * @see Object#equals(Object) * @see #equals(Object) */ int hashCode(); }trove-3.0.3/templates/gnu/trove/map/hash/0000755000175000017500000000000012000515265017244 5ustar ericherichtrove-3.0.3/templates/gnu/trove/map/hash/_E_ObjectHashMap.template0000644000175000017500000007164511763017634024105 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001, Eric D. Friedman All Rights Reserved. // Copyright (c) 2009, Rob Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.map.hash; import gnu.trove.map.T#E#ObjectMap; import gnu.trove.impl.Constants; import gnu.trove.impl.HashFunctions; import gnu.trove.impl.hash.*; import gnu.trove.procedure.T#E#ObjectProcedure; import gnu.trove.procedure.T#E#Procedure; import gnu.trove.procedure.TObjectProcedure; import gnu.trove.iterator.T#E#Iterator; import gnu.trove.iterator.T#E#ObjectIterator; import gnu.trove.iterator.TPrimitiveIterator; import gnu.trove.function.TObjectFunction; import gnu.trove.set.T#E#Set; import gnu.trove.T#E#Collection; import java.io.*; import java.util.*; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// /** * An open addressed Map implementation for #e# keys and Object values. * * Created: Sun Nov 4 08:52:45 2001 * * @author Eric D. Friedman * @author Rob Eden * @author Jeff Randall */ public class T#E#ObjectHashMap extends T#E#Hash implements T#E#ObjectMap, Externalizable { static final long serialVersionUID = 1L; private final T#E#ObjectProcedure PUT_ALL_PROC = new T#E#ObjectProcedure() { public boolean execute( #e# key, V value) { put( key, value ); return true; } }; /** the values of the map */ protected transient V[] _values; /** the value that represents null in the key set. */ protected #e# no_entry_key; /** * Creates a new T#E#ObjectHashMap instance with the default * capacity and load factor. */ public T#E#ObjectHashMap() { super(); } /** * Creates a new T#E#ObjectHashMap instance with a prime * capacity equal to or greater than initialCapacity and * with the default load factor. * * @param initialCapacity an int value */ public T#E#ObjectHashMap( int initialCapacity ) { super( initialCapacity ); no_entry_key = Constants.DEFAULT_#EC#_NO_ENTRY_VALUE; } /** * Creates a new T#E#ObjectHashMap instance with a prime * capacity equal to or greater than initialCapacity and * with the specified load factor. * * @param initialCapacity an int value * @param loadFactor a float value */ public T#E#ObjectHashMap( int initialCapacity, float loadFactor ) { super( initialCapacity, loadFactor ); no_entry_key = Constants.DEFAULT_#EC#_NO_ENTRY_VALUE; } /** * Creates a new T#E#ObjectHashMap instance with a prime * value at or near the specified capacity and load factor. * * @param initialCapacity used to find a prime capacity for the table. * @param loadFactor used to calculate the threshold over which * rehashing takes place. * @param noEntryKey the value used to represent null in the key set. */ public T#E#ObjectHashMap( int initialCapacity, float loadFactor, #e# noEntryKey ) { super( initialCapacity, loadFactor ); no_entry_key = noEntryKey; } /** * Creates a new T#E#ObjectHashMap that contains the entries * in the map passed to it. * * @param map the T#E#ObjectMap to be copied. */ public T#E#ObjectHashMap( T#E#ObjectMap map ) { this( map.size(), 0.5f, map.getNoEntryKey() ); putAll( map ); } /** {@inheritDoc} */ @SuppressWarnings({"unchecked"}) protected int setUp( int initialCapacity ) { int capacity; capacity = super.setUp( initialCapacity ); _values = ( V[] ) new Object[capacity]; return capacity; } /** {@inheritDoc} */ @SuppressWarnings({"unchecked"}) protected void rehash( int newCapacity ) { int oldCapacity = _set.length; #e# oldKeys[] = _set; V oldVals[] = _values; byte oldStates[] = _states; _set = new #e#[newCapacity]; _values = (V[]) new Object[newCapacity]; _states = new byte[newCapacity]; for ( int i = oldCapacity; i-- > 0; ) { if( oldStates[i] == FULL ) { #e# o = oldKeys[i]; int index = insertKey(o); _values[index] = oldVals[i]; } } } // Query Operations /** {@inheritDoc} */ public #e# getNoEntryKey() { return no_entry_key; } /** {@inheritDoc} */ public boolean containsKey( #e# key ) { return contains( key ); } /** {@inheritDoc} */ public boolean containsValue( Object val ) { byte[] states = _states; V[] vals = _values; // special case null values so that we don't have to // perform null checks before every call to equals() if ( null == val ) { for ( int i = vals.length; i-- > 0; ) { if ( states[i] == FULL && null == vals[i] ) { return true; } } } else { for ( int i = vals.length; i-- > 0; ) { if ( states[i] == FULL && ( val == vals[i] || val.equals( vals[i] ) ) ) { return true; } } } // end of else return false; } /** {@inheritDoc} */ public V get( #e# key ) { int index = index( key ); return index < 0 ? null : _values[index]; } // Modification Operations /** {@inheritDoc} */ public V put( #e# key, V value ) { int index = insertKey( key ); return doPut( value, index ); } /** {@inheritDoc} */ public V putIfAbsent( #e# key, V value ) { int index = insertKey( key ); if ( index < 0 ) return _values[-index - 1]; return doPut( value, index ); } @SuppressWarnings({"unchecked"}) private V doPut( V value, int index ) { V previous = null; boolean isNewMapping = true; if ( index < 0 ) { index = -index -1; previous = _values[index]; isNewMapping = false; } _values[index] = value; if (isNewMapping) { postInsertHook( consumeFreeSlot ); } return previous; } /** {@inheritDoc} */ public V remove( #e# key ) { V prev = null; int index = index( key ); if ( index >= 0 ) { prev = _values[index]; removeAt( index ); // clear key,state; adjust size } return prev; } /** {@inheritDoc} */ protected void removeAt( int index ) { _values[index] = null; super.removeAt( index ); // clear key, state; adjust size } // Bulk Operations /** {@inheritDoc} */ public void putAll( Map map ) { Set> set = map.entrySet(); for ( Map.Entry entry : set ) { put( entry.getKey(), entry.getValue() ); } } /** {@inheritDoc} */ public void putAll( T#E#ObjectMap map ){ map.forEachEntry( PUT_ALL_PROC ); } /** {@inheritDoc} */ public void clear() { super.clear(); Arrays.fill( _set, 0, _set.length, no_entry_key ); Arrays.fill( _states, 0, _states.length, FREE ); Arrays.fill( _values, 0, _values.length, null ); } // Views /** {@inheritDoc} */ public T#E#Set keySet() { return new KeyView(); } /** {@inheritDoc} */ @SuppressWarnings({"unchecked"}) public #e#[] keys() { #e#[] keys = new #e#[size()]; #e#[] k = _set; byte[] states = _states; for ( int i = k.length, j = 0; i-- > 0; ) { if ( states[i] == FULL ) { keys[j++] = k[i]; } } return keys; } /** {@inheritDoc} */ @SuppressWarnings({"unchecked"}) public #e#[] keys( #e#[] dest ) { if ( dest.length < _size ) { dest = new #e#[_size]; } #e#[] k = _set; byte[] states = _states; for ( int i = k.length, j = 0; i-- > 0; ) { if ( states[i] == FULL ) { dest[j++] = k[i]; } } return dest; } /** {@inheritDoc} */ public Collection valueCollection() { return new ValueView(); } /** {@inheritDoc} */ @SuppressWarnings({"unchecked"}) public Object[] values() { Object[] vals = new Object[size()]; V[] v = _values; byte[] states = _states; for ( int i = v.length, j = 0; i-- > 0; ) { if ( states[i] == FULL ) { vals[j++] = v[i]; } } return vals; } /** {@inheritDoc} */ @SuppressWarnings({"unchecked"}) public V[] values( V[] dest ) { if ( dest.length < _size ) { dest = ( V[] ) java.lang.reflect.Array.newInstance( dest.getClass().getComponentType(), _size); } V[] v = _values; byte[] states = _states; for ( int i = v.length, j = 0; i-- > 0; ) { if ( states[i] == FULL ) { dest[j++] = ( V ) v[i]; } } return dest; } /** {@inheritDoc} */ public T#E#ObjectIterator iterator() { return new T#E#ObjectHashIterator( this ); } /** {@inheritDoc} */ public boolean forEachKey( T#E#Procedure procedure ) { return forEach( procedure ); } /** {@inheritDoc} */ public boolean forEachValue( TObjectProcedure procedure ) { byte[] states = _states; V[] values = _values; for ( int i = values.length; i-- > 0; ) { if ( states[i] == FULL && ! procedure.execute( values[i] ) ) { return false; } } return true; } /** {@inheritDoc} */ @SuppressWarnings({"unchecked"}) public boolean forEachEntry( T#E#ObjectProcedure procedure ) { byte[] states = _states; #e#[] keys = _set; V[] values = _values; for (int i = keys.length; i-- > 0;) { if (states[i] == FULL && ! procedure.execute(keys[i],values[i])) { return false; } } return true; } /** {@inheritDoc} */ @SuppressWarnings({"unchecked"}) public boolean retainEntries( T#E#ObjectProcedure procedure ) { boolean modified = false; byte[] states = _states; #e#[] keys = _set; V[] values = _values; // Temporarily disable compaction. This is a fix for bug #1738760 tempDisableAutoCompaction(); try { for ( int i = keys.length; i-- > 0; ) { if ( states[i] == FULL && ! procedure.execute( keys[i], values[i] ) ) { removeAt( i ); modified = true; } } } finally { reenableAutoCompaction( true ); } return modified; } /** {@inheritDoc} */ public void transformValues( TObjectFunction function ) { byte[] states = _states; V[] values = _values; for ( int i = values.length; i-- > 0; ) { if ( states[i] == FULL ) { values[i] = function.execute( values[i] ); } } } // Comparison and hashing /** {@inheritDoc} */ public boolean equals( Object other ) { if ( ! ( other instanceof T#E#ObjectMap ) ) { return false; } T#E#ObjectMap that = ( T#E#ObjectMap ) other; if ( that.size() != this.size() ) { return false; } try { T#E#ObjectIterator iter = this.iterator(); while ( iter.hasNext() ) { iter.advance(); #e# key = iter.key(); Object value = iter.value(); if ( value == null ) { if ( !( that.get( key ) == null && that.containsKey( key ) ) ) { return false; } } else { if ( !value.equals( that.get( key ) ) ) { return false; } } } } catch ( ClassCastException ex ) { // unused. } return true; } /** {@inheritDoc} */ public int hashCode() { int hashcode = 0; V[] values = _values; byte[] states = _states; for ( int i = values.length; i-- > 0; ) { if ( states[i] == FULL ) { hashcode += HashFunctions.hash( _set[i] ) ^ ( values[i] == null ? 0 : values[i].hashCode() ); } } return hashcode; } class KeyView implements T#E#Set { /** {@inheritDoc} */ public #e# getNoEntryValue() { return no_entry_key; } /** {@inheritDoc} */ public int size() { return _size; } /** {@inheritDoc} */ public boolean isEmpty() { return _size == 0; } /** {@inheritDoc} */ public boolean contains( #e# entry ) { return T#E#ObjectHashMap.this.containsKey( entry ); } /** {@inheritDoc} */ public T#E#Iterator iterator() { return new T#E#HashIterator( T#E#ObjectHashMap.this ); } /** {@inheritDoc} */ public #e#[] toArray() { return keys(); } /** {@inheritDoc} */ public #e#[] toArray( #e#[] dest ) { return keys( dest ); } /** {@inheritDoc} */ public boolean add( #e# entry ) { throw new UnsupportedOperationException(); } /** {@inheritDoc} */ public boolean remove( #e# entry ) { return null != T#E#ObjectHashMap.this.remove( entry ); } /** {@inheritDoc} */ public boolean containsAll( Collection collection ) { for ( Object element : collection ) { if ( ! T#E#ObjectHashMap.this.containsKey( ( ( #ET# ) element ).#e#Value() ) ) { return false; } } return true; } /** {@inheritDoc} */ public boolean containsAll( T#E#Collection collection ) { if ( collection == this ) { return true; } T#E#Iterator iter = collection.iterator(); while ( iter.hasNext() ) { if ( ! T#E#ObjectHashMap.this.containsKey( iter.next() ) ) { return false; } } return true; } /** {@inheritDoc} */ public boolean containsAll( #e#[] array ) { for ( #e# element : array ) { if ( ! T#E#ObjectHashMap.this.containsKey( element ) ) { return false; } } return true; } /** {@inheritDoc} */ public boolean addAll( Collection collection ) { throw new UnsupportedOperationException(); } /** {@inheritDoc} */ public boolean addAll( T#E#Collection collection ) { throw new UnsupportedOperationException(); } /** {@inheritDoc} */ public boolean addAll( #e#[] array ) { throw new UnsupportedOperationException(); } /** {@inheritDoc} */ public boolean retainAll( Collection collection ) { boolean modified = false; T#E#Iterator iter = iterator(); while ( iter.hasNext() ) { //noinspection SuspiciousMethodCalls if ( ! collection.contains( #ET#.valueOf ( iter.next() ) ) ) { iter.remove(); modified = true; } } return modified; } /** {@inheritDoc} */ public boolean retainAll( T#E#Collection collection ) { if ( this == collection ) { return false; } boolean modified = false; T#E#Iterator iter = iterator(); while ( iter.hasNext() ) { if ( ! collection.contains( iter.next() ) ) { iter.remove(); modified = true; } } return modified; } /** {@inheritDoc} */ public boolean retainAll( #e#[] array ) { boolean changed = false; Arrays.sort( array ); #e#[] set = _set; byte[] states = _states; for ( int i = set.length; i-- > 0; ) { if ( states[i] == FULL && ( Arrays.binarySearch( array, set[i] ) < 0) ) { removeAt( i ); changed = true; } } return changed; } /** {@inheritDoc} */ public boolean removeAll( Collection collection ) { boolean changed = false; for ( Object element : collection ) { if ( element instanceof #ET# ) { #e# c = ( ( #ET# ) element ).#e#Value(); if ( remove( c ) ) { changed = true; } } } return changed; } /** {@inheritDoc} */ public boolean removeAll( T#E#Collection collection ) { if ( collection == this ) { clear(); return true; } boolean changed = false; T#E#Iterator iter = collection.iterator(); while ( iter.hasNext() ) { #e# element = iter.next(); if ( remove( element ) ) { changed = true; } } return changed; } /** {@inheritDoc} */ public boolean removeAll( #e#[] array ) { boolean changed = false; for ( int i = array.length; i-- > 0; ) { if ( remove(array[i]) ) { changed = true; } } return changed; } /** {@inheritDoc} */ public void clear() { T#E#ObjectHashMap.this.clear(); } /** {@inheritDoc} */ public boolean forEach( T#E#Procedure procedure ) { return T#E#ObjectHashMap.this.forEachKey( procedure ); } /** {@inheritDoc) */ public boolean equals( Object other ) { if (! ( other instanceof T#E#Set ) ) { return false; } final T#E#Set that = ( T#E#Set ) other; if ( that.size() != this.size() ) { return false; } for ( int i = _states.length; i-- > 0; ) { if ( _states[i] == FULL ) { if ( ! that.contains( _set[i] ) ) { return false; } } } return true; } /** {@inheritDoc} */ public int hashCode() { int hashcode = 0; for ( int i = _states.length; i-- > 0; ) { if ( _states[i] == FULL ) { hashcode += HashFunctions.hash( _set[i] ); } } return hashcode; } /** {@inheritDoc} */ public String toString() { final StringBuilder buf = new StringBuilder("{"); boolean first = true; for ( int i = _states.length; i-- > 0; ) { if ( _states[i] == FULL ) { if ( first ) first = false; else buf.append( "," ); buf.append( _set[i] ); } } return buf.toString(); } class T#E#HashIterator extends THashPrimitiveIterator implements T#E#Iterator { /** the collection on which the iterator operates */ private final T#E#Hash _hash; /** {@inheritDoc} */ public T#E#HashIterator( T#E#Hash hash ) { super( hash ); this._hash = hash; } /** {@inheritDoc} */ public #e# next() { moveToNextIndex(); return _hash._set[_index]; } } } /** a view onto the values of the map. */ protected class ValueView extends MapBackedView { @SuppressWarnings({"unchecked"}) public Iterator iterator() { return new T#E#ObjectValueHashIterator( T#E#ObjectHashMap.this ) { protected V objectAtIndex( int index ) { return _values[index]; } }; } public boolean containsElement( V value ) { return containsValue( value ); } public boolean removeElement( V value ) { V[] values = _values; byte[] states = _states; for ( int i = values.length; i-- > 0; ) { if ( states[i] == FULL ) { if ( value == values[i] || ( null != values[i] && values[i].equals( value ) ) ) { removeAt( i ); return true; } } } return false; } class T#E#ObjectValueHashIterator extends THashPrimitiveIterator implements Iterator { protected final T#E#ObjectHashMap _map; public T#E#ObjectValueHashIterator( T#E#ObjectHashMap map ) { super( map ); _map = map; } @SuppressWarnings("unchecked") protected V objectAtIndex( int index ) { byte[] states = _states; Object value = _map._values[index]; if ( states[index] != FULL ) { return null; } return ( V ) value; } /** {@inheritDoc} */ @SuppressWarnings("unchecked") public V next() { moveToNextIndex(); return ( V ) _map._values[_index]; } } } private abstract class MapBackedView extends AbstractSet implements Set, Iterable { public abstract Iterator iterator(); public abstract boolean removeElement( E key ); public abstract boolean containsElement( E key ); @SuppressWarnings({"unchecked"}) public boolean contains( Object key ) { return containsElement( (E) key ); } @SuppressWarnings({"unchecked"}) public boolean remove( Object o ) { return removeElement( (E) o ); } public void clear() { T#E#ObjectHashMap.this.clear(); } public boolean add( E obj ) { throw new UnsupportedOperationException(); } public int size() { return T#E#ObjectHashMap.this.size(); } public Object[] toArray() { Object[] result = new Object[size()]; Iterator e = iterator(); for ( int i = 0; e.hasNext(); i++ ) { result[i] = e.next(); } return result; } @SuppressWarnings({"unchecked"}) public T[] toArray( T[] a ) { int size = size(); if ( a.length < size ) { a = (T[]) java.lang.reflect.Array.newInstance( a.getClass().getComponentType(), size ); } Iterator it = iterator(); Object[] result = a; for ( int i = 0; i < size; i++ ) { result[i] = it.next(); } if ( a.length > size ) { a[size] = null; } return a; } public boolean isEmpty() { return T#E#ObjectHashMap.this.isEmpty(); } public boolean addAll( Collection collection ) { throw new UnsupportedOperationException(); } @SuppressWarnings({"SuspiciousMethodCalls"}) public boolean retainAll( Collection collection ) { boolean changed = false; Iterator i = iterator(); while ( i.hasNext() ) { if ( !collection.contains( i.next() ) ) { i.remove(); changed = true; } } return changed; } } class T#E#ObjectHashIterator extends THashPrimitiveIterator implements T#E#ObjectIterator { /** the collection being iterated over */ private final T#E#ObjectHashMap _map; /** * Creates an iterator over the specified map * * @param map map to iterate over. */ public T#E#ObjectHashIterator( T#E#ObjectHashMap map ) { super( map ); this._map = map; } /** {@inheritDoc} */ public void advance() { moveToNextIndex(); } /** {@inheritDoc} */ public #e# key() { return _map._set[_index]; } /** {@inheritDoc} */ public V value() { return _map._values[_index]; } /** {@inheritDoc} */ public V setValue( V val ) { V old = value(); _map._values[_index] = val; return old; } } public void writeExternal( ObjectOutput out ) throws IOException { // VERSION out.writeByte( 0 ); // SUPER super.writeExternal( out ); // NO_ENTRY_KEY out.write#E#( no_entry_key ); // NUMBER OF ENTRIES out.writeInt( _size ); // ENTRIES for ( int i = _states.length; i-- > 0; ) { if ( _states[i] == FULL ) { out.write#E#( _set[i] ); out.writeObject( _values[i] ); } } } @SuppressWarnings({"unchecked"}) public void readExternal( ObjectInput in ) throws IOException, ClassNotFoundException { // VERSION in.readByte(); // SUPER super.readExternal( in ); // NO_ENTRY_KEY no_entry_key = in.read#E#(); // NUMBER OF ENTRIES int size = in.readInt(); setUp( size ); // ENTRIES while (size-- > 0) { #e# key = in.read#E#(); V val = (V) in.readObject(); put(key, val); } } public String toString() { final StringBuilder buf = new StringBuilder("{"); forEachEntry(new T#E#ObjectProcedure() { private boolean first = true; public boolean execute(#e# key, Object value) { if ( first ) first = false; else buf.append( "," ); buf.append(key); buf.append("="); buf.append(value); return true; } }); buf.append("}"); return buf.toString(); } } // T#E#ObjectHashMap trove-3.0.3/templates/gnu/trove/map/hash/_K__V_HashMap.template0000644000175000017500000010737111763017634023404 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001, Eric D. Friedman All Rights Reserved. // Copyright (c) 2009, Rob Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.map.hash; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// import gnu.trove.map.T#K##V#Map; import gnu.trove.function.T#V#Function; import gnu.trove.procedure.*; import gnu.trove.set.*; import gnu.trove.iterator.*; import gnu.trove.iterator.hash.*; import gnu.trove.impl.hash.*; import gnu.trove.impl.HashFunctions; import gnu.trove.*; import java.io.*; import java.util.*; /** * An open addressed Map implementation for #k# keys and #v# values. * * @author Eric D. Friedman * @author Rob Eden * @author Jeff Randall * @version $Id: _K__V_HashMap.template,v 1.1.2.16 2010/03/02 04:09:50 robeden Exp $ */ public class T#K##V#HashMap extends T#K##V#Hash implements T#K##V#Map, Externalizable { static final long serialVersionUID = 1L; /** the values of the map */ protected transient #v#[] _values; /** * Creates a new T#K##V#HashMap instance with the default * capacity and load factor. */ public T#K##V#HashMap() { super(); } /** * Creates a new T#K##V#HashMap instance with a prime * capacity equal to or greater than initialCapacity and * with the default load factor. * * @param initialCapacity an int value */ public T#K##V#HashMap( int initialCapacity ) { super( initialCapacity ); } /** * Creates a new T#K##V#HashMap instance with a prime * capacity equal to or greater than initialCapacity and * with the specified load factor. * * @param initialCapacity an int value * @param loadFactor a float value */ public T#K##V#HashMap( int initialCapacity, float loadFactor ) { super( initialCapacity, loadFactor ); } /** * Creates a new T#K##V#HashMap instance with a prime * capacity equal to or greater than initialCapacity and * with the specified load factor. * * @param initialCapacity an int value * @param loadFactor a float value * @param noEntryKey a #k# value that represents * null for the Key set. * @param noEntryValue a #v# value that represents * null for the Value set. */ public T#K##V#HashMap( int initialCapacity, float loadFactor, #k# noEntryKey, #v# noEntryValue ) { super( initialCapacity, loadFactor, noEntryKey, noEntryValue ); } /** * Creates a new T#K##V#HashMap instance containing * all of the entries in the map passed in. * * @param keys a #k# array containing the keys for the matching values. * @param values a #v# array containing the values. */ public T#K##V#HashMap( #k#[] keys, #v#[] values ) { super( Math.max( keys.length, values.length ) ); int size = Math.min( keys.length, values.length ); for ( int i = 0; i < size; i++ ) { this.put( keys[i], values[i] ); } } /** * Creates a new T#K##V#HashMap instance containing * all of the entries in the map passed in. * * @param map a T#K##V#Map that will be duplicated. */ public T#K##V#HashMap( T#K##V#Map map ) { super( map.size() ); if ( map instanceof T#K##V#HashMap ) { T#K##V#HashMap hashmap = ( T#K##V#HashMap ) map; this._loadFactor = hashmap._loadFactor; this.no_entry_key = hashmap.no_entry_key; this.no_entry_value = hashmap.no_entry_value; //noinspection RedundantCast if ( this.no_entry_key != ( #k# ) 0 ) { Arrays.fill( _set, this.no_entry_key ); } //noinspection RedundantCast if ( this.no_entry_value != ( #v# ) 0 ) { Arrays.fill( _values, this.no_entry_value ); } setUp( (int) Math.ceil( DEFAULT_CAPACITY / _loadFactor ) ); } putAll( map ); } /** * initializes the hashtable to a prime capacity which is at least * initialCapacity + 1. * * @param initialCapacity an int value * @return the actual capacity chosen */ protected int setUp( int initialCapacity ) { int capacity; capacity = super.setUp( initialCapacity ); _values = new #v#[capacity]; return capacity; } /** * rehashes the map to the new capacity. * * @param newCapacity an int value */ /** {@inheritDoc} */ protected void rehash( int newCapacity ) { int oldCapacity = _set.length; #k# oldKeys[] = _set; #v# oldVals[] = _values; byte oldStates[] = _states; _set = new #k#[newCapacity]; _values = new #v#[newCapacity]; _states = new byte[newCapacity]; for ( int i = oldCapacity; i-- > 0; ) { if( oldStates[i] == FULL ) { #k# o = oldKeys[i]; int index = insertKey( o ); _values[index] = oldVals[i]; } } } /** {@inheritDoc} */ public #v# put( #k# key, #v# value ) { int index = insertKey( key ); return doPut( key, value, index ); } /** {@inheritDoc} */ public #v# putIfAbsent( #k# key, #v# value ) { int index = insertKey( key ); if (index < 0) return _values[-index - 1]; return doPut( key, value, index ); } private #v# doPut( #k# key, #v# value, int index ) { #v# previous = no_entry_value; boolean isNewMapping = true; if ( index < 0 ) { index = -index -1; previous = _values[index]; isNewMapping = false; } _values[index] = value; if (isNewMapping) { postInsertHook( consumeFreeSlot ); } return previous; } /** {@inheritDoc} */ public void putAll( Map map ) { ensureCapacity( map.size() ); // could optimize this for cases when map instanceof THashMap for ( Map.Entry entry : map.entrySet() ) { this.put( entry.getKey().#k#Value(), entry.getValue().#v#Value() ); } } /** {@inheritDoc} */ public void putAll( T#K##V#Map map ) { ensureCapacity( map.size() ); T#K##V#Iterator iter = map.iterator(); while ( iter.hasNext() ) { iter.advance(); this.put( iter.key(), iter.value() ); } } /** {@inheritDoc} */ public #v# get( #k# key ) { int index = index( key ); return index < 0 ? no_entry_value : _values[index]; } /** {@inheritDoc} */ public void clear() { super.clear(); Arrays.fill( _set, 0, _set.length, no_entry_key ); Arrays.fill( _values, 0, _values.length, no_entry_value ); Arrays.fill( _states, 0, _states.length, FREE ); } /** {@inheritDoc} */ public boolean isEmpty() { return 0 == _size; } /** {@inheritDoc} */ public #v# remove( #k# key ) { #v# prev = no_entry_value; int index = index( key ); if ( index >= 0 ) { prev = _values[index]; removeAt( index ); // clear key,state; adjust size } return prev; } /** {@inheritDoc} */ protected void removeAt( int index ) { _values[index] = no_entry_value; super.removeAt( index ); // clear key, state; adjust size } /** {@inheritDoc} */ public T#K#Set keySet() { return new TKeyView(); } /** {@inheritDoc} */ public #k#[] keys() { #k#[] keys = new #k#[size()]; #k#[] k = _set; byte[] states = _states; for ( int i = k.length, j = 0; i-- > 0; ) { if ( states[i] == FULL ) { keys[j++] = k[i]; } } return keys; } /** {@inheritDoc} */ public #k#[] keys( #k#[] array ) { int size = size(); if ( array.length < size ) { array = new #k#[size]; } #k#[] keys = _set; byte[] states = _states; for ( int i = keys.length, j = 0; i-- > 0; ) { if ( states[i] == FULL ) { array[j++] = keys[i]; } } return array; } /** {@inheritDoc} */ public T#V#Collection valueCollection() { return new TValueView(); } /** {@inheritDoc} */ public #v#[] values() { #v#[] vals = new #v#[size()]; #v#[] v = _values; byte[] states = _states; for ( int i = v.length, j = 0; i-- > 0; ) { if ( states[i] == FULL ) { vals[j++] = v[i]; } } return vals; } /** {@inheritDoc} */ public #v#[] values( #v#[] array ) { int size = size(); if ( array.length < size ) { array = new #v#[size]; } #v#[] v = _values; byte[] states = _states; for ( int i = v.length, j = 0; i-- > 0; ) { if ( states[i] == FULL ) { array[j++] = v[i]; } } return array; } /** {@inheritDoc} */ public boolean containsValue( #v# val ) { byte[] states = _states; #v#[] vals = _values; for ( int i = vals.length; i-- > 0; ) { if ( states[i] == FULL && val == vals[i] ) { return true; } } return false; } /** {@inheritDoc} */ public boolean containsKey( #k# key ) { return contains( key ); } /** {@inheritDoc} */ public T#K##V#Iterator iterator() { return new T#K##V#HashIterator( this ); } /** {@inheritDoc} */ public boolean forEachKey( T#K#Procedure procedure ) { return forEach( procedure ); } /** {@inheritDoc} */ public boolean forEachValue( T#V#Procedure procedure ) { byte[] states = _states; #v#[] values = _values; for ( int i = values.length; i-- > 0; ) { if ( states[i] == FULL && ! procedure.execute( values[i] ) ) { return false; } } return true; } /** {@inheritDoc} */ public boolean forEachEntry( T#K##V#Procedure procedure ) { byte[] states = _states; #k#[] keys = _set; #v#[] values = _values; for ( int i = keys.length; i-- > 0; ) { if ( states[i] == FULL && ! procedure.execute( keys[i], values[i] ) ) { return false; } } return true; } /** {@inheritDoc} */ public void transformValues( T#V#Function function ) { byte[] states = _states; #v#[] values = _values; for ( int i = values.length; i-- > 0; ) { if ( states[i] == FULL ) { values[i] = function.execute( values[i] ); } } } /** {@inheritDoc} */ public boolean retainEntries( T#K##V#Procedure procedure ) { boolean modified = false; byte[] states = _states; #k#[] keys = _set; #v#[] values = _values; // Temporarily disable compaction. This is a fix for bug #1738760 tempDisableAutoCompaction(); try { for ( int i = keys.length; i-- > 0; ) { if ( states[i] == FULL && ! procedure.execute( keys[i], values[i] ) ) { removeAt( i ); modified = true; } } } finally { reenableAutoCompaction( true ); } return modified; } /** {@inheritDoc} */ public boolean increment( #k# key ) { return adjustValue( key, ( #v# ) 1 ); } /** {@inheritDoc} */ public boolean adjustValue( #k# key, #v# amount ) { int index = index( key ); if (index < 0) { return false; } else { _values[index] += amount; return true; } } /** {@inheritDoc} */ public #v# adjustOrPutValue( #k# key, #v# adjust_amount, #v# put_amount ) { int index = insertKey( key ); final boolean isNewMapping; final #v# newValue; if ( index < 0 ) { index = -index -1; newValue = ( _values[index] += adjust_amount ); isNewMapping = false; } else { newValue = ( _values[index] = put_amount ); isNewMapping = true; } byte previousState = _states[index]; if ( isNewMapping ) { postInsertHook(consumeFreeSlot); } return newValue; } /** a view onto the keys of the map. */ protected class TKeyView implements T#K#Set { /** {@inheritDoc} */ public T#K#Iterator iterator() { return new T#K##V#KeyHashIterator( T#K##V#HashMap.this ); } /** {@inheritDoc} */ public #k# getNoEntryValue() { return no_entry_key; } /** {@inheritDoc} */ public int size() { return _size; } /** {@inheritDoc} */ public boolean isEmpty() { return 0 == _size; } /** {@inheritDoc} */ public boolean contains( #k# entry ) { return T#K##V#HashMap.this.contains( entry ); } /** {@inheritDoc} */ public #k#[] toArray() { return T#K##V#HashMap.this.keys(); } /** {@inheritDoc} */ public #k#[] toArray( #k#[] dest ) { return T#K##V#HashMap.this.keys( dest ); } /** * Unsupported when operating upon a Key Set view of a T#K##V#Map *

* {@inheritDoc} */ public boolean add( #k# entry ) { throw new UnsupportedOperationException(); } /** {@inheritDoc} */ public boolean remove( #k# entry ) { return no_entry_value != T#K##V#HashMap.this.remove( entry ); } /** {@inheritDoc} */ public boolean containsAll( Collection collection ) { for ( Object element : collection ) { if ( element instanceof #KT# ) { #k# ele = ( ( #KT# ) element ).#k#Value(); if ( ! T#K##V#HashMap.this.containsKey( ele ) ) { return false; } } else { return false; } } return true; } /** {@inheritDoc} */ public boolean containsAll( T#K#Collection collection ) { T#K#Iterator iter = collection.iterator(); while ( iter.hasNext() ) { if ( ! T#K##V#HashMap.this.containsKey( iter.next() ) ) { return false; } } return true; } /** {@inheritDoc} */ public boolean containsAll( #k#[] array ) { for ( #k# element : array ) { if ( ! T#K##V#HashMap.this.contains( element ) ) { return false; } } return true; } /** * Unsupported when operating upon a Key Set view of a T#K##V#Map *

* {@inheritDoc} */ public boolean addAll( Collection collection ) { throw new UnsupportedOperationException(); } /** * Unsupported when operating upon a Key Set view of a T#K##V#Map *

* {@inheritDoc} */ public boolean addAll( T#K#Collection collection ) { throw new UnsupportedOperationException(); } /** * Unsupported when operating upon a Key Set view of a T#K##V#Map *

* {@inheritDoc} */ public boolean addAll( #k#[] array ) { throw new UnsupportedOperationException(); } /** {@inheritDoc} */ @SuppressWarnings({"SuspiciousMethodCalls"}) public boolean retainAll( Collection collection ) { boolean modified = false; T#K#Iterator iter = iterator(); while ( iter.hasNext() ) { if ( ! collection.contains( #KT#.valueOf ( iter.next() ) ) ) { iter.remove(); modified = true; } } return modified; } /** {@inheritDoc} */ public boolean retainAll( T#K#Collection collection ) { if ( this == collection ) { return false; } boolean modified = false; T#K#Iterator iter = iterator(); while ( iter.hasNext() ) { if ( ! collection.contains( iter.next() ) ) { iter.remove(); modified = true; } } return modified; } /** {@inheritDoc} */ public boolean retainAll( #k#[] array ) { boolean changed = false; Arrays.sort( array ); #k#[] set = _set; byte[] states = _states; for ( int i = set.length; i-- > 0; ) { if ( states[i] == FULL && ( Arrays.binarySearch( array, set[i] ) < 0) ) { removeAt( i ); changed = true; } } return changed; } /** {@inheritDoc} */ public boolean removeAll( Collection collection ) { boolean changed = false; for ( Object element : collection ) { if ( element instanceof #KT# ) { #k# c = ( ( #KT# ) element ).#k#Value(); if ( remove( c ) ) { changed = true; } } } return changed; } /** {@inheritDoc} */ public boolean removeAll( T#K#Collection collection ) { if ( this == collection ) { clear(); return true; } boolean changed = false; T#K#Iterator iter = collection.iterator(); while ( iter.hasNext() ) { #k# element = iter.next(); if ( remove( element ) ) { changed = true; } } return changed; } /** {@inheritDoc} */ public boolean removeAll( #k#[] array ) { boolean changed = false; for ( int i = array.length; i-- > 0; ) { if ( remove( array[i] ) ) { changed = true; } } return changed; } /** {@inheritDoc} */ public void clear() { T#K##V#HashMap.this.clear(); } /** {@inheritDoc} */ public boolean forEach( T#K#Procedure procedure ) { return T#K##V#HashMap.this.forEachKey( procedure ); } @Override public boolean equals( Object other ) { if (! (other instanceof T#K#Set)) { return false; } final T#K#Set that = ( T#K#Set ) other; if ( that.size() != this.size() ) { return false; } for ( int i = _states.length; i-- > 0; ) { if ( _states[i] == FULL ) { if ( ! that.contains( _set[i] ) ) { return false; } } } return true; } @Override public int hashCode() { int hashcode = 0; for ( int i = _states.length; i-- > 0; ) { if ( _states[i] == FULL ) { hashcode += HashFunctions.hash( _set[i] ); } } return hashcode; } @Override public String toString() { final StringBuilder buf = new StringBuilder( "{" ); forEachKey( new T#K#Procedure() { private boolean first = true; public boolean execute( #k# key ) { if ( first ) { first = false; } else { buf.append( ", " ); } buf.append( key ); return true; } } ); buf.append( "}" ); return buf.toString(); } } /** a view onto the values of the map. */ protected class TValueView implements T#V#Collection { /** {@inheritDoc} */ public T#V#Iterator iterator() { return new T#K##V#ValueHashIterator( T#K##V#HashMap.this ); } /** {@inheritDoc} */ public #v# getNoEntryValue() { return no_entry_value; } /** {@inheritDoc} */ public int size() { return _size; } /** {@inheritDoc} */ public boolean isEmpty() { return 0 == _size; } /** {@inheritDoc} */ public boolean contains( #v# entry ) { return T#K##V#HashMap.this.containsValue( entry ); } /** {@inheritDoc} */ public #v#[] toArray() { return T#K##V#HashMap.this.values(); } /** {@inheritDoc} */ public #v#[] toArray( #v#[] dest ) { return T#K##V#HashMap.this.values( dest ); } public boolean add( #v# entry ) { throw new UnsupportedOperationException(); } /** {@inheritDoc} */ public boolean remove( #v# entry ) { #v#[] values = _values; #k#[] set = _set; for ( int i = values.length; i-- > 0; ) { if ( ( set[i] != FREE && set[i] != REMOVED ) && entry == values[i] ) { removeAt( i ); return true; } } return false; } /** {@inheritDoc} */ public boolean containsAll( Collection collection ) { for ( Object element : collection ) { if ( element instanceof #VT# ) { #v# ele = ( ( #VT# ) element ).#v#Value(); if ( ! T#K##V#HashMap.this.containsValue( ele ) ) { return false; } } else { return false; } } return true; } /** {@inheritDoc} */ public boolean containsAll( T#V#Collection collection ) { T#V#Iterator iter = collection.iterator(); while ( iter.hasNext() ) { if ( ! T#K##V#HashMap.this.containsValue( iter.next() ) ) { return false; } } return true; } /** {@inheritDoc} */ public boolean containsAll( #v#[] array ) { for ( #v# element : array ) { if ( ! T#K##V#HashMap.this.containsValue( element ) ) { return false; } } return true; } /** {@inheritDoc} */ public boolean addAll( Collection collection ) { throw new UnsupportedOperationException(); } /** {@inheritDoc} */ public boolean addAll( T#V#Collection collection ) { throw new UnsupportedOperationException(); } /** {@inheritDoc} */ public boolean addAll( #v#[] array ) { throw new UnsupportedOperationException(); } /** {@inheritDoc} */ @SuppressWarnings({"SuspiciousMethodCalls"}) public boolean retainAll( Collection collection ) { boolean modified = false; T#V#Iterator iter = iterator(); while ( iter.hasNext() ) { if ( ! collection.contains( #VT#.valueOf ( iter.next() ) ) ) { iter.remove(); modified = true; } } return modified; } /** {@inheritDoc} */ public boolean retainAll( T#V#Collection collection ) { if ( this == collection ) { return false; } boolean modified = false; T#V#Iterator iter = iterator(); while ( iter.hasNext() ) { if ( ! collection.contains( iter.next() ) ) { iter.remove(); modified = true; } } return modified; } /** {@inheritDoc} */ public boolean retainAll( #v#[] array ) { boolean changed = false; Arrays.sort( array ); #v#[] values = _values; byte[] states = _states; for ( int i = values.length; i-- > 0; ) { if ( states[i] == FULL && ( Arrays.binarySearch( array, values[i] ) < 0) ) { removeAt( i ); changed = true; } } return changed; } /** {@inheritDoc} */ public boolean removeAll( Collection collection ) { boolean changed = false; for ( Object element : collection ) { if ( element instanceof #VT# ) { #v# c = ( ( #VT# ) element ).#v#Value(); if ( remove( c ) ) { changed = true; } } } return changed; } /** {@inheritDoc} */ public boolean removeAll( T#V#Collection collection ) { if ( this == collection ) { clear(); return true; } boolean changed = false; T#V#Iterator iter = collection.iterator(); while ( iter.hasNext() ) { #v# element = iter.next(); if ( remove( element ) ) { changed = true; } } return changed; } /** {@inheritDoc} */ public boolean removeAll( #v#[] array ) { boolean changed = false; for ( int i = array.length; i-- > 0; ) { if ( remove( array[i] ) ) { changed = true; } } return changed; } /** {@inheritDoc} */ public void clear() { T#K##V#HashMap.this.clear(); } /** {@inheritDoc} */ public boolean forEach( T#V#Procedure procedure ) { return T#K##V#HashMap.this.forEachValue( procedure ); } /** {@inheritDoc} */ @Override public String toString() { final StringBuilder buf = new StringBuilder( "{" ); forEachValue( new T#V#Procedure() { private boolean first = true; public boolean execute( #v# value ) { if ( first ) { first = false; } else { buf.append( ", " ); } buf.append( value ); return true; } } ); buf.append( "}" ); return buf.toString(); } } class T#K##V#KeyHashIterator extends THashPrimitiveIterator implements T#K#Iterator { /** * Creates an iterator over the specified map * * @param hash the TPrimitiveHash we will be iterating over. */ T#K##V#KeyHashIterator( TPrimitiveHash hash ) { super( hash ); } /** {@inheritDoc} */ public #k# next() { moveToNextIndex(); return _set[_index]; } /** @{inheritDoc} */ public void remove() { if ( _expectedSize != _hash.size() ) { throw new ConcurrentModificationException(); } // Disable auto compaction during the remove. This is a workaround for bug 1642768. try { _hash.tempDisableAutoCompaction(); T#K##V#HashMap.this.removeAt( _index ); } finally { _hash.reenableAutoCompaction( false ); } _expectedSize--; } } class T#K##V#ValueHashIterator extends THashPrimitiveIterator implements T#V#Iterator { /** * Creates an iterator over the specified map * * @param hash the TPrimitiveHash we will be iterating over. */ T#K##V#ValueHashIterator( TPrimitiveHash hash ) { super( hash ); } /** {@inheritDoc} */ public #v# next() { moveToNextIndex(); return _values[_index]; } /** @{inheritDoc} */ public void remove() { if ( _expectedSize != _hash.size() ) { throw new ConcurrentModificationException(); } // Disable auto compaction during the remove. This is a workaround for bug 1642768. try { _hash.tempDisableAutoCompaction(); T#K##V#HashMap.this.removeAt( _index ); } finally { _hash.reenableAutoCompaction( false ); } _expectedSize--; } } class T#K##V#HashIterator extends THashPrimitiveIterator implements T#K##V#Iterator { /** * Creates an iterator over the specified map * * @param map the T#K##V#HashMap we will be iterating over. */ T#K##V#HashIterator( T#K##V#HashMap map ) { super( map ); } /** {@inheritDoc} */ public void advance() { moveToNextIndex(); } /** {@inheritDoc} */ public #k# key() { return _set[_index]; } /** {@inheritDoc} */ public #v# value() { return _values[_index]; } /** {@inheritDoc} */ public #v# setValue( #v# val ) { #v# old = value(); _values[_index] = val; return old; } /** @{inheritDoc} */ public void remove() { if ( _expectedSize != _hash.size() ) { throw new ConcurrentModificationException(); } // Disable auto compaction during the remove. This is a workaround for bug 1642768. try { _hash.tempDisableAutoCompaction(); T#K##V#HashMap.this.removeAt( _index ); } finally { _hash.reenableAutoCompaction( false ); } _expectedSize--; } } /** {@inheritDoc} */ @Override public boolean equals( Object other ) { if ( ! ( other instanceof T#K##V#Map ) ) { return false; } T#K##V#Map that = ( T#K##V#Map ) other; if ( that.size() != this.size() ) { return false; } #v#[] values = _values; byte[] states = _states; #v# this_no_entry_value = getNoEntryValue(); #v# that_no_entry_value = that.getNoEntryValue(); for ( int i = values.length; i-- > 0; ) { if ( states[i] == FULL ) { #k# key = _set[i]; #v# that_value = that.get( key ); #v# this_value = values[i]; if ( ( this_value != that_value ) && ( this_value != this_no_entry_value ) && ( that_value != that_no_entry_value ) ) { return false; } } } return true; } /** {@inheritDoc} */ @Override public int hashCode() { int hashcode = 0; byte[] states = _states; for ( int i = _values.length; i-- > 0; ) { if ( states[i] == FULL ) { hashcode += HashFunctions.hash( _set[i] ) ^ HashFunctions.hash( _values[i] ); } } return hashcode; } /** {@inheritDoc} */ @Override public String toString() { final StringBuilder buf = new StringBuilder( "{" ); forEachEntry( new T#K##V#Procedure() { private boolean first = true; public boolean execute( #k# key, #v# value ) { if ( first ) first = false; else buf.append( ", " ); buf.append(key); buf.append("="); buf.append(value); return true; } }); buf.append( "}" ); return buf.toString(); } /** {@inheritDoc} */ public void writeExternal(ObjectOutput out) throws IOException { // VERSION out.writeByte( 0 ); // SUPER super.writeExternal( out ); // NUMBER OF ENTRIES out.writeInt( _size ); // ENTRIES for ( int i = _states.length; i-- > 0; ) { if ( _states[i] == FULL ) { out.write#K#( _set[i] ); out.write#V#( _values[i] ); } } } /** {@inheritDoc} */ public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { // VERSION in.readByte(); // SUPER super.readExternal( in ); // NUMBER OF ENTRIES int size = in.readInt(); setUp( size ); // ENTRIES while (size-- > 0) { #k# key = in.read#K#(); #v# val = in.read#V#(); put(key, val); } } } // T#K##V#HashMap trove-3.0.3/templates/gnu/trove/map/hash/Object_E_HashMap.template0000644000175000017500000010242211763017634024071 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001, Eric D. Friedman All Rights Reserved. // Copyright (c) 2009, Rob Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.map.hash; import gnu.trove.impl.Constants; import gnu.trove.impl.HashFunctions; import gnu.trove.impl.hash.THash; import gnu.trove.impl.hash.TObjectHash; import gnu.trove.procedure.TObject#E#Procedure; import gnu.trove.procedure.TObjectProcedure; import gnu.trove.procedure.T#E#Procedure; import gnu.trove.iterator.TObject#E#Iterator; import gnu.trove.iterator.T#E#Iterator; import gnu.trove.iterator.hash.TObjectHashIterator; import gnu.trove.function.T#E#Function; import gnu.trove.map.TObject#E#Map; import gnu.trove.T#E#Collection; import java.io.*; import java.util.*; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// /** * An open addressed Map implementation for Object keys and #e# values. * * Created: Sun Nov 4 08:52:45 2001 * * @author Eric D. Friedman * @author Rob Eden * @author Jeff Randall */ public class TObject#E#HashMap extends TObjectHash implements TObject#E#Map, Externalizable { static final long serialVersionUID = 1L; private final TObject#E#Procedure PUT_ALL_PROC = new TObject#E#Procedure() { public boolean execute(K key, #e# value) { put(key, value); return true; } }; /** the values of the map */ protected transient #e#[] _values; /** the value that represents null */ protected #e# no_entry_value; /** * Creates a new TObject#E#HashMap instance with the default * capacity and load factor. */ public TObject#E#HashMap() { super(); no_entry_value = Constants.DEFAULT_#EC#_NO_ENTRY_VALUE; } /** * Creates a new TObject#E#HashMap instance with a prime * capacity equal to or greater than initialCapacity and * with the default load factor. * * @param initialCapacity an int value */ public TObject#E#HashMap( int initialCapacity ) { super( initialCapacity ); no_entry_value = Constants.DEFAULT_#EC#_NO_ENTRY_VALUE; } /** * Creates a new TObject#E#HashMap instance with a prime * capacity equal to or greater than initialCapacity and * with the specified load factor. * * @param initialCapacity an int value * @param loadFactor a float value */ public TObject#E#HashMap( int initialCapacity, float loadFactor ) { super( initialCapacity, loadFactor ); no_entry_value = Constants.DEFAULT_#EC#_NO_ENTRY_VALUE; } /** * Creates a new TObject#E#HashMap instance with a prime * value at or near the specified capacity and load factor. * * @param initialCapacity used to find a prime capacity for the table. * @param loadFactor used to calculate the threshold over which * rehashing takes place. * @param noEntryValue the value used to represent null. */ public TObject#E#HashMap( int initialCapacity, float loadFactor, #e# noEntryValue ) { super( initialCapacity, loadFactor ); no_entry_value = noEntryValue; //noinspection RedundantCast if ( no_entry_value != ( #e# ) 0 ) { Arrays.fill( _values, no_entry_value ); } } /** * Creates a new TObject#E#HashMap that contains the entries * in the map passed to it. * * @param map the TObject#E#Map to be copied. */ public TObject#E#HashMap( TObject#E#Map map ) { this( map.size(), 0.5f, map.getNoEntryValue() ); if ( map instanceof TObject#E#HashMap ) { TObject#E#HashMap hashmap = ( TObject#E#HashMap ) map; this._loadFactor = hashmap._loadFactor; this.no_entry_value = hashmap.no_entry_value; //noinspection RedundantCast if ( this.no_entry_value != ( #e# ) 0 ) { Arrays.fill( _values, this.no_entry_value ); } setUp( (int) Math.ceil( DEFAULT_CAPACITY / _loadFactor ) ); } putAll( map ); } /** * initializes the hashtable to a prime capacity which is at least * initialCapacity + 1. * * @param initialCapacity an int value * @return the actual capacity chosen */ public int setUp( int initialCapacity ) { int capacity; capacity = super.setUp( initialCapacity ); _values = new #e#[capacity]; return capacity; } /** * rehashes the map to the new capacity. * * @param newCapacity an int value */ protected void rehash( int newCapacity ) { int oldCapacity = _set.length; //noinspection unchecked K oldKeys[] = ( K[] ) _set; #e# oldVals[] = _values; _set = new Object[newCapacity]; Arrays.fill( _set, FREE ); _values = new #e#[newCapacity]; Arrays.fill( _values, no_entry_value ); for ( int i = oldCapacity; i-- > 0; ) { if( oldKeys[i] != FREE && oldKeys[i] != REMOVED ) { K o = oldKeys[i]; int index = insertKey(o); if ( index < 0 ) { throwObjectContractViolation( _set[ (-index -1) ], o); } _set[index] = o; _values[index] = oldVals[i]; } } } // Query Operations /** {@inheritDoc} */ public #e# getNoEntryValue() { return no_entry_value; } /** {@inheritDoc} */ public boolean containsKey( Object key ) { return contains( key ); } /** {@inheritDoc} */ public boolean containsValue( #e# val ) { Object[] keys = _set; #e#[] vals = _values; for ( int i = vals.length; i-- > 0; ) { if ( keys[i] != FREE && keys[i] != REMOVED && val == vals[i] ) { return true; } } return false; } /** {@inheritDoc} */ public #e# get( Object key ) { int index = index( key ); return index < 0 ? no_entry_value : _values[index]; } // Modification Operations /** {@inheritDoc} */ public #e# put( K key, #e# value ) { int index = insertKey( key ); return doPut( value, index ); } /** {@inheritDoc} */ public #e# putIfAbsent( K key, #e# value ) { int index = insertKey(key); if ( index < 0 ) return _values[-index - 1]; return doPut( value, index ); } private #e# doPut( #e# value, int index ) { #e# previous = no_entry_value; boolean isNewMapping = true; if ( index < 0 ) { index = -index -1; previous = _values[index]; isNewMapping = false; } //noinspection unchecked _values[index] = value; if ( isNewMapping ) { postInsertHook( consumeFreeSlot ); } return previous; } /** {@inheritDoc} */ public #e# remove( Object key ) { #e# prev = no_entry_value; int index = index(key); if ( index >= 0 ) { prev = _values[index]; removeAt( index ); // clear key,state; adjust size } return prev; } /** * Removes the mapping at index from the map. * This method is used internally and public mainly because * of packaging reasons. Caveat Programmer. * * @param index an int value */ protected void removeAt( int index ) { _values[index] = no_entry_value; super.removeAt( index ); // clear key, state; adjust size } // Bulk Operations /** {@inheritDoc} */ public void putAll( Map map ) { Set> set = map.entrySet(); for ( Map.Entry entry : set ) { put( entry.getKey(), entry.getValue() ); } } /** {@inheritDoc} */ public void putAll( TObject#E#Map map ){ map.forEachEntry( PUT_ALL_PROC ); } /** {@inheritDoc} */ public void clear() { super.clear(); Arrays.fill( _set, 0, _set.length, FREE ); Arrays.fill( _values, 0, _values.length, no_entry_value ); } // Views /** {@inheritDoc} */ public Set keySet() { return new KeyView(); } /** {@inheritDoc} */ public Object[] keys() { //noinspection unchecked K[] keys = ( K[] ) new Object[size()]; Object[] k = _set; for ( int i = k.length, j = 0; i-- > 0; ) { if ( k[i] != FREE && k[i] != REMOVED ) { //noinspection unchecked keys[j++] = ( K ) k[i]; } } return keys; } /** {@inheritDoc} */ public K[] keys( K[] a ) { int size = size(); if ( a.length < size ) { //noinspection unchecked a = ( K[] ) java.lang.reflect.Array.newInstance( a.getClass().getComponentType(), size ); } Object[] k = _set; for ( int i = k.length, j = 0; i-- > 0; ) { if ( k[i] != FREE && k[i] != REMOVED ) { //noinspection unchecked a[j++] = ( K ) k[i]; } } return a; } /** {@inheritDoc} */ public T#E#Collection valueCollection() { return new T#E#ValueCollection(); } /** {@inheritDoc} */ public #e#[] values() { #e#[] vals = new #e#[size()]; #e#[] v = _values; Object[] keys = _set; for ( int i = v.length, j = 0; i-- > 0; ) { if ( keys[i] != FREE && keys[i] != REMOVED ) { vals[j++] = v[i]; } } return vals; } /** {@inheritDoc} */ public #e#[] values( #e#[] array ) { int size = size(); if ( array.length < size ) { array = new #e#[size]; } #e#[] v = _values; Object[] keys = _set; for ( int i = v.length, j = 0; i-- > 0; ) { if ( keys[i] != FREE && keys[i] != REMOVED ) { array[j++] = v[i]; } } if ( array.length > size ) { array[size] = no_entry_value; } return array; } /** * @return an iterator over the entries in this map */ public TObject#E#Iterator iterator() { return new TObject#E#HashIterator( this ); } /** {@inheritDoc} */ @SuppressWarnings({"RedundantCast"}) public boolean increment( K key ) { //noinspection RedundantCast return adjustValue( key, (#e#)1 ); } /** {@inheritDoc} */ public boolean adjustValue( K key, #e# amount ) { int index = index(key); if ( index < 0 ) { return false; } else { _values[index] += amount; return true; } } /** {@inheritDoc} */ public #e# adjustOrPutValue( final K key, final #e# adjust_amount, final #e# put_amount ) { int index = insertKey( key ); final boolean isNewMapping; final #e# newValue; if ( index < 0 ) { index = -index -1; newValue = ( _values[index] += adjust_amount ); isNewMapping = false; } else { newValue = ( _values[index] = put_amount ); isNewMapping = true; } //noinspection unchecked if ( isNewMapping ) { postInsertHook( consumeFreeSlot ); } return newValue; } /** * Executes procedure for each key in the map. * * @param procedure a TObjectProcedure value * @return false if the loop over the keys terminated because * the procedure returned false for some key. */ public boolean forEachKey( TObjectProcedure procedure ) { return forEach( procedure ); } /** * Executes procedure for each value in the map. * * @param procedure a T#E#Procedure value * @return false if the loop over the values terminated because * the procedure returned false for some value. */ public boolean forEachValue( T#E#Procedure procedure ) { Object[] keys = _set; #e#[] values = _values; for ( int i = values.length; i-- > 0; ) { if ( keys[i] != FREE && keys[i] != REMOVED && ! procedure.execute( values[i] ) ) { return false; } } return true; } /** * Executes procedure for each key/value entry in the * map. * * @param procedure a TOObject#E#Procedure value * @return false if the loop over the entries terminated because * the procedure returned false for some entry. */ @SuppressWarnings({"unchecked"}) public boolean forEachEntry( TObject#E#Procedure procedure ) { Object[] keys = _set; #e#[] values = _values; for ( int i = keys.length; i-- > 0; ) { if ( keys[i] != FREE && keys[i] != REMOVED && ! procedure.execute( ( K ) keys[i], values[i] ) ) { return false; } } return true; } /** * Retains only those entries in the map for which the procedure * returns a true value. * * @param procedure determines which entries to keep * @return true if the map was modified. */ public boolean retainEntries( TObject#E#Procedure procedure ) { boolean modified = false; //noinspection unchecked K[] keys = ( K[] ) _set; #e#[] values = _values; // Temporarily disable compaction. This is a fix for bug #1738760 tempDisableAutoCompaction(); try { for ( int i = keys.length; i-- > 0; ) { if ( keys[i] != FREE && keys[i] != REMOVED && ! procedure.execute( keys[i], values[i] ) ) { removeAt(i); modified = true; } } } finally { reenableAutoCompaction( true ); } return modified; } /** * Transform the values in this map using function. * * @param function a T#E#Function value */ public void transformValues( T#E#Function function ) { Object[] keys = _set; #e#[] values = _values; for ( int i = values.length; i-- > 0; ) { if ( keys[i] != null && keys[i] != REMOVED ) { values[i] = function.execute( values[i] ); } } } // Comparison and hashing /** * Compares this map with another map for equality of their stored * entries. * * @param other an Object value * @return a boolean value */ public boolean equals( Object other ) { if ( ! ( other instanceof TObject#E#Map ) ) { return false; } TObject#E#Map that = ( TObject#E#Map ) other; if ( that.size() != this.size() ) { return false; } try { TObject#E#Iterator iter = this.iterator(); while ( iter.hasNext() ) { iter.advance(); Object key = iter.key(); #e# value = iter.value(); if ( value == no_entry_value ) { if ( !( that.get( key ) == that.getNoEntryValue() && that.containsKey( key ) ) ) { return false; } } else { if ( value != that.get( key ) ) { return false; } } } } catch ( ClassCastException ex ) { // unused. } return true; } /** {@inheritDoc} */ public int hashCode() { int hashcode = 0; Object[] keys = _set; #e#[] values = _values; for ( int i = values.length; i-- > 0; ) { if ( keys[i] != FREE && keys[i] != REMOVED ) { hashcode += HashFunctions.hash( values[i] ) ^ ( keys[i] == null ? 0 : keys[i].hashCode() ); } } return hashcode; } /** a view onto the keys of the map. */ protected class KeyView extends MapBackedView { @SuppressWarnings({"unchecked"}) public Iterator iterator() { return new TObjectHashIterator( TObject#E#HashMap.this ); } public boolean removeElement( K key ) { return no_entry_value != TObject#E#HashMap.this.remove( key ); } public boolean containsElement( K key ) { return TObject#E#HashMap.this.contains( key ); } } private abstract class MapBackedView extends AbstractSet implements Set, Iterable { public abstract boolean removeElement( E key ); public abstract boolean containsElement( E key ); @SuppressWarnings({"unchecked"}) public boolean contains( Object key ) { return containsElement( (E) key ); } @SuppressWarnings({"unchecked"}) public boolean remove( Object o ) { return removeElement( (E) o ); } public void clear() { TObject#E#HashMap.this.clear(); } public boolean add( E obj ) { throw new UnsupportedOperationException(); } public int size() { return TObject#E#HashMap.this.size(); } public Object[] toArray() { Object[] result = new Object[size()]; Iterator e = iterator(); for ( int i = 0; e.hasNext(); i++ ) { result[i] = e.next(); } return result; } public T[] toArray( T[] a ) { int size = size(); if ( a.length < size ) { //noinspection unchecked a = (T[]) java.lang.reflect.Array.newInstance( a.getClass().getComponentType(), size ); } Iterator it = iterator(); Object[] result = a; for ( int i = 0; i < size; i++ ) { result[i] = it.next(); } if ( a.length > size ) { a[size] = null; } return a; } public boolean isEmpty() { return TObject#E#HashMap.this.isEmpty(); } public boolean addAll( Collection collection ) { throw new UnsupportedOperationException(); } @SuppressWarnings({"SuspiciousMethodCalls"}) public boolean retainAll( Collection collection ) { boolean changed = false; Iterator i = iterator(); while ( i.hasNext() ) { if ( !collection.contains( i.next() ) ) { i.remove(); changed = true; } } return changed; } } class T#E#ValueCollection implements T#E#Collection { /** {@inheritDoc} */ public T#E#Iterator iterator() { return new TObject#E#ValueHashIterator(); } /** {@inheritDoc} */ public #e# getNoEntryValue() { return no_entry_value; } /** {@inheritDoc} */ public int size() { return _size; } /** {@inheritDoc} */ public boolean isEmpty() { return 0 == _size; } /** {@inheritDoc} */ public boolean contains( #e# entry ) { return TObject#E#HashMap.this.containsValue( entry ); } /** {@inheritDoc} */ public #e#[] toArray() { return TObject#E#HashMap.this.values(); } /** {@inheritDoc} */ public #e#[] toArray( #e#[] dest ) { return TObject#E#HashMap.this.values( dest ); } public boolean add( #e# entry ) { throw new UnsupportedOperationException(); } /** {@inheritDoc} */ public boolean remove( #e# entry ) { #e#[] values = _values; Object[] set = _set; for ( int i = values.length; i-- > 0; ) { if ( ( set[i] != FREE && set[i] != REMOVED ) && entry == values[i] ) { removeAt( i ); return true; } } return false; } /** {@inheritDoc} */ public boolean containsAll( Collection collection ) { for ( Object element : collection ) { if ( element instanceof #ET# ) { #e# ele = ( ( #ET# ) element ).#e#Value(); if ( ! TObject#E#HashMap.this.containsValue( ele ) ) { return false; } } else { return false; } } return true; } /** {@inheritDoc} */ public boolean containsAll( T#E#Collection collection ) { T#E#Iterator iter = collection.iterator(); while ( iter.hasNext() ) { if ( ! TObject#E#HashMap.this.containsValue( iter.next() ) ) { return false; } } return true; } /** {@inheritDoc} */ public boolean containsAll( #e#[] array ) { for ( #e# element : array ) { if ( ! TObject#E#HashMap.this.containsValue( element ) ) { return false; } } return true; } /** {@inheritDoc} */ public boolean addAll( Collection collection ) { throw new UnsupportedOperationException(); } /** {@inheritDoc} */ public boolean addAll( T#E#Collection collection ) { throw new UnsupportedOperationException(); } /** {@inheritDoc} */ public boolean addAll( #e#[] array ) { throw new UnsupportedOperationException(); } /** {@inheritDoc} */ @SuppressWarnings({"SuspiciousMethodCalls"}) public boolean retainAll( Collection collection ) { boolean modified = false; T#E#Iterator iter = iterator(); while ( iter.hasNext() ) { if ( ! collection.contains( #ET#.valueOf ( iter.next() ) ) ) { iter.remove(); modified = true; } } return modified; } /** {@inheritDoc} */ public boolean retainAll( T#E#Collection collection ) { if ( this == collection ) { return false; } boolean modified = false; T#E#Iterator iter = iterator(); while ( iter.hasNext() ) { if ( ! collection.contains( iter.next() ) ) { iter.remove(); modified = true; } } return modified; } /** {@inheritDoc} */ public boolean retainAll( #e#[] array ) { boolean changed = false; Arrays.sort( array ); #e#[] values = _values; Object[] set = _set; for ( int i = set.length; i-- > 0; ) { if ( set[i] != FREE && set[i] != REMOVED && ( Arrays.binarySearch( array, values[i] ) < 0) ) { removeAt( i ); changed = true; } } return changed; } /** {@inheritDoc} */ public boolean removeAll( Collection collection ) { boolean changed = false; for ( Object element : collection ) { if ( element instanceof #ET# ) { #e# c = ( ( #ET# ) element ).#e#Value(); if ( remove( c ) ) { changed = true; } } } return changed; } /** {@inheritDoc} */ public boolean removeAll( T#E#Collection collection ) { if ( this == collection ) { clear(); return true; } boolean changed = false; T#E#Iterator iter = collection.iterator(); while ( iter.hasNext() ) { #e# element = iter.next(); if ( remove( element ) ) { changed = true; } } return changed; } /** {@inheritDoc} */ public boolean removeAll( #e#[] array ) { boolean changed = false; for ( int i = array.length; i-- > 0; ) { if ( remove( array[i] ) ) { changed = true; } } return changed; } /** {@inheritDoc} */ public void clear() { TObject#E#HashMap.this.clear(); } /** {@inheritDoc} */ public boolean forEach( T#E#Procedure procedure ) { return TObject#E#HashMap.this.forEachValue( procedure ); } @Override public String toString() { final StringBuilder buf = new StringBuilder( "{" ); forEachValue( new T#E#Procedure() { private boolean first = true; public boolean execute( #e# value ) { if ( first ) { first = false; } else { buf.append( ", " ); } buf.append( value ); return true; } } ); buf.append( "}" ); return buf.toString(); } class TObject#E#ValueHashIterator implements T#E#Iterator { protected THash _hash = TObject#E#HashMap.this; /** * the number of elements this iterator believes are in the * data structure it accesses. */ protected int _expectedSize; /** the index used for iteration. */ protected int _index; /** Creates an iterator over the specified map */ TObject#E#ValueHashIterator() { _expectedSize = _hash.size(); _index = _hash.capacity(); } /** {@inheritDoc} */ public boolean hasNext() { return nextIndex() >= 0; } /** {@inheritDoc} */ public #e# next() { moveToNextIndex(); return _values[_index]; } /** @{inheritDoc} */ public void remove() { if ( _expectedSize != _hash.size() ) { throw new ConcurrentModificationException(); } // Disable auto compaction during the remove. This is a workaround for // bug 1642768. try { _hash.tempDisableAutoCompaction(); TObject#E#HashMap.this.removeAt( _index ); } finally { _hash.reenableAutoCompaction( false ); } _expectedSize--; } /** * Sets the internal index so that the `next' object * can be returned. */ protected final void moveToNextIndex() { // doing the assignment && < 0 in one line shaves // 3 opcodes... if ( ( _index = nextIndex() ) < 0 ) { throw new NoSuchElementException(); } } /** * Returns the index of the next value in the data structure * or a negative value if the iterator is exhausted. * * @return an int value * @throws ConcurrentModificationException * if the underlying * collection's size has been modified since the iterator was * created. */ protected final int nextIndex() { if ( _expectedSize != _hash.size() ) { throw new ConcurrentModificationException(); } Object[] set = TObject#E#HashMap.this._set; int i = _index; while ( i-- > 0 && ( set[i] == TObjectHash.FREE || set[i] == TObjectHash.REMOVED ) ) { // do nothing } return i; } } } class TObject#E#HashIterator extends TObjectHashIterator implements TObject#E#Iterator { /** the collection being iterated over */ private final TObject#E#HashMap _map; public TObject#E#HashIterator( TObject#E#HashMap map ) { super( map ); this._map = map; } /** {@inheritDoc} */ public void advance() { moveToNextIndex(); } /** {@inheritDoc} */ @SuppressWarnings({"unchecked"}) public K key() { return ( K ) _map._set[_index]; } /** {@inheritDoc} */ public #e# value() { return _map._values[_index]; } /** {@inheritDoc} */ public #e# setValue( #e# val ) { #e# old = value(); _map._values[_index] = val; return old; } } // Externalization public void writeExternal( ObjectOutput out ) throws IOException { // VERSION out.writeByte( 0 ); // SUPER super.writeExternal( out ); // NO_ENTRY_VALUE out.write#E#( no_entry_value ); // NUMBER OF ENTRIES out.writeInt( _size ); // ENTRIES for ( int i = _set.length; i-- > 0; ) { if ( _set[i] != REMOVED && _set[i] != FREE ) { out.writeObject( _set[i] ); out.write#E#( _values[i] ); } } } public void readExternal( ObjectInput in ) throws IOException, ClassNotFoundException { // VERSION in.readByte(); // SUPER super.readExternal( in ); // NO_ENTRY_VALUE no_entry_value = in.read#E#(); // NUMBER OF ENTRIES int size = in.readInt(); setUp( size ); // ENTRIES while (size-- > 0) { //noinspection unchecked K key = ( K ) in.readObject(); #e# val = in.read#E#(); put(key, val); } } /** {@inheritDoc} */ public String toString() { final StringBuilder buf = new StringBuilder("{"); forEachEntry( new TObject#E#Procedure() { private boolean first = true; public boolean execute( K key, #e# value ) { if ( first ) first = false; else buf.append( "," ); buf.append( key ).append( "=" ).append( value ); return true; } }); buf.append( "}" ); return buf.toString(); } } // TObject#E#HashMap trove-3.0.3/templates/gnu/trove/map/custom_hash/0000755000175000017500000000000012000515265020636 5ustar ericherichtrove-3.0.3/templates/gnu/trove/map/custom_hash/Object_E_CustomHashMap.template0000644000175000017500000010353711763017634026666 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001, Eric D. Friedman All Rights Reserved. // Copyright (c) 2009, Rob Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.map.custom_hash; import gnu.trove.T#E#Collection; import gnu.trove.function.T#E#Function; import gnu.trove.impl.Constants; import gnu.trove.impl.HashFunctions; import gnu.trove.impl.hash.TCustomObjectHash; import gnu.trove.impl.hash.THash; import gnu.trove.iterator.T#E#Iterator; import gnu.trove.iterator.TObject#E#Iterator; import gnu.trove.iterator.hash.TObjectHashIterator; import gnu.trove.map.TObject#E#Map; import gnu.trove.procedure.T#E#Procedure; import gnu.trove.procedure.TObject#E#Procedure; import gnu.trove.procedure.TObjectProcedure; import gnu.trove.strategy.HashingStrategy; import java.io.*; import java.util.*; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// /** * An open addressed Map implementation for Object keys and #e# values. * * @author Rob Eden */ public class TObject#E#CustomHashMap extends TCustomObjectHash implements TObject#E#Map, Externalizable { static final long serialVersionUID = 1L; private final TObject#E#Procedure PUT_ALL_PROC = new TObject#E#Procedure() { public boolean execute(K key, #e# value) { put(key, value); return true; } }; /** the values of the map */ protected transient #e#[] _values; /** the value that represents null */ protected #e# no_entry_value; /** FOR EXTERNALIZATION ONLY!!! */ public TObject#E#CustomHashMap() {} /** * Creates a new TObject#E#HashMap instance with the default * capacity and load factor. */ public TObject#E#CustomHashMap( HashingStrategy strategy ) { super( strategy ); no_entry_value = Constants.DEFAULT_#EC#_NO_ENTRY_VALUE; } /** * Creates a new TObject#E#HashMap instance with a prime * capacity equal to or greater than initialCapacity and * with the default load factor. * * @param initialCapacity an int value */ public TObject#E#CustomHashMap( HashingStrategy strategy, int initialCapacity ) { super( strategy, initialCapacity ); no_entry_value = Constants.DEFAULT_#EC#_NO_ENTRY_VALUE; } /** * Creates a new TObject#E#HashMap instance with a prime * capacity equal to or greater than initialCapacity and * with the specified load factor. * * @param initialCapacity an int value * @param loadFactor a float value */ public TObject#E#CustomHashMap( HashingStrategy strategy, int initialCapacity, float loadFactor ) { super( strategy, initialCapacity, loadFactor ); no_entry_value = Constants.DEFAULT_#EC#_NO_ENTRY_VALUE; } /** * Creates a new TObject#E#HashMap instance with a prime * value at or near the specified capacity and load factor. * * @param initialCapacity used to find a prime capacity for the table. * @param loadFactor used to calculate the threshold over which * rehashing takes place. * @param noEntryValue the value used to represent null. */ public TObject#E#CustomHashMap( HashingStrategy strategy, int initialCapacity, float loadFactor, #e# noEntryValue ) { super( strategy, initialCapacity, loadFactor ); no_entry_value = noEntryValue; //noinspection RedundantCast if ( no_entry_value != ( #e# ) 0 ) { Arrays.fill( _values, no_entry_value ); } } /** * Creates a new TObject#E#CustomHashMap that contains the entries * in the map passed to it. * * @param map the TObject#E#Map to be copied. */ public TObject#E#CustomHashMap( HashingStrategy strategy, TObject#E#Map map ) { this( strategy, map.size(), 0.5f, map.getNoEntryValue() ); if ( map instanceof TObject#E#CustomHashMap ) { TObject#E#CustomHashMap hashmap = ( TObject#E#CustomHashMap ) map; this._loadFactor = hashmap._loadFactor; this.no_entry_value = hashmap.no_entry_value; this.strategy = hashmap.strategy; //noinspection RedundantCast if ( this.no_entry_value != ( #e# ) 0 ) { Arrays.fill( _values, this.no_entry_value ); } setUp( (int) Math.ceil( DEFAULT_CAPACITY / _loadFactor ) ); } putAll( map ); } /** * initializes the hashtable to a prime capacity which is at least * initialCapacity + 1. * * @param initialCapacity an int value * @return the actual capacity chosen */ public int setUp( int initialCapacity ) { int capacity; capacity = super.setUp( initialCapacity ); _values = new #e#[capacity]; return capacity; } /** * rehashes the map to the new capacity. * * @param newCapacity an int value */ protected void rehash( int newCapacity ) { int oldCapacity = _set.length; //noinspection unchecked K oldKeys[] = ( K[] ) _set; #e# oldVals[] = _values; _set = new Object[newCapacity]; Arrays.fill( _set, FREE ); _values = new #e#[newCapacity]; Arrays.fill( _values, no_entry_value ); for ( int i = oldCapacity; i-- > 0; ) { K o = oldKeys[i]; if( o != FREE && o != REMOVED ) { int index = insertKey(o); if ( index < 0 ) { throwObjectContractViolation( _set[ (-index -1) ], o); } _values[index] = oldVals[i]; } } } // Query Operations /** {@inheritDoc} */ public #e# getNoEntryValue() { return no_entry_value; } /** {@inheritDoc} */ public boolean containsKey( Object key ) { return contains( key ); } /** {@inheritDoc} */ public boolean containsValue( #e# val ) { Object[] keys = _set; #e#[] vals = _values; for ( int i = vals.length; i-- > 0; ) { if ( keys[i] != FREE && keys[i] != REMOVED && val == vals[i] ) { return true; } } return false; } /** {@inheritDoc} */ public #e# get( Object key ) { int index = index( key ); return index < 0 ? no_entry_value : _values[index]; } // Modification Operations /** {@inheritDoc} */ public #e# put( K key, #e# value ) { int index = insertKey( key ); return doPut( value, index ); } /** {@inheritDoc} */ public #e# putIfAbsent( K key, #e# value ) { int index = insertKey(key); if ( index < 0 ) return _values[-index - 1]; return doPut( value, index ); } private #e# doPut( #e# value, int index ) { #e# previous = no_entry_value; boolean isNewMapping = true; if ( index < 0 ) { index = -index -1; previous = _values[index]; isNewMapping = false; } //noinspection unchecked _values[index] = value; if ( isNewMapping ) { postInsertHook( consumeFreeSlot ); } return previous; } /** {@inheritDoc} */ public #e# remove( Object key ) { #e# prev = no_entry_value; int index = index(key); if ( index >= 0 ) { prev = _values[index]; removeAt( index ); // clear key,state; adjust size } return prev; } /** * Removes the mapping at index from the map. * This method is used internally and public mainly because * of packaging reasons. Caveat Programmer. * * @param index an int value */ protected void removeAt( int index ) { _values[index] = no_entry_value; super.removeAt( index ); // clear key, state; adjust size } // Bulk Operations /** {@inheritDoc} */ public void putAll( Map map ) { Set> set = map.entrySet(); for ( Map.Entry entry : set ) { put( entry.getKey(), entry.getValue() ); } } /** {@inheritDoc} */ public void putAll( TObject#E#Map map ){ map.forEachEntry( PUT_ALL_PROC ); } /** {@inheritDoc} */ public void clear() { super.clear(); Arrays.fill( _set, 0, _set.length, FREE ); Arrays.fill( _values, 0, _values.length, no_entry_value ); } // Views /** {@inheritDoc} */ public Set keySet() { return new KeyView(); } /** {@inheritDoc} */ public Object[] keys() { //noinspection unchecked K[] keys = ( K[] ) new Object[size()]; Object[] k = _set; for ( int i = k.length, j = 0; i-- > 0; ) { if ( k[i] != FREE && k[i] != REMOVED ) { //noinspection unchecked keys[j++] = ( K ) k[i]; } } return keys; } /** {@inheritDoc} */ public K[] keys( K[] a ) { int size = size(); if ( a.length < size ) { //noinspection unchecked a = ( K[] ) java.lang.reflect.Array.newInstance( a.getClass().getComponentType(), size ); } Object[] k = _set; for ( int i = k.length, j = 0; i-- > 0; ) { if ( k[i] != FREE && k[i] != REMOVED ) { //noinspection unchecked a[j++] = ( K ) k[i]; } } return a; } /** {@inheritDoc} */ public T#E#Collection valueCollection() { return new T#E#ValueCollection(); } /** {@inheritDoc} */ public #e#[] values() { #e#[] vals = new #e#[size()]; #e#[] v = _values; Object[] keys = _set; for ( int i = v.length, j = 0; i-- > 0; ) { if ( keys[i] != FREE && keys[i] != REMOVED ) { vals[j++] = v[i]; } } return vals; } /** {@inheritDoc} */ public #e#[] values( #e#[] array ) { int size = size(); if ( array.length < size ) { array = new #e#[size]; } #e#[] v = _values; Object[] keys = _set; for ( int i = v.length, j = 0; i-- > 0; ) { if ( keys[i] != FREE && keys[i] != REMOVED ) { array[j++] = v[i]; } } if ( array.length > size ) { array[size] = no_entry_value; } return array; } /** * @return an iterator over the entries in this map */ public TObject#E#Iterator iterator() { return new TObject#E#HashIterator( this ); } /** {@inheritDoc} */ @SuppressWarnings({"RedundantCast"}) public boolean increment( K key ) { //noinspection RedundantCast return adjustValue( key, (#e#)1 ); } /** {@inheritDoc} */ public boolean adjustValue( K key, #e# amount ) { int index = index(key); if ( index < 0 ) { return false; } else { _values[index] += amount; return true; } } /** {@inheritDoc} */ public #e# adjustOrPutValue( final K key, final #e# adjust_amount, final #e# put_amount ) { int index = insertKey( key ); final boolean isNewMapping; final #e# newValue; if ( index < 0 ) { index = -index -1; newValue = ( _values[index] += adjust_amount ); isNewMapping = false; } else { newValue = ( _values[index] = put_amount ); isNewMapping = true; } //noinspection unchecked if ( isNewMapping ) { postInsertHook( consumeFreeSlot ); } return newValue; } /** * Executes procedure for each key in the map. * * @param procedure a TObjectProcedure value * @return false if the loop over the keys terminated because * the procedure returned false for some key. */ public boolean forEachKey( TObjectProcedure procedure ) { return forEach( procedure ); } /** * Executes procedure for each value in the map. * * @param procedure a T#E#Procedure value * @return false if the loop over the values terminated because * the procedure returned false for some value. */ public boolean forEachValue( T#E#Procedure procedure ) { Object[] keys = _set; #e#[] values = _values; for ( int i = values.length; i-- > 0; ) { if ( keys[i] != FREE && keys[i] != REMOVED && ! procedure.execute( values[i] ) ) { return false; } } return true; } /** * Executes procedure for each key/value entry in the * map. * * @param procedure a TOObject#E#Procedure value * @return false if the loop over the entries terminated because * the procedure returned false for some entry. */ @SuppressWarnings({"unchecked"}) public boolean forEachEntry( TObject#E#Procedure procedure ) { Object[] keys = _set; #e#[] values = _values; for ( int i = keys.length; i-- > 0; ) { if ( keys[i] != FREE && keys[i] != REMOVED && ! procedure.execute( ( K ) keys[i], values[i] ) ) { return false; } } return true; } /** * Retains only those entries in the map for which the procedure * returns a true value. * * @param procedure determines which entries to keep * @return true if the map was modified. */ public boolean retainEntries( TObject#E#Procedure procedure ) { boolean modified = false; //noinspection unchecked K[] keys = ( K[] ) _set; #e#[] values = _values; // Temporarily disable compaction. This is a fix for bug #1738760 tempDisableAutoCompaction(); try { for ( int i = keys.length; i-- > 0; ) { if ( keys[i] != FREE && keys[i] != REMOVED && ! procedure.execute( keys[i], values[i] ) ) { removeAt(i); modified = true; } } } finally { reenableAutoCompaction( true ); } return modified; } /** * Transform the values in this map using function. * * @param function a T#E#Function value */ public void transformValues( T#E#Function function ) { Object[] keys = _set; #e#[] values = _values; for ( int i = values.length; i-- > 0; ) { if ( keys[i] != null && keys[i] != REMOVED ) { values[i] = function.execute( values[i] ); } } } // Comparison and hashing /** * Compares this map with another map for equality of their stored * entries. * * @param other an Object value * @return a boolean value */ public boolean equals( Object other ) { if ( ! ( other instanceof TObject#E#Map ) ) { return false; } TObject#E#Map that = ( TObject#E#Map ) other; if ( that.size() != this.size() ) { return false; } try { TObject#E#Iterator iter = this.iterator(); while ( iter.hasNext() ) { iter.advance(); Object key = iter.key(); #e# value = iter.value(); if ( value == no_entry_value ) { if ( !( that.get( key ) == that.getNoEntryValue() && that.containsKey( key ) ) ) { return false; } } else { if ( value != that.get( key ) ) { return false; } } } } catch ( ClassCastException ex ) { // unused. } return true; } /** {@inheritDoc} */ public int hashCode() { int hashcode = 0; Object[] keys = _set; #e#[] values = _values; for ( int i = values.length; i-- > 0; ) { if ( keys[i] != FREE && keys[i] != REMOVED ) { hashcode += HashFunctions.hash( values[i] ) ^ ( keys[i] == null ? 0 : keys[i].hashCode() ); } } return hashcode; } /** a view onto the keys of the map. */ protected class KeyView extends MapBackedView { @SuppressWarnings({"unchecked"}) public Iterator iterator() { return new TObjectHashIterator( TObject#E#CustomHashMap.this ); } public boolean removeElement( K key ) { return no_entry_value != TObject#E#CustomHashMap.this.remove( key ); } public boolean containsElement( K key ) { return TObject#E#CustomHashMap.this.contains( key ); } } private abstract class MapBackedView extends AbstractSet implements Set, Iterable { public abstract boolean removeElement( E key ); public abstract boolean containsElement( E key ); @SuppressWarnings({"unchecked"}) public boolean contains( Object key ) { return containsElement( (E) key ); } @SuppressWarnings({"unchecked"}) public boolean remove( Object o ) { return removeElement( (E) o ); } public void clear() { TObject#E#CustomHashMap.this.clear(); } public boolean add( E obj ) { throw new UnsupportedOperationException(); } public int size() { return TObject#E#CustomHashMap.this.size(); } public Object[] toArray() { Object[] result = new Object[size()]; Iterator e = iterator(); for ( int i = 0; e.hasNext(); i++ ) { result[i] = e.next(); } return result; } public T[] toArray( T[] a ) { int size = size(); if ( a.length < size ) { //noinspection unchecked a = (T[]) java.lang.reflect.Array.newInstance( a.getClass().getComponentType(), size ); } Iterator it = iterator(); Object[] result = a; for ( int i = 0; i < size; i++ ) { result[i] = it.next(); } if ( a.length > size ) { a[size] = null; } return a; } public boolean isEmpty() { return TObject#E#CustomHashMap.this.isEmpty(); } public boolean addAll( Collection collection ) { throw new UnsupportedOperationException(); } @SuppressWarnings({"SuspiciousMethodCalls"}) public boolean retainAll( Collection collection ) { boolean changed = false; Iterator i = iterator(); while ( i.hasNext() ) { if ( !collection.contains( i.next() ) ) { i.remove(); changed = true; } } return changed; } } class T#E#ValueCollection implements T#E#Collection { /** {@inheritDoc} */ public T#E#Iterator iterator() { return new TObject#E#ValueHashIterator(); } /** {@inheritDoc} */ public #e# getNoEntryValue() { return no_entry_value; } /** {@inheritDoc} */ public int size() { return _size; } /** {@inheritDoc} */ public boolean isEmpty() { return 0 == _size; } /** {@inheritDoc} */ public boolean contains( #e# entry ) { return TObject#E#CustomHashMap.this.containsValue( entry ); } /** {@inheritDoc} */ public #e#[] toArray() { return TObject#E#CustomHashMap.this.values(); } /** {@inheritDoc} */ public #e#[] toArray( #e#[] dest ) { return TObject#E#CustomHashMap.this.values( dest ); } public boolean add( #e# entry ) { throw new UnsupportedOperationException(); } /** {@inheritDoc} */ public boolean remove( #e# entry ) { #e#[] values = _values; Object[] set = _set; for ( int i = values.length; i-- > 0; ) { if ( ( set[i] != FREE && set[i] != REMOVED ) && entry == values[i] ) { removeAt( i ); return true; } } return false; } /** {@inheritDoc} */ public boolean containsAll( Collection collection ) { for ( Object element : collection ) { if ( element instanceof #ET# ) { #e# ele = ( ( #ET# ) element ).#e#Value(); if ( ! TObject#E#CustomHashMap.this.containsValue( ele ) ) { return false; } } else { return false; } } return true; } /** {@inheritDoc} */ public boolean containsAll( T#E#Collection collection ) { T#E#Iterator iter = collection.iterator(); while ( iter.hasNext() ) { if ( ! TObject#E#CustomHashMap.this.containsValue( iter.next() ) ) { return false; } } return true; } /** {@inheritDoc} */ public boolean containsAll( #e#[] array ) { for ( #e# element : array ) { if ( ! TObject#E#CustomHashMap.this.containsValue( element ) ) { return false; } } return true; } /** {@inheritDoc} */ public boolean addAll( Collection collection ) { throw new UnsupportedOperationException(); } /** {@inheritDoc} */ public boolean addAll( T#E#Collection collection ) { throw new UnsupportedOperationException(); } /** {@inheritDoc} */ public boolean addAll( #e#[] array ) { throw new UnsupportedOperationException(); } /** {@inheritDoc} */ @SuppressWarnings({"SuspiciousMethodCalls"}) public boolean retainAll( Collection collection ) { boolean modified = false; T#E#Iterator iter = iterator(); while ( iter.hasNext() ) { if ( ! collection.contains( #ET#.valueOf ( iter.next() ) ) ) { iter.remove(); modified = true; } } return modified; } /** {@inheritDoc} */ public boolean retainAll( T#E#Collection collection ) { if ( this == collection ) { return false; } boolean modified = false; T#E#Iterator iter = iterator(); while ( iter.hasNext() ) { if ( ! collection.contains( iter.next() ) ) { iter.remove(); modified = true; } } return modified; } /** {@inheritDoc} */ public boolean retainAll( #e#[] array ) { boolean changed = false; Arrays.sort( array ); #e#[] values = _values; Object[] set = _set; for ( int i = set.length; i-- > 0; ) { if ( set[i] != FREE && set[i] != REMOVED && ( Arrays.binarySearch( array, values[i] ) < 0) ) { removeAt( i ); changed = true; } } return changed; } /** {@inheritDoc} */ public boolean removeAll( Collection collection ) { boolean changed = false; for ( Object element : collection ) { if ( element instanceof #ET# ) { #e# c = ( ( #ET# ) element ).#e#Value(); if ( remove( c ) ) { changed = true; } } } return changed; } /** {@inheritDoc} */ public boolean removeAll( T#E#Collection collection ) { if ( this == collection ) { clear(); return true; } boolean changed = false; T#E#Iterator iter = collection.iterator(); while ( iter.hasNext() ) { #e# element = iter.next(); if ( remove( element ) ) { changed = true; } } return changed; } /** {@inheritDoc} */ public boolean removeAll( #e#[] array ) { boolean changed = false; for ( int i = array.length; i-- > 0; ) { if ( remove( array[i] ) ) { changed = true; } } return changed; } /** {@inheritDoc} */ public void clear() { TObject#E#CustomHashMap.this.clear(); } /** {@inheritDoc} */ public boolean forEach( T#E#Procedure procedure ) { return TObject#E#CustomHashMap.this.forEachValue( procedure ); } @Override public String toString() { final StringBuilder buf = new StringBuilder( "{" ); forEachValue( new T#E#Procedure() { private boolean first = true; public boolean execute( #e# value ) { if ( first ) { first = false; } else { buf.append( ", " ); } buf.append( value ); return true; } } ); buf.append( "}" ); return buf.toString(); } class TObject#E#ValueHashIterator implements T#E#Iterator { protected THash _hash = TObject#E#CustomHashMap.this; /** * the number of elements this iterator believes are in the * data structure it accesses. */ protected int _expectedSize; /** the index used for iteration. */ protected int _index; /** Creates an iterator over the specified map */ TObject#E#ValueHashIterator() { _expectedSize = _hash.size(); _index = _hash.capacity(); } /** {@inheritDoc} */ public boolean hasNext() { return nextIndex() >= 0; } /** {@inheritDoc} */ public #e# next() { moveToNextIndex(); return _values[_index]; } /** @{inheritDoc} */ public void remove() { if ( _expectedSize != _hash.size() ) { throw new ConcurrentModificationException(); } // Disable auto compaction during the remove. This is a workaround for // bug 1642768. try { _hash.tempDisableAutoCompaction(); TObject#E#CustomHashMap.this.removeAt( _index ); } finally { _hash.reenableAutoCompaction( false ); } _expectedSize--; } /** * Sets the internal index so that the `next' object * can be returned. */ protected final void moveToNextIndex() { // doing the assignment && < 0 in one line shaves // 3 opcodes... if ( ( _index = nextIndex() ) < 0 ) { throw new NoSuchElementException(); } } /** * Returns the index of the next value in the data structure * or a negative value if the iterator is exhausted. * * @return an int value * @throws java.util.ConcurrentModificationException * if the underlying * collection's size has been modified since the iterator was * created. */ protected final int nextIndex() { if ( _expectedSize != _hash.size() ) { throw new ConcurrentModificationException(); } Object[] set = TObject#E#CustomHashMap.this._set; int i = _index; while ( i-- > 0 && ( set[i] == TCustomObjectHash.FREE || set[i] == TCustomObjectHash.REMOVED ) ) { ; } return i; } } } class TObject#E#HashIterator extends TObjectHashIterator implements TObject#E#Iterator { /** the collection being iterated over */ private final TObject#E#CustomHashMap _map; public TObject#E#HashIterator( TObject#E#CustomHashMap map ) { super( map ); this._map = map; } /** {@inheritDoc} */ public void advance() { moveToNextIndex(); } /** {@inheritDoc} */ @SuppressWarnings({"unchecked"}) public K key() { return ( K ) _map._set[_index]; } /** {@inheritDoc} */ public #e# value() { return _map._values[_index]; } /** {@inheritDoc} */ public #e# setValue( #e# val ) { #e# old = value(); _map._values[_index] = val; return old; } } // Externalization public void writeExternal( ObjectOutput out ) throws IOException { // VERSION out.writeByte( 0 ); // SUPER super.writeExternal( out ); // STRATEGY out.writeObject( strategy ); // NO_ENTRY_VALUE out.write#E#( no_entry_value ); // NUMBER OF ENTRIES out.writeInt( _size ); // ENTRIES for ( int i = _set.length; i-- > 0; ) { if ( _set[i] != REMOVED && _set[i] != FREE ) { out.writeObject( _set[i] ); out.write#E#( _values[i] ); } } } public void readExternal( ObjectInput in ) throws IOException, ClassNotFoundException { // VERSION in.readByte(); // SUPER super.readExternal( in ); // STRATEGY strategy = ( HashingStrategy ) in.readObject(); // NO_ENTRY_VALUE no_entry_value = in.read#E#(); // NUMBER OF ENTRIES int size = in.readInt(); setUp( size ); // ENTRIES while (size-- > 0) { //noinspection unchecked K key = ( K ) in.readObject(); #e# val = in.read#E#(); put(key, val); } } /** {@inheritDoc} */ public String toString() { final StringBuilder buf = new StringBuilder("{"); forEachEntry( new TObject#E#Procedure() { private boolean first = true; public boolean execute( K key, #e# value ) { if ( first ) first = false; else buf.append( "," ); buf.append( key ).append( "=" ).append( value ); return true; } }); buf.append( "}" ); return buf.toString(); } } trove-3.0.3/templates/gnu/trove/map/_E_ObjectMap.template0000644000175000017500000004213511763017634022346 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001, Eric D. Friedman All Rights Reserved. // Copyright (c) 2009, Rob Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.map; import gnu.trove.iterator.T#E#ObjectIterator; import gnu.trove.procedure.T#E#Procedure; import gnu.trove.procedure.TObjectProcedure; import gnu.trove.procedure.T#E#ObjectProcedure; import gnu.trove.function.TObjectFunction; import gnu.trove.set.T#E#Set; import java.util.Collection; import java.util.Map; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// /** * Interface for a primitive map of #e# keys and Object values. */ public interface T#E#ObjectMap { // Query Operations /** * Returns the value that represents null in the {@link #keySet()}. * The default value is generally zero, but can be changed during * construction of the collection. * * @return the value that represents a null value in this collection. */ #e# getNoEntryKey(); /** * Returns the number of key-value mappings in this map. If the * map contains more than Integer.MAX_VALUE elements, returns * Integer.MAX_VALUE. * * @return the number of key-value mappings in this map */ int size(); /** * Returns true if this map contains no key-value mappings. * * @return true if this map contains no key-value mappings */ boolean isEmpty(); /** * Returns true if this map contains a mapping for the specified * key. More formally, returns true if and only if * this map contains a mapping for a key k such that * key.equals(k). (There can be at most one such mapping.) * * @param key key whose presence in this map is to be tested * @return true if this map contains a mapping for the specified * key * @throws ClassCastException if the key is of an inappropriate type for * this map (optional) * @throws NullPointerException if the specified key is null and this map * does not permit null keys (optional) */ boolean containsKey( #e# key ); /** * Returns true if this map maps one or more keys to the * specified value. More formally, returns true if and only if * this map contains at least one mapping to a value v such that * (value==null ? v==null : value.equals(v)). This operation * will probably require time linear in the map size for most * implementations of the Map interface. * * @param value value whose presence in this map is to be tested * @return true if this map maps one or more keys to the * specified value * @throws ClassCastException if the value is of an inappropriate type for * this map (optional) * @throws NullPointerException if the specified value is null and this * map does not permit null values (optional) */ boolean containsValue( Object value ); /** * Returns the value to which the specified key is mapped, * or {@code null} if this map contains no mapping for the key. * *

More formally, if this map contains a mapping from a key * {@code k} to a value {@code v} such that {@code (key==null ? k==null : * key.equals(k))}, then this method returns {@code v}; otherwise * it returns {@code null}. (There can be at most one such mapping.) * *

If this map permits null values, then a return value of * {@code null} does not necessarily indicate that the map * contains no mapping for the key; it's also possible that the map * explicitly maps the key to {@code null}. The {@link #containsKey * containsKey} operation may be used to distinguish these two cases. * * @param key the key whose associated value is to be returned * @return the #e# value to which the specified key is mapped, or * {@code null} if this map contains no mapping for the key * @throws ClassCastException if the key is of an inappropriate type for * this map (optional) * @throws NullPointerException if the specified key is null and this map * does not permit null keys (optional) */ V get( #e# key ); // Modification Operations /** * Associates the specified value with the specified key in this map * (optional operation). If the map previously contained a mapping for * the key, the old value is replaced by the specified value. (A map * m is said to contain a mapping for a key k if and only * if {@link #containsKey(#e#) m.containsKey(k)} would return * true.) * * @param key key with which the specified value is to be associated * @param value an #e# value value to be associated with the specified key * @return the previous value associated with key, or * no_entry_value if there was no mapping for key. * (A no_entry_value return can also indicate that the map * previously associated null with key, * if the implementation supports null values.) * @throws UnsupportedOperationException if the put operation * is not supported by this map * @throws ClassCastException if the class of the specified key or value * prevents it from being stored in this map * @throws NullPointerException if the specified key or value is null * and this map does not permit null keys or values * @throws IllegalArgumentException if some property of the specified key * or value prevents it from being stored in this map * @see #getNoEntryKey() */ V put( #e# key, V value); /** * Inserts a key/value pair into the map if the specified key is not already * associated with a value. * * @param key key with which the specified value is to be associated * @param value an #e# value to be associated with the specified key * * @return the previous value associated with key, or null * if none was found. */ V putIfAbsent( #e# key, V value ); /** * Removes the mapping for a key from this map if it is present * (optional operation). More formally, if this map contains a mapping * from key k to value v such that * key.equals(k), that mapping * is removed. (The map can contain at most one such mapping.) * *

Returns the value to which this map previously associated the key, * or null if the map contained no mapping for the key. * *

If this map permits null values, then a return value of * null does not necessarily indicate that the map * contained no mapping for the key; it's also possible that the map * explicitly mapped the key to null. * *

The map will not contain a mapping for the specified key once the * call returns. * * @param key key whose mapping is to be removed from the map * @return the previous #e# value associated with key, or * null if there was no mapping for key. * @throws UnsupportedOperationException if the remove operation * is not supported by this map * @throws ClassCastException if the key is of an inappropriate type for * this map (optional) * @throws NullPointerException if the specified key is null and this * map does not permit null keys (optional) */ V remove( #e# key ); // Bulk Operations /** * Copies all of the mappings from the specified map to this map * (optional operation). The effect of this call is equivalent to that * of calling {@link #put(#e#,Object) put(k, v)} on this map once * for each mapping from key k to value v in the * specified map. The behavior of this operation is undefined if the * specified map is modified while the operation is in progress. * * @param m mappings to be stored in this map * @throws UnsupportedOperationException if the putAll operation * is not supported by this map * @throws ClassCastException if the class of a key or value in the * specified map prevents it from being stored in this map * @throws NullPointerException if the specified map is null, or if * this map does not permit null keys or values, and the * specified map contains null keys or values * @throws IllegalArgumentException if some property of a key or value in * the specified map prevents it from being stored in this map */ void putAll( Map m); /** * Put all the entries from the given map into this map. * * @param map The map from which entries will be obtained to put into this map. */ void putAll( T#E#ObjectMap map ); /** * Removes all of the mappings from this map (optional operation). * The map will be empty after this call returns. * * @throws UnsupportedOperationException if the clear operation * is not supported by this map */ void clear(); // Views /** * Returns a {@link T#E#Set} view of the keys contained in this map. * The set is backed by the map, so changes to the map are * reflected in the set, and vice-versa. If the map is modified * while an iteration over the set is in progress (except through * the iterator's own remove operation), the results of * the iteration are undefined. The set supports element removal, * which removes the corresponding mapping from the map, via the * Iterator.remove, Set.remove, * removeAll, retainAll, and clear * operations. It does not support the add or addAll * operations. * * @return a set view of the keys contained in this map */ T#E#Set keySet(); /** * Returns a copy of the keys of the map as an array. * Changes to the array of keys will not be reflected in the map * nor vice-versa. * * @return a copy of the keys of the map as an array. */ #e#[] keys(); /** * Returns a copy of the keys of the map as an array. * Changes to the array of keys will not be reflected in the map * nor vice-versa. * * @param array the array into which the elements of the list are to be stored, * if it is big enough; otherwise, a new array of the same type is * allocated for this purpose. * @return the keys of the map as an array. */ #e#[] keys( #e#[] array ); /** * Returns a {@link Collection} view of the values contained in this map. * The collection is backed by the map, so changes to the map are * reflected in the collection, and vice-versa. If the map is * modified while an iteration over the collection is in progress * (except through the iterator's own remove operation), * the results of the iteration are undefined. The collection * supports element removal, which removes the corresponding * mapping from the map, via the Iterator.remove, * Collection.remove, removeAll, * retainAll and clear operations. It does not * support the add or addAll operations. * * @return a collection view of the values contained in this map */ Collection valueCollection(); /** * Returns the values of the map as an Object array. Note that the array returned * is typed as an Object[] and may not be cast to a more specific type. See * {@link #values(V[])} for a version which allows specifically typed arrays. * Changes to the array of values will not be reflected in the map * nor vice-versa. * * @return the values of the map as an array of #e# values. */ Object[] values(); /** * Returns the values of the map using an existing array. * Changes to the array of values will not be reflected in the map * nor vice-versa. * * @param array the array into which the elements of the list are to be stored, * if it is big enough; otherwise, a new array of the same type is * allocated for this purpose. * @return the values of the map as an array of #e# values. */ V[] values( V[] array ); /** * Returns a T#E#ObjectIterator with access to this map's keys and values. * * @return a T#E#ObjectIterator with access to this map's keys and values. */ public T#E#ObjectIterator iterator(); /** * Executes procedure for each key in the map. * * @param procedure a TObjectProcedure value * @return false if the loop over the keys terminated because * the procedure returned false for some key. */ public boolean forEachKey( T#E#Procedure procedure ); /** * Executes procedure for each value in the map. * * @param procedure a TObjectProcedure value * @return false if the loop over the values terminated because * the procedure returned false for some value. */ public boolean forEachValue( TObjectProcedure procedure ); /** * Executes procedure for each key/value entry in the * map. * * @param procedure a T#E#ObjectProcedure value * @return false if the loop over the entries terminated because * the procedure returned false for some entry. */ public boolean forEachEntry( T#E#ObjectProcedure procedure ); /** * Transform the values in this map using function. * * @param function a TObjectFunction value */ public void transformValues( TObjectFunction function ); /** * Retains only those entries in the map for which the procedure * returns a true value. * * @param procedure determines which entries to keep * @return true if the map was modified. */ public boolean retainEntries( T#E#ObjectProcedure procedure ); // Comparison and hashing /** * Compares the specified object with this map for equality. Returns * true if the given object is also a map and the two maps * represent the same mappings. More formally, two maps m1 and * m2 represent the same mappings if * m1.entrySet().equals(m2.entrySet()). This ensures that the * equals method works properly across different implementations * of the Map interface. * * @param o object to be compared for equality with this map * @return true if the specified object is equal to this map */ boolean equals( Object o ); /** * Returns the hash code value for this map. The hash code of a map is * defined to be the sum of the hash codes of each entry in the map's * entrySet() view. This ensures that m1.equals(m2) * implies that m1.hashCode()==m2.hashCode() for any two maps * m1 and m2, as required by the general contract of * {@link Object#hashCode}. * * @return the hash code value for this map * @see Object#equals(Object) * @see #equals(Object) */ int hashCode(); }trove-3.0.3/templates/gnu/trove/decorator/0000755000175000017500000000000012000515265017526 5ustar ericherichtrove-3.0.3/templates/gnu/trove/decorator/Object_E_MapDecorator.template0000644000175000017500000002473711763017634025426 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2002, Eric D. Friedman All Rights Reserved. // Copyright (c) 2009, Robert D. Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.decorator; import gnu.trove.map.TObject#E#Map; import gnu.trove.iterator.TObject#E#Iterator; import java.io.*; import java.util.*; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// /** * Wrapper class to make a TObject#E#Map conform to the java.util.Map API. * This class simply decorates an underlying TObject#E#Map and translates the Object-based * APIs into their Trove primitive analogs. *

* Note that wrapping and unwrapping primitive values is extremely inefficient. If * possible, users of this class should override the appropriate methods in this class * and use a table of canonical values. *

* Created: Mon Sep 23 22:07:40 PDT 2002 * * @author Eric D. Friedman * @author Robert D. Eden * @author Jeff Randall */ public class TObject#E#MapDecorator extends AbstractMap implements Map, Externalizable, Cloneable { static final long serialVersionUID = 1L; /** * the wrapped primitive map */ protected TObject#E#Map _map; /** * FOR EXTERNALIZATION ONLY!! */ public TObject#E#MapDecorator() {} /** * Creates a wrapper that decorates the specified primitive map. * * @param map the TObject#E#Map to wrap. */ public TObject#E#MapDecorator( TObject#E#Map map ) { super(); this._map = map; } /** * Returns a reference to the map wrapped by this decorator. * * @return the wrapped TObject#E#Map instance. */ public TObject#E#Map getMap() { return _map; } /** * Inserts a key/value pair into the map. * * @param key an Object value * @param value an #ET# value * @return the previous value associated with key, * or Integer(0) if none was found. */ public #ET# put( K key, #ET# value ) { if ( value == null ) return wrapValue( _map.put( key, _map.getNoEntryValue() ) ); return wrapValue( _map.put( key, unwrapValue( value ) ) ); } /** * Retrieves the value for key * * @param key an Object value * @return the value of key or null if no such mapping exists. */ public #ET# get( Object key ) { #e# v = _map.get( key ); // There may be a false positive since primitive maps // cannot return null, so we have to do an extra // check here. if ( v == _map.getNoEntryValue() ) { return null; } else { return wrapValue( v ); } } /** * Empties the map. */ public void clear() { this._map.clear(); } /** * Deletes a key/value pair from the map. * * @param key an Object value * @return the removed value, or Integer(0) if it was not found in the map */ public #ET# remove( Object key ) { #e# v = _map.remove( key ); // There may be a false positive since primitive maps // cannot return null, so we have to do an extra // check here. if ( v == _map.getNoEntryValue() ) { return null; } else { return wrapValue( v ); } } /** * Returns a Set view on the entries of the map. * * @return a Set value */ public Set> entrySet() { return new AbstractSet>() { public int size() { return _map.size(); } public boolean isEmpty() { return TObject#E#MapDecorator.this.isEmpty(); } public boolean contains( Object o ) { if ( o instanceof Map.Entry ) { Object k = ( ( Map.Entry ) o ).getKey(); Object v = ( ( Map.Entry ) o ).getValue(); return TObject#E#MapDecorator.this.containsKey( k ) && TObject#E#MapDecorator.this.get( k ).equals( v ); } else { return false; } } public Iterator> iterator() { return new Iterator>() { private final TObject#E#Iterator it = _map.iterator(); public Map.Entry next() { it.advance(); final K key = it.key(); final #ET# v = wrapValue( it.value() ); return new Map.Entry() { private #ET# val = v; public boolean equals( Object o ) { return o instanceof Map.Entry && ( ( Map.Entry ) o ).getKey().equals( key ) && ( ( Map.Entry ) o ).getValue().equals( val ); } public K getKey() { return key; } public #ET# getValue() { return val; } public int hashCode() { return key.hashCode() + val.hashCode(); } public #ET# setValue( #ET# value ) { val = value; return put( key, value ); } }; } public boolean hasNext() { return it.hasNext(); } public void remove() { it.remove(); } }; } public boolean add( Map.Entry o ) { throw new UnsupportedOperationException(); } public boolean remove( Object o ) { boolean modified = false; if ( contains( o ) ) { //noinspection unchecked K key = ( ( Map.Entry ) o ).getKey(); _map.remove( key ); modified = true; } return modified; } public boolean addAll(Collection> c) { throw new UnsupportedOperationException(); } public void clear() { TObject#E#MapDecorator.this.clear(); } }; } /** * Checks for the presence of val in the values of the map. * * @param val an Object value * @return a boolean value */ public boolean containsValue( Object val ) { return val instanceof #ET# && _map.containsValue( unwrapValue( val ) ); } /** * Checks for the present of key in the keys of the map. * * @param key an Object value * @return a boolean value */ public boolean containsKey( Object key ) { return _map.containsKey( key ); } /** * Returns the number of entries in the map. * * @return the map's size. */ public int size() { return this._map.size(); } /** * Indicates whether map has any entries. * * @return true if the map is empty */ public boolean isEmpty() { return this._map.size() == 0; } /** * Copies the key/value mappings in map into this map. * Note that this will be a deep copy, as storage is by * primitive value. * * @param map a Map value */ public void putAll( Map map ) { Iterator> it = map.entrySet().iterator(); for ( int i = map.size(); i-- > 0; ) { Entry e = it.next(); this.put( e.getKey(), e.getValue() ); } } /** * Wraps a value * * @param k value in the underlying map * @return an Object representation of the value */ protected #ET# wrapValue( #e# k ) { return #ET#.valueOf( k ); } /** * Unwraps a value * * @param value wrapped value * @return an unwrapped representation of the value */ protected #e# unwrapValue( Object value ) { return ( ( #ET# ) value ).#e#Value(); } // Implements Externalizable public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { // VERSION in.readByte(); // MAP //noinspection unchecked _map = ( TObject#E#Map ) in.readObject(); } // Implements Externalizable public void writeExternal(ObjectOutput out) throws IOException { // VERSION out.writeByte( 0 ); // MAP out.writeObject( _map ); } } // TObject#E#MapDecorator trove-3.0.3/templates/gnu/trove/decorator/_E_ObjectMapDecorator.template0000644000175000017500000002510311763017634025412 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2002, Eric D. Friedman All Rights Reserved. // Copyright (c) 2009, Robert D. Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.decorator; import gnu.trove.map.T#E#ObjectMap; import gnu.trove.iterator.T#E#ObjectIterator; import java.io.*; import java.util.*; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// /** * Wrapper class to make a T#E#ObjectMap conform to the java.util.Map API. * This class simply decorates an underlying T#E#ObjectMap and translates the Object-based * APIs into their Trove primitive analogs. *

* Note that wrapping and unwrapping primitive values is extremely inefficient. If * possible, users of this class should override the appropriate methods in this class * and use a table of canonical values. *

* Created: Mon Sep 23 22:07:40 PDT 2002 * * @author Eric D. Friedman * @author Robert D. Eden * @author Jeff Randall */ public class T#E#ObjectMapDecorator extends AbstractMap<#ET#, V> implements Map<#ET#, V>, Externalizable, Cloneable { static final long serialVersionUID = 1L; /** the wrapped primitive map */ protected T#E#ObjectMap _map; /** * FOR EXTERNALIZATION ONLY!! */ public T#E#ObjectMapDecorator() {} /** * Creates a wrapper that decorates the specified primitive map. * * @param map the T#E#ObjectMap to wrap. */ public T#E#ObjectMapDecorator( T#E#ObjectMap map ) { super(); this._map = map; } /** * Returns a reference to the map wrapped by this decorator. * * @return the wrapped T#E#ObjectMap instance. */ public T#E#ObjectMap getMap() { return _map; } /** * Inserts a key/value pair into the map. * * @param key an #ET# value * @param value an Object value * @return the previous value associated with key, * or null if none was found. */ public V put( #ET# key, V value ) { #e# k; if ( key == null ) { k = _map.getNoEntryKey(); } else { k = unwrapKey( key ); } return _map.put( k, value ); } /** * Retrieves the value for key * * @param key an Object value * @return the value of key or null if no such mapping exists. */ public V get( Object key ) { #e# k; if ( key != null ) { if ( key instanceof #ET# ) { k = unwrapKey( ( #ET# ) key ); } else { return null; } } else { k = _map.getNoEntryKey(); } return _map.get( k ); } /** * Empties the map. */ public void clear() { this._map.clear(); } /** * Deletes a key/value pair from the map. * * @param key an Object value * @return the removed value, or Integer(0) if it was not found in the map */ public V remove( Object key ) { #e# k; if ( key != null ) { if ( key instanceof #ET# ) { k = unwrapKey( ( #ET# ) key ); } else { return null; } } else { k = _map.getNoEntryKey(); } return _map.remove( k ); } /** * Returns a Set view on the entries of the map. * * @return a Set value */ public Set> entrySet() { return new AbstractSet>() { public int size() { return _map.size(); } public boolean isEmpty() { return T#E#ObjectMapDecorator.this.isEmpty(); } public boolean contains( Object o ) { if ( o instanceof Map.Entry ) { Object k = ( ( Map.Entry ) o ).getKey(); Object v = ( ( Map.Entry ) o ).getValue(); return T#E#ObjectMapDecorator.this.containsKey( k ) && T#E#ObjectMapDecorator.this.get( k ).equals( v ); } else { return false; } } public Iterator> iterator() { return new Iterator>() { private final T#E#ObjectIterator it = _map.iterator(); public Map.Entry<#ET#,V> next() { it.advance(); #e# k = it.key(); final #ET# key = (k == _map.getNoEntryKey()) ? null : wrapKey( k ); final V v = it.value(); return new Map.Entry<#ET#,V>() { private V val = v; public boolean equals( Object o ) { return o instanceof Map.Entry && ( ( Map.Entry ) o ).getKey().equals( key ) && ( ( Map.Entry ) o ).getValue().equals( val ); } public #ET# getKey() { return key; } public V getValue() { return val; } public int hashCode() { return key.hashCode() + val.hashCode(); } public V setValue( V value ) { val = value; return put( key, value ); } }; } public boolean hasNext() { return it.hasNext(); } public void remove() { it.remove(); } }; } public boolean add( Map.Entry<#ET#,V> o ) { throw new UnsupportedOperationException(); } public boolean remove( Object o ) { boolean modified = false; if ( contains( o ) ) { //noinspection unchecked #ET# key = ( ( Map.Entry<#ET#,V> ) o ).getKey(); _map.remove( unwrapKey( key ) ); modified = true; } return modified; } public boolean addAll( Collection> c ) { throw new UnsupportedOperationException(); } public void clear() { T#E#ObjectMapDecorator.this.clear(); } }; } /** * Checks for the presence of val in the values of the map. * * @param val an Object value * @return a boolean value */ public boolean containsValue( Object val ) { return _map.containsValue( val ); } /** * Checks for the present of key in the keys of the map. * * @param key an Object value * @return a boolean value */ public boolean containsKey( Object key ) { if ( key == null ) return _map.containsKey( _map.getNoEntryKey() ); return key instanceof #ET# && _map.containsKey( ( ( #ET# ) key ).#e#Value() ); } /** * Returns the number of entries in the map. * * @return the map's size. */ public int size() { return this._map.size(); } /** * Indicates whether map has any entries. * * @return true if the map is empty */ public boolean isEmpty() { return size() == 0; } /** * Copies the key/value mappings in map into this map. * Note that this will be a deep copy, as storage is by * primitive value. * * @param map a Map value */ public void putAll( Map map ) { Iterator> it = map.entrySet().iterator(); for ( int i = map.size(); i-- > 0; ) { Entry e = it.next(); this.put( e.getKey(), e.getValue() ); } } /** * Wraps a key * * @param k key in the underlying map * @return an Object representation of the key */ protected #ET# wrapKey( #e# k ) { return #ET#.valueOf( k ); } /** * Unwraps a key * * @param key wrapped key * @return an unwrapped representation of the key */ protected #e# unwrapKey( #ET# key ) { return key.#e#Value(); } // Implements Externalizable public void readExternal( ObjectInput in ) throws IOException, ClassNotFoundException { // VERSION in.readByte(); // MAP //noinspection unchecked _map = ( T#E#ObjectMap ) in.readObject(); } // Implements Externalizable public void writeExternal( ObjectOutput out ) throws IOException { // VERSION out.writeByte( 0 ); // MAP out.writeObject( _map ); } } // T#E#ObjectHashMapDecorator trove-3.0.3/templates/gnu/trove/decorator/_E_SetDecorator.template0000644000175000017500000001460711763017634024310 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2002, Eric D. Friedman All Rights Reserved. // Copyright (c) 2009, Robert D. Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.decorator; import gnu.trove.set.T#E#Set; import gnu.trove.iterator.T#E#Iterator; import java.io.*; import java.util.AbstractSet; import java.util.Iterator; import java.util.Set; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// /** * Wrapper class to make a T#E#Set conform to the java.util.Set API. * This class simply decorates an underlying T#E#Set and translates the Object-based * APIs into their Trove primitive analogs. *

*

* Note that wrapping and unwrapping primitive values is extremely inefficient. If * possible, users of this class should override the appropriate methods in this class * and use a table of canonical values. *

*

* Created: Tue Sep 24 22:08:17 PDT 2002 * * @author Eric D. Friedman * @author Robert D. Eden * @author Jeff Randall */ public class T#E#SetDecorator extends AbstractSet<#ET#> implements Set<#ET#>, Externalizable { static final long serialVersionUID = 1L; /** the wrapped primitive set */ protected T#E#Set _set; /** * FOR EXTERNALIZATION ONLY!! */ public T#E#SetDecorator() {} /** * Creates a wrapper that decorates the specified primitive set. * * @param set the T#E#Set to wrap. */ public T#E#SetDecorator( T#E#Set set ) { super(); this._set = set; } /** * Returns a reference to the set wrapped by this decorator. * * @return the wrapped T#E#Set instance. */ public T#E#Set getSet() { return _set; } /** * Inserts a value into the set. * * @param value true if the set was modified by the insertion */ public boolean add( #ET# value ) { return value != null && _set.add( value.#e#Value() ); } /** * Compares this set with another set for equality of their stored * entries. * * @param other an Object value * @return true if the sets are identical */ public boolean equals( Object other ) { if ( _set.equals( other ) ) { return true; // comparing two trove sets } else if ( other instanceof Set ) { Set that = ( Set ) other; if ( that.size() != _set.size() ) { return false; // different sizes, no need to compare } else { // now we have to do it the hard way Iterator it = that.iterator(); for ( int i = that.size(); i-- > 0; ) { Object val = it.next(); if ( val instanceof #ET# ) { #e# v = ( ( #ET# ) val ).#e#Value(); if ( _set.contains( v ) ) { // match, ok to continue } else { return false; // no match: we're done } } else { return false; // different type in other set } } return true; // all entries match } } else { return false; } } /** * Empties the set. */ public void clear() { this._set.clear(); } /** * Deletes a value from the set. * * @param value an Object value * @return true if the set was modified */ public boolean remove( Object value ) { return value instanceof #ET# && _set.remove( ( ( #ET# ) value ).#e#Value() ); } /** * Creates an iterator over the values of the set. * * @return an iterator with support for removals in the underlying set */ public Iterator<#ET#> iterator() { return new Iterator<#ET#>() { private final T#E#Iterator it = _set.iterator(); public #ET# next() { return #ET#.valueOf( it.next() ); } public boolean hasNext() { return it.hasNext(); } public void remove() { it.remove(); } }; } /** * Returns the number of entries in the set. * * @return the set's size. */ public int size() { return this._set.size(); } /** * Indicates whether set has any entries. * * @return true if the set is empty */ public boolean isEmpty() { return this._set.size() == 0; } /** * {@inheritDoc} */ @Override public boolean contains( Object o ) { if ( ! ( o instanceof #ET# ) ) return false; return _set.contains( ( ( #ET# ) o ).#e#Value() ); } // Implements Externalizable public void readExternal( ObjectInput in ) throws IOException, ClassNotFoundException { // VERSION in.readByte(); // SET _set = ( T#E#Set ) in.readObject(); } // Implements Externalizable public void writeExternal( ObjectOutput out ) throws IOException { // VERSION out.writeByte( 0 ); // SET out.writeObject( _set ); } } // T#E#HashSetDecorator trove-3.0.3/templates/gnu/trove/decorator/_E_ListDecorator.template0000644000175000017500000000752011763017634024464 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2009, Robert D. Eden All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.decorator; import gnu.trove.list.T#E#List; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.AbstractList; import java.util.List; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// /** * Wrapper class to make a T#E#List conform to the java.util.List API. * This class simply decorates an underlying T#E#List and translates the Object-based * APIs into their Trove primitive analogs. *

* Note that wrapping and unwrapping primitive values is extremely inefficient. If * possible, users of this class should override the appropriate methods in this class * and use a table of canonical values. *

* * @author Robert D. Eden */ public class T#E#ListDecorator extends AbstractList<#ET#> implements List<#ET#>, Externalizable, Cloneable { static final long serialVersionUID = 1L; /** the wrapped primitive list */ protected T#E#List list; /** * FOR EXTERNALIZATION ONLY!! */ public T#E#ListDecorator() {} /** * Creates a wrapper that decorates the specified primitive map. * * @param list the T#E#List to wrap. */ public T#E#ListDecorator( T#E#List list ) { super(); this.list = list; } /** * Returns a reference to the list wrapped by this decorator. * * @return the wrapped T#E#List instance. */ public T#E#List getList() { return list; } @Override public int size() { return list.size(); } @Override public #ET# get( int index ) { #e# value = list.get( index ); if ( value == list.getNoEntryValue() ) return null; else return #ET#.valueOf( value ); } @Override public #ET# set( int index, #ET# value ) { #e# previous_value = list.set( index, value ); if ( previous_value == list.getNoEntryValue() ) return null; else return #ET#.valueOf( previous_value ); } @Override public void add( int index, #ET# value ) { list.insert( index, value.#e#Value() ); } @Override public #ET# remove( int index ) { #e# previous_value = list.removeAt( index ); if ( previous_value == list.getNoEntryValue() ) return null; else return #ET#.valueOf( previous_value ); } // Implements Externalizable public void readExternal( ObjectInput in ) throws IOException, ClassNotFoundException { // VERSION in.readByte(); // LIST list = ( T#E#List ) in.readObject(); } // Implements Externalizable public void writeExternal( ObjectOutput out ) throws IOException { // VERSION out.writeByte(0); // LIST out.writeObject( list ); } } trove-3.0.3/templates/gnu/trove/decorator/_K__V_MapDecorator.template0000644000175000017500000002767311763017634024733 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2002, Eric D. Friedman All Rights Reserved. // Copyright (c) 2009, Robert D. Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.decorator; import gnu.trove.map.T#K##V#Map; import gnu.trove.iterator.T#K##V#Iterator; import java.io.*; import java.util.*; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// /** * Wrapper class to make a T#K##V#Map conform to the java.util.Map API. * This class simply decorates an underlying T#K##V#Map and translates the Object-based * APIs into their Trove primitive analogs. *

* Note that wrapping and unwrapping primitive values is extremely inefficient. If * possible, users of this class should override the appropriate methods in this class * and use a table of canonical values. *

* Created: Mon Sep 23 22:07:40 PDT 2002 * * @author Eric D. Friedman * @author Robert D. Eden * @author Jeff Randall */ public class T#K##V#MapDecorator extends AbstractMap<#KT#, #VT#> implements Map<#KT#, #VT#>, Externalizable, Cloneable { static final long serialVersionUID = 1L; /** the wrapped primitive map */ protected T#K##V#Map _map; /** * FOR EXTERNALIZATION ONLY!! */ public T#K##V#MapDecorator() {} /** * Creates a wrapper that decorates the specified primitive map. * * @param map the T#K##V#Map to wrap. */ public T#K##V#MapDecorator( T#K##V#Map map ) { super(); this._map = map; } /** * Returns a reference to the map wrapped by this decorator. * * @return the wrapped T#K##V#Map instance. */ public T#K##V#Map getMap() { return _map; } /** * Inserts a key/value pair into the map. * * @param key an Object value * @param value an Object value * @return the previous value associated with key, * or #VT#(0) if none was found. */ public #VT# put( #KT# key, #VT# value ) { #k# k; #v# v; if ( key == null ) { k = _map.getNoEntryKey(); } else { k = unwrapKey( key ); } if ( value == null ) { v = _map.getNoEntryValue(); } else { v = unwrapValue( value ); } #v# retval = _map.put( k, v ); if ( retval == _map.getNoEntryValue() ) { return null; } return wrapValue( retval ); } /** * Retrieves the value for key * * @param key an Object value * @return the value of key or null if no such mapping exists. */ public #VT# get( Object key ) { #k# k; if ( key != null ) { if ( key instanceof #KT# ) { k = unwrapKey( key ); } else { return null; } } else { k = _map.getNoEntryKey(); } #v# v = _map.get( k ); // There may be a false positive since primitive maps // cannot return null, so we have to do an extra // check here. if ( v == _map.getNoEntryValue() ) { return null; } else { return wrapValue( v ); } } /** * Empties the map. */ public void clear() { this._map.clear(); } /** * Deletes a key/value pair from the map. * * @param key an Object value * @return the removed value, or null if it was not found in the map */ public #VT# remove( Object key ) { #k# k; if ( key != null ) { if ( key instanceof #KT# ) { k = unwrapKey( key ); } else { return null; } } else { k = _map.getNoEntryKey(); } #v# v = _map.remove( k ); // There may be a false positive since primitive maps // cannot return null, so we have to do an extra // check here. if ( v == _map.getNoEntryValue() ) { return null; } else { return wrapValue( v ); } } /** * Returns a Set view on the entries of the map. * * @return a Set value */ public Set> entrySet() { return new AbstractSet>() { public int size() { return _map.size(); } public boolean isEmpty() { return T#K##V#MapDecorator.this.isEmpty(); } public boolean contains( Object o ) { if (o instanceof Map.Entry) { Object k = ( ( Map.Entry ) o ).getKey(); Object v = ( ( Map.Entry ) o ).getValue(); return T#K##V#MapDecorator.this.containsKey(k) && T#K##V#MapDecorator.this.get(k).equals(v); } else { return false; } } public Iterator> iterator() { return new Iterator>() { private final T#K##V#Iterator it = _map.iterator(); public Map.Entry<#KT#,#VT#> next() { it.advance(); #k# ik = it.key(); final #KT# key = (ik == _map.getNoEntryKey()) ? null : wrapKey( ik ); #v# iv = it.value(); final #VT# v = (iv == _map.getNoEntryValue()) ? null : wrapValue( iv ); return new Map.Entry<#KT#,#VT#>() { private #VT# val = v; public boolean equals( Object o ) { return o instanceof Map.Entry && ( ( Map.Entry ) o ).getKey().equals(key) && ( ( Map.Entry ) o ).getValue().equals(val); } public #KT# getKey() { return key; } public #VT# getValue() { return val; } public int hashCode() { return key.hashCode() + val.hashCode(); } public #VT# setValue( #VT# value ) { val = value; return put( key, value ); } }; } public boolean hasNext() { return it.hasNext(); } public void remove() { it.remove(); } }; } public boolean add( Map.Entry<#KT#,#VT#> o ) { throw new UnsupportedOperationException(); } public boolean remove( Object o ) { boolean modified = false; if ( contains( o ) ) { //noinspection unchecked #KT# key = ( ( Map.Entry<#KT#,#VT#> ) o ).getKey(); _map.remove( unwrapKey( key ) ); modified = true; } return modified; } public boolean addAll( Collection> c ) { throw new UnsupportedOperationException(); } public void clear() { T#K##V#MapDecorator.this.clear(); } }; } /** * Checks for the presence of val in the values of the map. * * @param val an Object value * @return a boolean value */ public boolean containsValue( Object val ) { return val instanceof #VT# && _map.containsValue( unwrapValue( val ) ); } /** * Checks for the present of key in the keys of the map. * * @param key an Object value * @return a boolean value */ public boolean containsKey( Object key ) { if ( key == null ) return _map.containsKey( _map.getNoEntryKey() ); return key instanceof #KT# && _map.containsKey( unwrapKey( key ) ); } /** * Returns the number of entries in the map. * * @return the map's size. */ public int size() { return this._map.size(); } /** * Indicates whether map has any entries. * * @return true if the map is empty */ public boolean isEmpty() { return size() == 0; } /** * Copies the key/value mappings in map into this map. * Note that this will be a deep copy, as storage is by * primitive value. * * @param map a Map value */ public void putAll( Map map ) { Iterator> it = map.entrySet().iterator(); for ( int i = map.size(); i-- > 0; ) { Entry e = it.next(); this.put( e.getKey(), e.getValue() ); } } /** * Wraps a key * * @param k key in the underlying map * @return an Object representation of the key */ protected #KT# wrapKey( #k# k ) { return #KT#.valueOf( k ); } /** * Unwraps a key * * @param key wrapped key * @return an unwrapped representation of the key */ protected #k# unwrapKey( Object key ) { return ( ( #KT# ) key ).#k#Value(); } /** * Wraps a value * * @param k value in the underlying map * @return an Object representation of the value */ protected #VT# wrapValue( #v# k ) { return #VT#.valueOf( k ); } /** * Unwraps a value * * @param value wrapped value * @return an unwrapped representation of the value */ protected #v# unwrapValue( Object value ) { return ( ( #VT# ) value ).#v#Value(); } // Implements Externalizable public void readExternal( ObjectInput in ) throws IOException, ClassNotFoundException { // VERSION in.readByte(); // MAP _map = ( T#K##V#Map ) in.readObject(); } // Implements Externalizable public void writeExternal( ObjectOutput out ) throws IOException { // VERSION out.writeByte(0); // MAP out.writeObject( _map ); } } // T#K##V#HashMapDecorator trove-3.0.3/templates/gnu/trove/iterator/0000755000175000017500000000000012000515265017375 5ustar ericherichtrove-3.0.3/templates/gnu/trove/iterator/_E_ObjectIterator.template0000644000175000017500000001124311763017634024472 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001, Eric D. Friedman All Rights Reserved. // Copyright (c) 2009, Rob Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.iterator; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// /** * Iterator for maps of type #e# and Object. *

* The iterator semantics for Trove's primitive maps is slightly different * from those defined in java.util.Iterator, but still well within * the scope of the pattern, as defined by Gamma, et al. *

* This iterator does not implicitly advance to the next entry when * the value at the current position is retrieved. Rather, you must explicitly * ask the iterator to advance() and then retrieve either the key(), * the value() or both. This is done so that you have the option, but not * the obligation, to retrieve keys and/or values as your application requires, and * without introducing wrapper objects that would carry both. As the iteration is * stateful, access to the key/value parts of the current map entry happens in * constant time. *

* In practice, the iterator is akin to a "search finger" that you move from * position to position. Read or write operations affect the current entry only and * do not assume responsibility for moving the finger. *

* Here are some sample scenarios for this class of iterator: *

*

 * // accessing keys/values through an iterator:
 * for ( T#E#ObjectIterator it = map.iterator(); it.hasNext(); ) {
 *   it.advance();
 *   if ( satisfiesCondition( it.key() ) ) {
 *     doSomethingWithValue( it.value() );
 *   }
 * }
 * 
*

*

 * // modifying values in-place through iteration:
 * for ( T#E#ObjectIterator it = map.iterator(); it.hasNext(); ) {
 *   it.advance();
 *   if ( satisfiesCondition( it.key() ) ) {
 *     it.setValue( newValueForKey( it.key() ) );
 *   }
 * }
 * 
*

*

 * // deleting entries during iteration:
 * for ( T#E#ObjectIterator it = map.iterator(); it.hasNext(); ) {
 *   it.advance();
 *   if ( satisfiesCondition( it.key() ) ) {
 *     it.remove();
 *   }
 * }
 * 
*

*

 * // faster iteration by avoiding hasNext():
 * T#E#ObjectIterator iterator = map.iterator();
 * for ( int i = map.size(); i-- > 0; ) {
 *   iterator.advance();
 *   doSomethingWithKeyAndValue( iterator.key(), iterator.value() );
 * }
 * 
* * @author Eric D. Friedman * @author Rob Eden * @author Jeff Randall * @version $Id: _E_ObjectIterator.template,v 1.1.2.1 2009/09/15 02:38:31 upholderoftruth Exp $ */ public interface T#E#ObjectIterator extends TAdvancingIterator { /** * Provides access to the key of the mapping at the iterator's position. * Note that you must advance() the iterator at least once * before invoking this method. * * @return the key of the entry at the iterator's current position. */ public #e# key(); /** * Provides access to the value of the mapping at the iterator's position. * Note that you must advance() the iterator at least once * before invoking this method. * * @return the value of the entry at the iterator's current position. */ public V value(); /** * Replace the value of the mapping at the iterator's position with the * specified value. Note that you must advance() the iterator at * least once before invoking this method. * * @param val the value to set in the current entry * @return the old value of the entry. */ public V setValue( V val ); }trove-3.0.3/templates/gnu/trove/iterator/_E_Iterator.template0000644000175000017500000000300611763017634023341 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001, Eric D. Friedman All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.iterator; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// /** * Iterator for #e# collections. */ public interface T#E#Iterator extends TIterator { /** * Advances the iterator to the next element in the underlying collection * and returns it. * * @return the next #e# in the collection * @exception NoSuchElementException if the iterator is already exhausted */ public #e# next(); } trove-3.0.3/templates/gnu/trove/iterator/_K__V_Iterator.template0000644000175000017500000001053611763017634024001 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001, Eric D. Friedman All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.iterator; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// /** * Iterator for maps of type #k# and #v#. * *

The iterator semantics for Trove's primitive maps is slightly different * from those defined in java.util.Iterator, but still well within * the scope of the pattern, as defined by Gamma, et al.

* *

This iterator does not implicitly advance to the next entry when * the value at the current position is retrieved. Rather, you must explicitly * ask the iterator to advance() and then retrieve either the key(), * the value() or both. This is done so that you have the option, but not * the obligation, to retrieve keys and/or values as your application requires, and * without introducing wrapper objects that would carry both. As the iteration is * stateful, access to the key/value parts of the current map entry happens in * constant time.

* *

In practice, the iterator is akin to a "search finger" that you move from * position to position. Read or write operations affect the current entry only and * do not assume responsibility for moving the finger.

* *

Here are some sample scenarios for this class of iterator:

* *
 * // accessing keys/values through an iterator:
 * for ( T#K##V#Iterator it = map.iterator(); it.hasNext(); ) {
 *   it.advance();
 *   if ( satisfiesCondition( it.key() ) {
 *     doSomethingWithValue( it.value() );
 *   }
 * }
 * 
* *
 * // modifying values in-place through iteration:
 * for ( T#K##V#Iterator it = map.iterator(); it.hasNext(); ) {
 *   it.advance();
 *   if ( satisfiesCondition( it.key() ) {
 *     it.setValue( newValueForKey( it.key() ) );
 *   }
 * }
 * 
* *
 * // deleting entries during iteration:
 * for ( T#K##V#Iterator it = map.iterator(); it.hasNext(); ) {
 *   it.advance();
 *   if ( satisfiesCondition( it.key() ) {
 *     it.remove();
 *   }
 * }
 * 
* *
 * // faster iteration by avoiding hasNext():
 * T#K##V#Iterator iterator = map.iterator();
 * for ( int i = map.size(); i-- > 0; ) {
 *   iterator.advance();
 *   doSomethingWithKeyAndValue( iterator.key(), iterator.value() );
 * }
 * 
*/ public interface T#K##V#Iterator extends TAdvancingIterator { /** * Provides access to the key of the mapping at the iterator's position. * Note that you must advance() the iterator at least once * before invoking this method. * * @return the key of the entry at the iterator's current position. */ public #k# key(); /** * Provides access to the value of the mapping at the iterator's position. * Note that you must advance() the iterator at least once * before invoking this method. * * @return the value of the entry at the iterator's current position. */ public #v# value(); /** * Replace the value of the mapping at the iterator's position with the * specified value. Note that you must advance() the iterator at * least once before invoking this method. * * @param val the value to set in the current entry * @return the old value of the entry. */ public #v# setValue( #v# val ); } trove-3.0.3/templates/gnu/trove/iterator/Object_E_Iterator.template0000644000175000017500000001124711763017634024476 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001, Eric D. Friedman All Rights Reserved. // Copyright (c) 2009, Rob Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.iterator; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// /** * Iterator for maps of type Object and #e#. *

* The iterator semantics for Trove's primitive maps is slightly different * from those defined in java.util.Iterator, but still well within * the scope of the pattern, as defined by Gamma, et al. *

* This iterator does not implicitly advance to the next entry when * the value at the current position is retrieved. Rather, you must explicitly * ask the iterator to advance() and then retrieve either the key(), * the value() or both. This is done so that you have the option, but not * the obligation, to retrieve keys and/or values as your application requires, and * without introducing wrapper objects that would carry both. As the iteration is * stateful, access to the key/value parts of the current map entry happens in * constant time. *

* In practice, the iterator is akin to a "search finger" that you move from * position to position. Read or write operations affect the current entry only and * do not assume responsibility for moving the finger. *

* Here are some sample scenarios for this class of iterator: *

*

 * // accessing keys/values through an iterator:
 * for ( TObject#E#Iterator it = map.iterator(); it.hasNext(); ) {
 *   it.advance();
 *   if ( satisfiesCondition( it.key() ) ) {
 *     doSomethingWithValue( it.value() );
 *   }
 * }
 * 
*

*

 * // modifying values in-place through iteration:
 * for ( TObject#E#Iterator it = map.iterator(); it.hasNext(); ) {
 *   it.advance();
 *   if ( satisfiesCondition( it.key() ) ) {
 *     it.setValue( newValueForKey( it.key() ) );
 *   }
 * }
 * 
*

*

 * // deleting entries during iteration:
 * for ( TObject#E#Iterator it = map.iterator(); it.hasNext(); ) {
 *   it.advance();
 *   if ( satisfiesCondition( it.key() ) ) {
 *     it.remove();
 *   }
 * }
 * 
*

*

 * // faster iteration by avoiding hasNext():
 * TObject#E#Iterator iterator = map.iterator();
 * for ( int i = map.size(); i-- > 0; ) {
 *   iterator.advance();
 *   doSomethingWithKeyAndValue( iterator.key(), iterator.value() );
 * }
 * 
* * @author Eric D. Friedman * @author Rob Eden * @author Jeff Randall * @version $Id: Object_E_Iterator.template,v 1.1.2.1 2009/09/14 19:02:20 upholderoftruth Exp $ */ public interface TObject#E#Iterator extends TAdvancingIterator { /** * Provides access to the key of the mapping at the iterator's position. * Note that you must advance() the iterator at least once * before invoking this method. * * @return the key of the entry at the iterator's current position. */ public K key(); /** * Provides access to the value of the mapping at the iterator's position. * Note that you must advance() the iterator at least once * before invoking this method. * * @return the value of the entry at the iterator's current position. */ public #e# value(); /** * Replace the value of the mapping at the iterator's position with the * specified value. Note that you must advance() the iterator at * least once before invoking this method. * * @param val the value to set in the current entry * @return the old value of the entry. */ public #e# setValue( #e# val ); }trove-3.0.3/templates/gnu/trove/queue/0000755000175000017500000000000012000515265016670 5ustar ericherichtrove-3.0.3/templates/gnu/trove/queue/_E_Queue.template0000644000175000017500000000452111763017634022132 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2009, Rob Eden All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.queue; import gnu.trove.T#E#Collection; import java.io.Serializable; /** * Interface for Trove queue implementations. * * @see java.util.Queue */ public interface T#E#Queue extends T#E#Collection { /** * Retrieves and removes the head of this queue. This method differs from * {@link #poll} only in that it throws an exception if this queue is empty. */ public #e# element(); /** * Inserts the specified element into this queue if it is possible to do so * immediately without violating capacity restrictions. When using a * capacity-restricted queue, this method is generally preferable to * {@link #add}, which can fail to insert an element only by throwing an exception. * * @param e The element to add. * * @return true if the element was added to this queue, else false */ public boolean offer( #e# e ); /** * Retrieves, but does not remove, the head of this queue, or returns * {@link #getNoEntryValue} if this queue is empty. * * @return the head of this queue, or {@link #getNoEntryValue} if this queue is empty */ public #e# peek(); /** * Retrieves and removes the head of this queue, or returns {@link #getNoEntryValue} * if this queue is empty. * * @return the head of this queue, or {@link #getNoEntryValue} if this queue is empty */ public #e# poll(); }trove-3.0.3/templates/gnu/trove/procedure/0000755000175000017500000000000012000515265017534 5ustar ericherichtrove-3.0.3/templates/gnu/trove/procedure/Object_E_Procedure.template0000644000175000017500000000325611763017634024775 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001, Eric D. Friedman All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.procedure; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// /** * Interface for procedures that take two parameters of type Object and #e#. */ public interface TObject#E#Procedure { /** * Executes this procedure. A false return value indicates that * the application executing this procedure should not invoke this * procedure again. * * @param a an Object value * @param b a #e# value * @return true if additional invocations of the procedure are * allowed. */ public boolean execute( K a, #e# b ); } trove-3.0.3/templates/gnu/trove/procedure/_E_ObjectProcedure.template0000644000175000017500000000325611763017634024775 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001, Eric D. Friedman All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.procedure; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// /** * Interface for procedures that take two parameters of type #e# and Object. */ public interface T#E#ObjectProcedure { /** * Executes this procedure. A false return value indicates that * the application executing this procedure should not invoke this * procedure again. * * @param a a #e# value * @param b an Object value * @return true if additional invocations of the procedure are * allowed. */ public boolean execute( #e# a, T b ); } trove-3.0.3/templates/gnu/trove/procedure/_E_Procedure.template0000644000175000017500000000314711763017634023645 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001, Eric D. Friedman All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.procedure; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// /** * Interface for procedures with one #e# parameter. */ public interface T#E#Procedure { /** * Executes this procedure. A false return value indicates that * the application executing this procedure should not invoke this * procedure again. * * @param value a value of type #e# * @return true if additional invocations of the procedure are * allowed. */ public boolean execute( #e# value ); }trove-3.0.3/templates/gnu/trove/procedure/_K__V_Procedure.template0000644000175000017500000000324311763017634024274 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001, Eric D. Friedman All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.procedure; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// /** * Interface for procedures that take two parameters of type #k# and #v#. */ public interface T#K##V#Procedure { /** * Executes this procedure. A false return value indicates that * the application executing this procedure should not invoke this * procedure again. * * @param a a #k# value * @param b a #v# value * @return true if additional invocations of the procedure are * allowed. */ public boolean execute( #k# a, #v# b ); } trove-3.0.3/templates/gnu/trove/TCollections.template0000644000175000017500000004103511763017634021722 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2008, Robert D. Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// import gnu.trove.set.*; import gnu.trove.list.*; import gnu.trove.map.*; import gnu.trove.impl.unmodifiable.*; import gnu.trove.impl.sync.*; import java.util.RandomAccess; /** * Trove equivalent of the {@link java.util.Collections} class. */ @SuppressWarnings({"UnusedDeclaration"}) public class TCollections { // Disallow creation of instances of this class private TCollections() { } /////////////////////////// // TUnmodifiableCollections #REPLICATED1# #REPLICATED2# #REPLICATED3# #REPLICATED4# #REPLICATED5# #REPLICATED6# /////////////////////////// // TSynchronizedCollections #REPLICATED7# #REPLICATED8# #REPLICATED9# #REPLICATED10# #REPLICATED11# #REPLICATED12# } ====START_REPLICATED_CONTENT #1==== /** * Returns an unmodifiable view of the specified Trove primitive collection. This method * allows modules to provide users with "read-only" access to internal * collections. Query operations on the returned collection "read through" * to the specified collection, and attempts to modify the returned * collection, whether direct or via its iterator, result in an * UnsupportedOperationException.

* * The returned collection does not pass the hashCode and equals * operations through to the backing collection, but relies on * Object's equals and hashCode methods. This * is necessary to preserve the contracts of these operations in the case * that the backing collection is a set or a list.

* * The returned collection will be serializable if the specified collection * is serializable. * * @param c the collection for which an unmodifiable view is to be * returned. * @return an unmodifiable view of the specified Trove primitive collection. */ public static T#E#Collection unmodifiableCollection( T#E#Collection c ) { return new TUnmodifiable#E#Collection( c ); } =====END_REPLICATED_CONTENT #1===== ====START_REPLICATED_CONTENT #2==== /** * Returns an unmodifiable view of the specified Trove primitive set. This method allows * modules to provide users with "read-only" access to internal sets. * Query operations on the returned set "read through" to the specified * set, and attempts to modify the returned set, whether direct or via its * iterator, result in an UnsupportedOperationException.

* * The returned set will be serializable if the specified set * is serializable. * * @param s the set for which an unmodifiable view is to be returned. * @return an unmodifiable view of the specified Trove primitive set. */ public static T#E#Set unmodifiableSet( T#E#Set s ) { return new TUnmodifiable#E#Set( s ); } =====END_REPLICATED_CONTENT #2===== ====START_REPLICATED_CONTENT #3==== /** * Returns an unmodifiable view of the specified Trove primitive list. This method allows * modules to provide users with "read-only" access to internal * lists. Query operations on the returned list "read through" to the * specified list, and attempts to modify the returned list, whether * direct or via its iterator, result in an * UnsupportedOperationException.

* * The returned list will be serializable if the specified list * is serializable. Similarly, the returned list will implement * {@link RandomAccess} if the specified list does. * * @param list the list for which an unmodifiable view is to be returned. * @return an unmodifiable view of the specified Trove primitive list. */ public static T#E#List unmodifiableList( T#E#List list) { return ( list instanceof RandomAccess ? new TUnmodifiableRandomAccess#E#List( list ) : new TUnmodifiable#E#List( list ) ); } =====END_REPLICATED_CONTENT #3===== ====START_REPLICATED_CONTENT #4==== /** * Returns an unmodifiable view of the specified Trove primitive/primitive map. This method * allows modules to provide users with "read-only" access to internal * maps. Query operations on the returned map "read through" * to the specified map, and attempts to modify the returned * map, whether direct or via its collection views, result in an * UnsupportedOperationException.

* * The returned map will be serializable if the specified map * is serializable. * * @param m the map for which an unmodifiable view is to be returned. * @return an unmodifiable view of the specified Trove primitive/primitive map. */ public static T#K##V#Map unmodifiableMap( T#K##V#Map m ) { return new TUnmodifiable#K##V#Map( m ); } =====END_REPLICATED_CONTENT #4===== ====START_REPLICATED_CONTENT #5==== /** * Returns an unmodifiable view of the specified Trove primitive/Object map. This method * allows modules to provide users with "read-only" access to internal * maps. Query operations on the returned map "read through" * to the specified map, and attempts to modify the returned * map, whether direct or via its collection views, result in an * UnsupportedOperationException.

* * The returned map will be serializable if the specified map * is serializable. * * @param m the map for which an unmodifiable view is to be returned. * @return an unmodifiable view of the specified Trove primitive/primitive map. */ public static T#E#ObjectMap unmodifiableMap( T#E#ObjectMap m ) { return new TUnmodifiable#E#ObjectMap( m ); } =====END_REPLICATED_CONTENT #5===== ====START_REPLICATED_CONTENT #6==== /** * Returns an unmodifiable view of the specified Trove Object/primitive map. This method * allows modules to provide users with "read-only" access to internal * maps. Query operations on the returned map "read through" * to the specified map, and attempts to modify the returned * map, whether direct or via its collection views, result in an * UnsupportedOperationException.

* * The returned map will be serializable if the specified map * is serializable. * * @param m the map for which an unmodifiable view is to be returned. * @return an unmodifiable view of the specified Trove primitive/primitive map. */ public static TObject#E#Map unmodifiableMap( TObject#E#Map m ) { return new TUnmodifiableObject#E#Map( m ); } =====END_REPLICATED_CONTENT #6===== ====START_REPLICATED_CONTENT #7==== /** * Returns a synchronized (thread-safe) Trove collection backed by the specified * Trove collection. In order to guarantee serial access, it is critical that * all access to the backing collection is accomplished * through the returned collection.

* * It is imperative that the user manually synchronize on the returned * collection when iterating over it: *

     *  T#E#Collection c = TCollections.synchronizedCollection( myCollection );
     *     ...
     *  synchronized( c ) {
     *      T#E#Iterator i = c.iterator(); // Must be in the synchronized block
     *      while ( i.hasNext() )
     *         foo( i.next() );
     *  }
     * 
* Failure to follow this advice may result in non-deterministic behavior. * *

The returned collection does not pass the hashCode * and equals operations through to the backing collection, but * relies on Object's equals and hashCode methods. This is * necessary to preserve the contracts of these operations in the case * that the backing collection is a set or a list.

* * The returned collection will be serializable if the specified collection * is serializable. * * @param c the collection to be "wrapped" in a synchronized collection. * @return a synchronized view of the specified collection. */ public static T#E#Collection synchronizedCollection( T#E#Collection c ) { return new TSynchronized#E#Collection(c); } static T#E#Collection synchronizedCollection( T#E#Collection c, Object mutex ) { return new TSynchronized#E#Collection( c, mutex ); } =====END_REPLICATED_CONTENT #7===== ====START_REPLICATED_CONTENT #8==== /** * Returns a synchronized (thread-safe) Trove set backed by the specified * set. In order to guarantee serial access, it is critical that * all access to the backing set is accomplished * through the returned set.

* * It is imperative that the user manually synchronize on the returned * set when iterating over it: *

     *  T#E#Set s = TCollections.synchronizedSet( new T#E#HashSet() );
     *      ...
     *  synchronized(s) {
     *      T#E#Iterator i = s.iterator(); // Must be in the synchronized block
     *      while ( i.hasNext() )
     *          foo( i.next() );
     *  }
     * 
* Failure to follow this advice may result in non-deterministic behavior. * *

The returned set will be serializable if the specified set is * serializable. * * @param s the set to be "wrapped" in a synchronized set. * @return a synchronized view of the specified set. */ public static T#E#Set synchronizedSet( T#E#Set s ) { return new TSynchronized#E#Set( s ); } static T#E#Set synchronizedSet( T#E#Set s, Object mutex ) { return new TSynchronized#E#Set( s, mutex ); } =====END_REPLICATED_CONTENT #8===== ====START_REPLICATED_CONTENT #9==== /** * Returns a synchronized (thread-safe) Trove list backed by the specified * list. In order to guarantee serial access, it is critical that * all access to the backing list is accomplished * through the returned list.

* * It is imperative that the user manually synchronize on the returned * list when iterating over it: *

     *  T#E#List list = TCollections.synchronizedList( new T#E#ArrayList() );
     *      ...
     *  synchronized( list ) {
     *      T#E#Iterator i = list.iterator(); // Must be in synchronized block
     *      while ( i.hasNext() )
     *          foo( i.next() );
     *  }
     * 
* Failure to follow this advice may result in non-deterministic behavior. * *

The returned list will be serializable if the specified list is * serializable. * * @param list the list to be "wrapped" in a synchronized list. * @return a synchronized view of the specified list. */ public static T#E#List synchronizedList( T#E#List list ) { return ( list instanceof RandomAccess ? new TSynchronizedRandomAccess#E#List( list ) : new TSynchronized#E#List( list ) ); } static T#E#List synchronizedList( T#E#List list, Object mutex ) { return ( list instanceof RandomAccess ? new TSynchronizedRandomAccess#E#List( list, mutex ) : new TSynchronized#E#List( list, mutex ) ); } =====END_REPLICATED_CONTENT #9===== ====START_REPLICATED_CONTENT #10==== /** * Returns a synchronized (thread-safe) Trove map backed by the specified * map. In order to guarantee serial access, it is critical that * all access to the backing map is accomplished * through the returned map.

* * It is imperative that the user manually synchronize on the returned * map when iterating over any of its collection views: *

     *  T#K##V#Map m = TCollections.synchronizedMap( new T#K##V#HashMap() );
     *      ...
     *  T#K#Set s = m.keySet();  // Needn't be in synchronized block
     *      ...
     *  synchronized( m ) {  // Synchronizing on m, not s!
     *      T#K#Iterator i = s.iterator(); // Must be in synchronized block
     *      while ( i.hasNext() )
     *          foo( i.next() );
     *  }
     * 
* Failure to follow this advice may result in non-deterministic behavior. * *

The returned map will be serializable if the specified map is * serializable. * * @param m the map to be "wrapped" in a synchronized map. * @return a synchronized view of the specified map. */ public static T#K##V#Map synchronizedMap( T#K##V#Map m ) { return new TSynchronized#K##V#Map( m ); } =====END_REPLICATED_CONTENT #10===== ====START_REPLICATED_CONTENT #11==== /** * Returns a synchronized (thread-safe) Trove map backed by the specified * map. In order to guarantee serial access, it is critical that * all access to the backing map is accomplished * through the returned map.

* * It is imperative that the user manually synchronize on the returned * map when iterating over any of its collection views: *

     *  T#E#ObjectMap m = TCollections.synchronizedMap( new T#E#ObjectHashMap() );
     *      ...
     *  T#E#Set s = m.keySet();  // Needn't be in synchronized block
     *      ...
     *  synchronized( m ) {  // Synchronizing on m, not s!
     *      T#E#Iterator i = s.iterator(); // Must be in synchronized block
     *      while ( i.hasNext() )
     *          foo( i.next() );
     *  }
     * 
* Failure to follow this advice may result in non-deterministic behavior. * *

The returned map will be serializable if the specified map is * serializable. * * @param m the map to be "wrapped" in a synchronized map. * @return a synchronized view of the specified map. */ public static T#E#ObjectMap synchronizedMap( T#E#ObjectMap m ) { return new TSynchronized#E#ObjectMap( m ); } =====END_REPLICATED_CONTENT #11===== ====START_REPLICATED_CONTENT #12==== /** * Returns a synchronized (thread-safe) Trove map backed by the specified * map. In order to guarantee serial access, it is critical that * all access to the backing map is accomplished * through the returned map.

* * It is imperative that the user manually synchronize on the returned * map when iterating over any of its collection views: *

     *  TObject#E#Map m = TCollections.synchronizedMap( new TObject#E#HashMap() );
     *      ...
     *  Set s = m.keySet();  // Needn't be in synchronized block
     *      ...
     *  synchronized( m ) {  // Synchronizing on m, not s!
     *      Iterator i = s.iterator(); // Must be in synchronized block
     *      while ( i.hasNext() )
     *          foo( i.next() );
     *  }
     * 
* Failure to follow this advice may result in non-deterministic behavior. * *

The returned map will be serializable if the specified map is * serializable. * * @param m the map to be "wrapped" in a synchronized map. * @return a synchronized view of the specified map. */ public static TObject#E#Map synchronizedMap( TObject#E#Map m ) { return new TSynchronizedObject#E#Map( m ); } =====END_REPLICATED_CONTENT #12=====trove-3.0.3/templates/gnu/trove/list/0000755000175000017500000000000012000515265016517 5ustar ericherichtrove-3.0.3/templates/gnu/trove/list/_E_List.template0000644000175000017500000003707011763017634021615 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2009, Rob Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.list; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// import gnu.trove.function.*; import gnu.trove.procedure.*; import gnu.trove.T#E#Collection; import java.io.Serializable; import java.util.Random; /** * Interface for Trove list implementations. */ public interface T#E#List extends T#E#Collection { /** * Returns the value that is used to represent null. The default * value is generally zero, but can be changed during construction * of the collection. * * @return the value that represents null */ public #e# getNoEntryValue(); /** * Returns the number of values in the list. * * @return the number of values in the list. */ public int size(); /** * Tests whether this list contains any values. * * @return true if the list is empty. */ public boolean isEmpty(); /** * Adds val to the end of the list, growing as needed. * * @param val an #e# value * @return true if the list was modified by the add operation */ public boolean add(#e# val); /** * Adds the values in the array vals to the end of the * list, in order. * * @param vals an #e#[] value */ public void add( #e#[] vals ); /** * Adds a subset of the values in the array vals to the * end of the list, in order. * * @param vals an #e#[] value * @param offset the offset at which to start copying * @param length the number of values to copy. */ public void add( #e#[] vals, int offset, int length ); /** * Inserts value into the list at offset. All * values including and to the right of offset are shifted * to the right. * * @param offset an int value * @param value an #e# value */ public void insert( int offset, #e# value ); /** * Inserts the array of values into the list at * offset. All values including and to the right of * offset are shifted to the right. * * @param offset an int value * @param values an #e#[] value */ public void insert( int offset, #e#[] values ); /** * Inserts a slice of the array of values into the list * at offset. All values including and to the right of * offset are shifted to the right. * * @param offset an int value * @param values an #e#[] value * @param valOffset the offset in the values array at which to * start copying. * @param len the number of values to copy from the values array */ public void insert( int offset, #e#[] values, int valOffset, int len ); /** * Returns the value at the specified offset. * * @param offset an int value * @return an #e# value */ public #e# get( int offset ); /** * Sets the value at the specified offset. * * @param offset an int value * @param val an #e# value * * @return The value previously at the given index. */ public #e# set( int offset, #e# val ); /** * Replace the values in the list starting at offset with * the contents of the values array. * * @param offset the first offset to replace * @param values the source of the new values */ public void set( int offset, #e#[] values ); /** * Replace the values in the list starting at offset with * length values from the values array, starting * at valOffset. * * @param offset the first offset to replace * @param values the source of the new values * @param valOffset the first value to copy from the values array * @param length the number of values to copy */ public void set( int offset, #e#[] values, int valOffset, int length ); /** * Sets the value at the specified offset and returns the * previously stored value. * * @param offset an int value * @param val an #e# value * @return the value previously stored at offset. */ public #e# replace( int offset, #e# val ); /** * Flushes the internal state of the list, resetting the capacity * to the default. */ public void clear(); /** * Removes value from the list. * * @param value an #e# value * @return true if the list was modified by the remove operation. */ public boolean remove( #e# value ); /** * Removes value at a given offset from the list. * * @param offset an int value that represents * the offset to the element to be removed * @return an #e# that is the value removed. */ public #e# removeAt( int offset ); /** * Removes length values from the list, starting at * offset * * @param offset an int value * @param length an int value */ public void remove( int offset, int length ); /** * Transform each value in the list using the specified function. * * @param function a T#E#Function value */ public void transformValues( T#E#Function function ); /** * Reverse the order of the elements in the list. */ public void reverse(); /** * Reverse the order of the elements in the range of the list. * * @param from the inclusive index at which to start reversing * @param to the exclusive index at which to stop reversing */ public void reverse( int from, int to ); /** * Shuffle the elements of the list using the specified random * number generator. * * @param rand a Random value */ public void shuffle( Random rand ); /** * Returns a sublist of this list. * * @param begin low endpoint (inclusive) of the subList. * @param end high endpoint (exclusive) of the subList. * @return sublist of this list from begin, inclusive to end, exclusive. * @throws IndexOutOfBoundsException - endpoint out of range * @throws IllegalArgumentException - endpoints out of order (end > begin) */ public T#E#List subList( int begin, int end ); /** * Copies the contents of the list into a native array. * * @return an #e#[] value */ public #e#[] toArray(); /** * Copies a slice of the list into a native array. * * @param offset the offset at which to start copying * @param len the number of values to copy. * @return an #e#[] value */ public #e#[] toArray( int offset, int len ); /** * Copies a slice of the list into a native array. * *

If the list fits in the specified array with room to spare (i.e., * the array has more elements than the list), the element in the array * immediately following the end of the list is set to * {@link #getNoEntryValue()}. * (This is useful in determining the length of the list only if * the caller knows that the list does not contain any "null" elements.) * *

NOTE: Trove does not allocate a new array if the array passed in is * not large enough to hold all of the data elements. It will instead fill * the array passed in. * * @param dest the array to copy into. * @return the array passed in. */ public #e#[] toArray( #e#[] dest ); /** * Copies a slice of the list into a native array. * * @param dest the array to copy into. * @param offset the offset where the first value should be copied * @param len the number of values to copy. * @return the array passed in. */ public #e#[] toArray( #e#[] dest, int offset, int len ); /** * Copies a slice of the list into a native array. * * @param dest the array to copy into. * @param source_pos the offset of the first value to copy * @param dest_pos the offset where the first value should be copied * @param len the number of values to copy. * @return the array passed in. */ public #e#[] toArray( #e#[] dest, int source_pos, int dest_pos, int len ); /** * Applies the procedure to each value in the list in ascending * (front to back) order. * * @param procedure a T#E#Procedure value * @return true if the procedure did not terminate prematurely. */ public boolean forEach( T#E#Procedure procedure ); /** * Applies the procedure to each value in the list in descending * (back to front) order. * * @param procedure a T#E#Procedure value * @return true if the procedure did not terminate prematurely. */ public boolean forEachDescending( T#E#Procedure procedure ); /** * Sort the values in the list (ascending) using the Sun quicksort * implementation. * * @see java.util.Arrays#sort */ public void sort(); /** * Sort a slice of the list (ascending) using the Sun quicksort * implementation. * * @param fromIndex the index at which to start sorting (inclusive) * @param toIndex the index at which to stop sorting (exclusive) * @see java.util.Arrays#sort */ public void sort( int fromIndex, int toIndex ); /** * Fills every slot in the list with the specified value. * * @param val the value to use when filling */ public void fill( #e# val ); /** * Fills a range in the list with the specified value. * * @param fromIndex the offset at which to start filling (inclusive) * @param toIndex the offset at which to stop filling (exclusive) * @param val the value to use when filling */ public void fill( int fromIndex, int toIndex, #e# val ); /** * Performs a binary search for value in the entire list. * Note that you must @{link #sort sort} the list before * doing a search. * * @param value the value to search for * @return the absolute offset in the list of the value, or its * negative insertion point into the sorted list. */ public int binarySearch( #e# value ); /** * Performs a binary search for value in the specified * range. Note that you must @{link #sort sort} the list * or the range before doing a search. * * @param value the value to search for * @param fromIndex the lower boundary of the range (inclusive) * @param toIndex the upper boundary of the range (exclusive) * @return the absolute offset in the list of the value, or its * negative insertion point into the sorted list. */ public int binarySearch( #e# value, int fromIndex, int toIndex ); /** * Searches the list front to back for the index of * value. * * @param value an #e# value * @return the first offset of the value, or -1 if it is not in * the list. * @see #binarySearch for faster searches on sorted lists */ public int indexOf( #e# value ); /** * Searches the list front to back for the index of * value, starting at offset. * * @param offset the offset at which to start the linear search * (inclusive) * @param value an #e# value * @return the first offset of the value, or -1 if it is not in * the list. * @see #binarySearch for faster searches on sorted lists */ public int indexOf( int offset, #e# value ); /** * Searches the list back to front for the last index of * value. * * @param value an #e# value * @return the last offset of the value, or -1 if it is not in * the list. * @see #binarySearch for faster searches on sorted lists */ public int lastIndexOf( #e# value ); /** * Searches the list back to front for the last index of * value, starting at offset. * * @param offset the offset at which to start the linear search * (exclusive) * @param value an #e# value * @return the last offset of the value, or -1 if it is not in * the list. * @see #binarySearch for faster searches on sorted lists */ public int lastIndexOf( int offset, #e# value ); /** * Searches the list for value * * @param value an #e# value * @return true if value is in the list. */ public boolean contains( #e# value ); /** * Searches the list for values satisfying condition in * the manner of the *nix grep utility. * * @param condition a condition to apply to each element in the list * @return a list of values which match the condition. */ public T#E#List grep( T#E#Procedure condition ); /** * Searches the list for values which do not satisfy * condition. This is akin to *nix grep -v. * * @param condition a condition to apply to each element in the list * @return a list of values which do not match the condition. */ public T#E#List inverseGrep( T#E#Procedure condition ); /** * Finds the maximum value in the list. * * @return the largest value in the list. * @exception IllegalStateException if the list is empty */ public #e# max(); /** * Finds the minimum value in the list. * * @return the smallest value in the list. * @exception IllegalStateException if the list is empty */ public #e# min(); /** * Calculates the sum of all the values in the list. * * @return the sum of the values in the list (zero if the list is empty). */ public #e# sum(); } trove-3.0.3/templates/gnu/trove/list/linked/0000755000175000017500000000000012000515265017765 5ustar ericherichtrove-3.0.3/templates/gnu/trove/list/linked/_E_LinkedList.template0000644000175000017500000006651711763017634024222 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001, Eric D. Friedman All Rights Reserved. // Copyright (c) 2009, Rob Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // Copyright (c) 2011, Johan Parent All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.list.linked; import gnu.trove.function.T#E#Function; import gnu.trove.list.T#E#List; import gnu.trove.procedure.T#E#Procedure; import gnu.trove.iterator.T#E#Iterator; import gnu.trove.T#E#Collection; import gnu.trove.impl.*; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.*; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// /** * A resizable, double linked list of #e# primitives. */ public class T#E#LinkedList implements T#E#List, Externalizable { #e# no_entry_value; int size; T#E#Link head = null; T#E#Link tail = head; public T#E#LinkedList() { } public T#E#LinkedList(#e# no_entry_value) { this.no_entry_value = no_entry_value; } public T#E#LinkedList(T#E#List list) { no_entry_value = list.getNoEntryValue(); // for (T#E#Iterator iterator = list.iterator(); iterator.hasNext();) { #e# next = iterator.next(); add(next); } } /** {@inheritDoc} */ public #e# getNoEntryValue() { return no_entry_value; } /** {@inheritDoc} */ public int size() { return size; } /** {@inheritDoc} */ public boolean isEmpty() { return size() == 0; } /** {@inheritDoc} */ public boolean add(#e# val) { T#E#Link l = new T#E#Link(val); if (no(head)) { head = l; tail = l; } else { l.setPrevious(tail); tail.setNext(l); // tail = l; } size++; return true; } /** {@inheritDoc} */ public void add(#e#[] vals) { for (#e# val : vals) { add(val); } } /** {@inheritDoc} */ public void add(#e#[] vals, int offset, int length) { for (int i = 0; i < length; i++) { #e# val = vals[offset + i]; add(val); } } /** {@inheritDoc} */ public void insert(int offset, #e# value) { T#E#LinkedList tmp = new T#E#LinkedList(); tmp.add(value); insert(offset, tmp); } /** {@inheritDoc} */ public void insert(int offset, #e#[] values) { insert(offset, link(values, 0, values.length)); } /** {@inheritDoc} */ public void insert(int offset, #e#[] values, int valOffset, int len) { insert(offset, link(values, valOffset, len)); } void insert(int offset, T#E#LinkedList tmp) { T#E#Link l = getLinkAt(offset); size = size + tmp.size; // if (l == head) { // Add in front tmp.tail.setNext(head); head.setPrevious(tmp.tail); head = tmp.head; return; } if (no(l)) { if (size == 0) { // New empty list head = tmp.head; tail = tmp.tail; } else { // append tail.setNext(tmp.head); tmp.head.setPrevious(tail); tail = tmp.tail; } } else { T#E#Link prev = l.getPrevious(); l.getPrevious().setNext(tmp.head); // Link by behind tmp tmp.tail.setNext(l); l.setPrevious(tmp.tail); tmp.head.setPrevious(prev); } } static T#E#LinkedList link(#e#[] values, int valOffset, int len) { T#E#LinkedList ret = new T#E#LinkedList(); for (int i = 0; i < len; i++) { ret.add(values[valOffset + i]); } return ret; } /** {@inheritDoc} */ public #e# get(int offset) { if (offset > size) throw new IndexOutOfBoundsException("index " + offset + " exceeds size " + size); T#E#Link l = getLinkAt(offset); // if (no(l)) return no_entry_value; return l.getValue(); } /** * Returns the link at the given offset. *

* A simple bisection criteria is used to keep the worst case complexity equal to * O(n/2) where n = size(). Simply start from head of list or tail depending on offset * and list size. * * @param offset of the link * @return link or null if non-existent */ public T#E#Link getLinkAt(int offset) { if (offset >= size()) return null; if (offset <= (size() >>> 1)) return getLink(head, 0, offset, true); else return getLink(tail, size() - 1, offset, false); } /** * Returns the link at absolute offset starting from given the initial link 'l' at index 'idx' * * @param l * @param idx * @param offset * @return */ private static T#E#Link getLink(T#E#Link l, int idx, int offset) { return getLink(l, idx, offset, true); } /** * Returns link at given absolute offset starting from link 'l' at index 'idx' * @param l * @param idx * @param offset * @param next * @return */ private static T#E#Link getLink(T#E#Link l, int idx, int offset, boolean next) { int i = idx; // while (got(l)) { if (i == offset) { return l; } i = i + (next ? 1 : -1); l = next ? l.getNext() : l.getPrevious(); } return null; } /** {@inheritDoc} */ public #e# set(int offset, #e# val) { if (offset > size) throw new IndexOutOfBoundsException("index " + offset + " exceeds size " + size); T#E#Link l = getLinkAt(offset); // if (no(l)) throw new IndexOutOfBoundsException("at offset " + offset); #e# prev = l.getValue(); l.setValue(val); return prev; } /** {@inheritDoc} */ public void set(int offset, #e#[] values) { set(offset, values, 0, values.length); } /** {@inheritDoc} */ public void set(int offset, #e#[] values, int valOffset, int length) { for (int i = 0; i < length; i++) { #e# value = values[valOffset + i]; set(offset + i, value); } } /** {@inheritDoc} */ public #e# replace(int offset, #e# val) { return set(offset, val); } /** {@inheritDoc} */ public void clear() { size = 0; // head = null; tail = null; } /** {@inheritDoc} */ public boolean remove(#e# value) { boolean changed = false; for (T#E#Link l = head; got(l); l = l.getNext()) { // if (l.getValue() == value) { changed = true; // removeLink(l); } } return changed; } /** * unlinks the give T#E#Link from the list * * @param l */ private void removeLink(T#E#Link l) { if (no(l)) return; size--; T#E#Link prev = l.getPrevious(); T#E#Link next = l.getNext(); if (got(prev)) { prev.setNext(next); } else { // No previous we must be head head = next; } if (got(next)) { next.setPrevious(prev); } else { // No next so me must be tail tail = prev; } // Unlink l.setNext(null); l.setPrevious(null); } /** {@inheritDoc} */ public boolean containsAll(Collection collection) { if (isEmpty()) return false; for (Object o : collection) { if (o instanceof #ET#) { #ET# i = (#ET#) o; if (!(contains(i))) return false; } else { return false; } } return true; } /** {@inheritDoc} */ public boolean containsAll(T#E#Collection collection) { if (isEmpty()) return false; for (T#E#Iterator it = collection.iterator(); it.hasNext();) { #e# i = it.next(); if (!(contains(i))) return false; } return true; } /** {@inheritDoc} */ public boolean containsAll(#e#[] array) { if (isEmpty()) return false; for (#e# i : array) { if (!contains(i)) return false; } return true; } /** {@inheritDoc} */ public boolean addAll(Collection collection) { boolean ret = false; for (#ET# v : collection) { if (add(v.#e#Value())) ret = true; } return ret; } /** {@inheritDoc} */ public boolean addAll(T#E#Collection collection) { boolean ret = false; for (T#E#Iterator it = collection.iterator(); it.hasNext();) { #e# i = it.next(); if (add(i)) ret = true; } return ret; } /** {@inheritDoc} */ public boolean addAll(#e#[] array) { boolean ret = false; for (#e# i : array) { if (add(i)) ret = true; } return ret; } /** {@inheritDoc} */ public boolean retainAll(Collection collection) { boolean modified = false; T#E#Iterator iter = iterator(); while (iter.hasNext()) { if (!collection.contains(#ET#.valueOf(iter.next()))) { iter.remove(); modified = true; } } return modified; } /** {@inheritDoc} */ public boolean retainAll(T#E#Collection collection) { boolean modified = false; T#E#Iterator iter = iterator(); while (iter.hasNext()) { if (!collection.contains(iter.next())) { iter.remove(); modified = true; } } return modified; } /** {@inheritDoc} */ public boolean retainAll(#e#[] array) { Arrays.sort(array); boolean modified = false; T#E#Iterator iter = iterator(); while (iter.hasNext()) { if (Arrays.binarySearch(array, iter.next()) < 0) { iter.remove(); modified = true; } } return modified; } /** {@inheritDoc} */ public boolean removeAll(Collection collection) { boolean modified = false; T#E#Iterator iter = iterator(); while (iter.hasNext()) { if (collection.contains(#ET#.valueOf(iter.next()))) { iter.remove(); modified = true; } } return modified; } /** {@inheritDoc} */ public boolean removeAll(T#E#Collection collection) { boolean modified = false; T#E#Iterator iter = iterator(); while (iter.hasNext()) { if (collection.contains(iter.next())) { iter.remove(); modified = true; } } return modified; } /** {@inheritDoc} */ public boolean removeAll(#e#[] array) { Arrays.sort(array); boolean modified = false; T#E#Iterator iter = iterator(); while (iter.hasNext()) { if (Arrays.binarySearch(array, iter.next()) >= 0) { iter.remove(); modified = true; } } return modified; } /** {@inheritDoc} */ public #e# removeAt(int offset) { T#E#Link l = getLinkAt(offset); if (no(l)) throw new ArrayIndexOutOfBoundsException("no elemenet at " + offset); #e# prev = l.getValue(); removeLink(l); return prev; } /** {@inheritDoc} */ public void remove(int offset, int length) { for (int i = 0; i < length; i++) { removeAt(offset); // since the list shrinks we don't need to use offset+i to get the next entry ;) } } /** {@inheritDoc} */ public void transformValues(T#E#Function function) { for (T#E#Link l = head; got(l);) { // l.setValue(function.execute(l.getValue())); // l = l.getNext(); } } /** {@inheritDoc} */ public void reverse() { T#E#Link h = head; T#E#Link t = tail; T#E#Link prev, next, tmp; // T#E#Link l = head; while (got(l)) { next = l.getNext(); prev = l.getPrevious(); // tmp = l; l = l.getNext(); // tmp.setNext(prev); tmp.setPrevious(next); } // head = t; tail = h; } /** {@inheritDoc} */ public void reverse(int from, int to) { if (from > to) throw new IllegalArgumentException("from > to : " + from + ">" + to); T#E#Link start = getLinkAt(from); T#E#Link stop = getLinkAt(to); T#E#Link prev, next; T#E#Link tmp = null; T#E#Link tmpHead = start.getPrevious(); // T#E#Link l = start; while (l != stop) { next = l.getNext(); prev = l.getPrevious(); // tmp = l; l = l.getNext(); // tmp.setNext(prev); tmp.setPrevious(next); } // At this point l == stop and tmp is the but last element { if (got(tmp)) { tmpHead.setNext(tmp); stop.setPrevious(tmpHead); } start.setNext(stop); stop.setPrevious(start); } /** {@inheritDoc} */ public void shuffle(Random rand) { for (int i = 0; i < size; i++) { T#E#Link l = getLinkAt(rand.nextInt(size())); removeLink(l); add(l.getValue()); } } /** {@inheritDoc} */ public T#E#List subList(int begin, int end) { if (end < begin) { throw new IllegalArgumentException("begin index " + begin + " greater than end index " + end); } if (size < begin) { throw new IllegalArgumentException("begin index " + begin + " greater than last index " + size); } if (begin < 0) { throw new IndexOutOfBoundsException("begin index can not be < 0"); } if (end > size) { throw new IndexOutOfBoundsException("end index < " + size); } T#E#LinkedList ret = new T#E#LinkedList(); T#E#Link tmp = getLinkAt(begin); for (int i = begin; i < end; i++) { ret.add(tmp.getValue()); // copy tmp = tmp.getNext(); } return ret; } /** {@inheritDoc} */ public #e#[] toArray() { return toArray(new #e#[size], 0, size); } /** {@inheritDoc} */ public #e#[] toArray(int offset, int len) { return toArray(new #e#[len], offset, 0, len); } /** {@inheritDoc} */ public #e#[] toArray(#e#[] dest) { return toArray(dest, 0, size); } /** {@inheritDoc} */ public #e#[] toArray(#e#[] dest, int offset, int len) { return toArray(dest, offset, 0, len); } /** {@inheritDoc} */ public #e#[] toArray(#e#[] dest, int source_pos, int dest_pos, int len) { if (len == 0) { return dest; // nothing to copy } if (source_pos < 0 || source_pos >= size()) { throw new ArrayIndexOutOfBoundsException(source_pos); } T#E#Link tmp = getLinkAt(source_pos); for (int i = 0; i < len; i++) { dest[dest_pos + i] = tmp.getValue(); // copy tmp = tmp.getNext(); } return dest; } /** {@inheritDoc} */ public boolean forEach(T#E#Procedure procedure) { for (T#E#Link l = head; got(l); l = l.getNext()) { if (!procedure.execute(l.getValue())) return false; } return true; } /** {@inheritDoc} */ public boolean forEachDescending(T#E#Procedure procedure) { for (T#E#Link l = tail; got(l); l = l.getPrevious()) { if (!procedure.execute(l.getValue())) return false; } return true; } /** {@inheritDoc} */ public void sort() { sort(0, size); } /** {@inheritDoc} */ public void sort(int fromIndex, int toIndex) { T#E#List tmp = subList(fromIndex, toIndex); #e#[] vals = tmp.toArray(); Arrays.sort(vals); set(fromIndex, vals); } /** {@inheritDoc} */ public void fill(#e# val) { fill(0, size, val); } /** {@inheritDoc} */ public void fill(int fromIndex, int toIndex, #e# val) { if (fromIndex < 0) { throw new IndexOutOfBoundsException("begin index can not be < 0"); } T#E#Link l = getLinkAt(fromIndex); if (toIndex > size) { for (int i = fromIndex; i < size; i++) { l.setValue(val); l = l.getNext(); } for (int i = size; i < toIndex; i++) { add(val); } } else { for (int i = fromIndex; i < toIndex; i++) { l.setValue(val); l = l.getNext(); } } } /** {@inheritDoc} */ public int binarySearch(#e# value) { return binarySearch(value, 0, size()); } /** {@inheritDoc} */ public int binarySearch(#e# value, int fromIndex, int toIndex) { if (fromIndex < 0) { throw new IndexOutOfBoundsException("begin index can not be < 0"); } if (toIndex > size) { throw new IndexOutOfBoundsException("end index > size: " + toIndex + " > " + size); } if (toIndex < fromIndex) { return -(fromIndex+1); } T#E#Link middle; int mid; int from = fromIndex; T#E#Link fromLink = getLinkAt(fromIndex); int to = toIndex; while (from < to) { mid = (from + to) >>> 1; middle = getLink(fromLink, from, mid); if (middle.getValue() == value) return mid; if (middle.getValue() < value) { from = mid + 1; fromLink = middle.next; } else { to = mid - 1; } } return -(from + 1); } /** {@inheritDoc} */ public int indexOf(#e# value) { return indexOf(0, value); } /** {@inheritDoc} */ public int indexOf(int offset, #e# value) { int count = offset; for (T#E#Link l = getLinkAt(offset); got(l.getNext()); l = l.getNext()) { if (l.getValue() == value) return count; count++; } return -1; } /** {@inheritDoc} */ public int lastIndexOf(#e# value) { return lastIndexOf(0, value); } /** {@inheritDoc} */ public int lastIndexOf(int offset, #e# value) { if (isEmpty()) return -1; int last = -1; int count = offset; for (T#E#Link l = getLinkAt(offset); got(l.getNext()); l = l.getNext()) { if (l.getValue() == value) last = count; count++; } return last; } /** {@inheritDoc} */ public boolean contains(#e# value) { if (isEmpty()) return false; for (T#E#Link l = head; got(l); l = l.getNext()) { if (l.getValue() == value) return true; } return false; } /** {@inheritDoc} */ public T#E#Iterator iterator() { return new T#E#Iterator() { T#E#Link l = head; T#E#Link current; public #e# next() { if (no(l)) throw new NoSuchElementException(); #e# ret = l.getValue(); current = l; l = l.getNext(); return ret; } public boolean hasNext() { return got(l); } public void remove() { if (current == null) throw new IllegalStateException(); removeLink(current); current = null; } }; } /** {@inheritDoc} */ public T#E#List grep(T#E#Procedure condition) { T#E#List ret = new T#E#LinkedList(); for (T#E#Link l = head; got(l); l = l.getNext()) { if (condition.execute(l.getValue())) ret.add(l.getValue()); } return ret; } /** {@inheritDoc} */ public T#E#List inverseGrep(T#E#Procedure condition) { T#E#List ret = new T#E#LinkedList(); for (T#E#Link l = head; got(l); l = l.getNext()) { if (!condition.execute(l.getValue())) ret.add(l.getValue()); } return ret; } /** {@inheritDoc} */ public #e# max() { #e# ret = #EMIN#; if (isEmpty()) throw new IllegalStateException(); for (T#E#Link l = head; got(l); l = l.getNext()) { if (ret < l.getValue()) ret = l.getValue(); } return ret; } /** {@inheritDoc} */ public #e# min() { #e# ret = #EMAX#; if (isEmpty()) throw new IllegalStateException(); for (T#E#Link l = head; got(l); l = l.getNext()) { if (ret > l.getValue()) ret = l.getValue(); } return ret; } /** {@inheritDoc} */ public #e# sum() { #e# sum = 0; for (T#E#Link l = head; got(l); l = l.getNext()) { sum += l.getValue(); } return sum; } // // // static class T#E#Link { #e# value; T#E#Link previous; T#E#Link next; T#E#Link(#e# value) { this.value = value; } public #e# getValue() { return value; } public void setValue(#e# value) { this.value = value; } public T#E#Link getPrevious() { return previous; } public void setPrevious(T#E#Link previous) { this.previous = previous; } public T#E#Link getNext() { return next; } public void setNext(T#E#Link next) { this.next = next; } } class RemoveProcedure implements T#E#Procedure { boolean changed = false; /** * Executes this procedure. A false return value indicates that * the application executing this procedure should not invoke this * procedure again. * * @param value a value of type int * @return true if additional invocations of the procedure are * allowed. */ public boolean execute(#e# value) { if (remove(value)) changed = true; return true; } public boolean isChanged() { return changed; } } /** {@inheritDoc} */ public void writeExternal(ObjectOutput out) throws IOException { // VERSION out.writeByte(0); // NO_ENTRY_VALUE out.write#E#(no_entry_value); // ENTRIES out.writeInt(size); for (T#E#Iterator iterator = iterator(); iterator.hasNext();) { #e# next = iterator.next(); out.write#E#(next); } } /** {@inheritDoc} */ public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { // VERSION in.readByte(); // NO_ENTRY_VALUE no_entry_value = in.read#E#(); // ENTRIES int len = in.readInt(); for (int i = 0; i < len; i++) { add(in.read#E#()); } } static boolean got(Object ref) { return ref != null; } static boolean no(Object ref) { return ref == null; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; T#E#LinkedList that = (T#E#LinkedList) o; if (no_entry_value != that.no_entry_value) return false; if (size != that.size) return false; T#E#Iterator iterator = iterator(); T#E#Iterator thatIterator = that.iterator(); while (iterator.hasNext()) { if (!thatIterator.hasNext()) return false; if (iterator.next() != thatIterator.next()) return false; } return true; } @Override public int hashCode() { int result = HashFunctions.hash(no_entry_value); result = 31 * result + size; for (T#E#Iterator iterator = iterator(); iterator.hasNext();) { result = 31 * result + HashFunctions.hash(iterator.next()); } return result; } @Override public String toString() { final StringBuilder buf = new StringBuilder("{"); T#E#Iterator it = iterator(); while (it.hasNext()) { #e# next = it.next(); buf.append(next); if (it.hasNext()) buf.append(", "); } buf.append("}"); return buf.toString(); } } // T#E#LinkedList trove-3.0.3/templates/gnu/trove/list/array/0000755000175000017500000000000012000515265017635 5ustar ericherichtrove-3.0.3/templates/gnu/trove/list/array/_E_ArrayList.template0000644000175000017500000007005611763017634023733 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001, Eric D. Friedman All Rights Reserved. // Copyright (c) 2009, Rob Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.list.array; import gnu.trove.function.T#E#Function; import gnu.trove.list.T#E#List; import gnu.trove.procedure.T#E#Procedure; import gnu.trove.iterator.T#E#Iterator; import gnu.trove.T#E#Collection; import gnu.trove.impl.*; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.*; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// /** * A resizable, array-backed list of #e# primitives. */ public class T#E#ArrayList implements T#E#List, Externalizable { static final long serialVersionUID = 1L; /** the data of the list */ protected #e#[] _data; /** the index after the last entry in the list */ protected int _pos; /** the default capacity for new lists */ protected static final int DEFAULT_CAPACITY = Constants.DEFAULT_CAPACITY; /** the #e# value that represents null */ protected #e# no_entry_value; /** * Creates a new T#E#ArrayList instance with the * default capacity. */ @SuppressWarnings({"RedundantCast"}) public T#E#ArrayList() { this( DEFAULT_CAPACITY, ( #e# ) 0 ); } /** * Creates a new T#E#ArrayList instance with the * specified capacity. * * @param capacity an int value */ @SuppressWarnings({"RedundantCast"}) public T#E#ArrayList( int capacity ) { this( capacity, ( #e# ) 0 ); } /** * Creates a new T#E#ArrayList instance with the * specified capacity. * * @param capacity an int value * @param no_entry_value an #e# value that represents null. */ public T#E#ArrayList( int capacity, #e# no_entry_value ) { _data = new #e#[ capacity ]; _pos = 0; this.no_entry_value = no_entry_value; } /** * Creates a new T#E#ArrayList instance that contains * a copy of the collection passed to us. * * @param collection the collection to copy */ public T#E#ArrayList ( T#E#Collection collection ) { this( collection.size() ); addAll( collection ); } /** * Creates a new T#E#ArrayList instance whose * capacity is the length of values array and whose * initial contents are the specified values. *

* A defensive copy of the given values is held by the new instance. * * @param values an #e#[] value */ public T#E#ArrayList( #e#[] values ) { this( values.length ); add( values ); } protected T#E#ArrayList(#e#[] values, #e# no_entry_value, boolean wrap) { if (!wrap) throw new IllegalStateException("Wrong call"); if (values == null) throw new IllegalArgumentException("values can not be null"); _data = values; _pos = values.length; this.no_entry_value = no_entry_value; } /** * Returns a primitive List implementation that wraps around the given primitive array. *

* NOTE: mutating operation are allowed as long as the List does not grow. In that case * an IllegalStateException will be thrown * * @param values * @return */ public static T#E#ArrayList wrap(#e#[] values) { return wrap(values, ( #e# ) 0); } /** * Returns a primitive List implementation that wraps around the given primitive array. *

* NOTE: mutating operation are allowed as long as the List does not grow. In that case * an IllegalStateException will be thrown * * @param values * @param no_entry_value * @return */ public static T#E#ArrayList wrap(#e#[] values, #e# no_entry_value) { return new T#E#ArrayList(values, no_entry_value, true) { /** * Growing the wrapped external array is not allow */ @Override public void ensureCapacity(int capacity) { if (capacity > _data.length) throw new IllegalStateException("Can not grow ArrayList wrapped external array"); } }; } /** {@inheritDoc} */ public #e# getNoEntryValue() { return no_entry_value; } // sizing /** * Grow the internal array as needed to accommodate the specified number of elements. * The size of the array bytes on each resize unless capacity requires more than twice * the current capacity. */ public void ensureCapacity( int capacity ) { if ( capacity > _data.length ) { int newCap = Math.max( _data.length << 1, capacity ); #e#[] tmp = new #e#[ newCap ]; System.arraycopy( _data, 0, tmp, 0, _data.length ); _data = tmp; } } /** {@inheritDoc} */ public int size() { return _pos; } /** {@inheritDoc} */ public boolean isEmpty() { return _pos == 0; } /** * Sheds any excess capacity above and beyond the current size of the list. */ public void trimToSize() { if ( _data.length > size() ) { #e#[] tmp = new #e#[ size() ]; toArray( tmp, 0, tmp.length ); _data = tmp; } } // modifying /** {@inheritDoc} */ public boolean add( #e# val ) { ensureCapacity( _pos + 1 ); _data[ _pos++ ] = val; return true; } /** {@inheritDoc} */ public void add( #e#[] vals ) { add( vals, 0, vals.length ); } /** {@inheritDoc} */ public void add( #e#[] vals, int offset, int length ) { ensureCapacity( _pos + length ); System.arraycopy( vals, offset, _data, _pos, length ); _pos += length; } /** {@inheritDoc} */ public void insert( int offset, #e# value ) { if ( offset == _pos ) { add( value ); return; } ensureCapacity( _pos + 1 ); // shift right System.arraycopy( _data, offset, _data, offset + 1, _pos - offset ); // insert _data[ offset ] = value; _pos++; } /** {@inheritDoc} */ public void insert( int offset, #e#[] values ) { insert( offset, values, 0, values.length ); } /** {@inheritDoc} */ public void insert( int offset, #e#[] values, int valOffset, int len ) { if ( offset == _pos ) { add( values, valOffset, len ); return; } ensureCapacity( _pos + len ); // shift right System.arraycopy( _data, offset, _data, offset + len, _pos - offset ); // insert System.arraycopy( values, valOffset, _data, offset, len ); _pos += len; } /** {@inheritDoc} */ public #e# get( int offset ) { if ( offset >= _pos ) { throw new ArrayIndexOutOfBoundsException( offset ); } return _data[ offset ]; } /** * Returns the value at the specified offset without doing any bounds checking. */ public #e# getQuick( int offset ) { return _data[ offset ]; } /** {@inheritDoc} */ public #e# set( int offset, #e# val ) { if ( offset >= _pos ) { throw new ArrayIndexOutOfBoundsException( offset ); } #e# prev_val = _data[ offset ]; _data[ offset ] = val; return prev_val; } /** {@inheritDoc} */ public #e# replace( int offset, #e# val ) { if ( offset >= _pos ) { throw new ArrayIndexOutOfBoundsException( offset ); } #e# old = _data[ offset ]; _data[ offset ] = val; return old; } /** {@inheritDoc} */ public void set( int offset, #e#[] values ) { set( offset, values, 0, values.length ); } /** {@inheritDoc} */ public void set( int offset, #e#[] values, int valOffset, int length ) { if ( offset < 0 || offset + length > _pos ) { throw new ArrayIndexOutOfBoundsException( offset ); } System.arraycopy( values, valOffset, _data, offset, length ); } /** * Sets the value at the specified offset without doing any bounds checking. */ public void setQuick( int offset, #e# val ) { _data[ offset ] = val; } /** {@inheritDoc} */ public void clear() { clear( DEFAULT_CAPACITY ); } /** * Flushes the internal state of the list, setting the capacity of the empty list to * capacity. */ public void clear( int capacity ) { _data = new #e#[ capacity ]; _pos = 0; } /** * Sets the size of the list to 0, but does not change its capacity. This method can * be used as an alternative to the {@link #clear()} method if you want to recycle a * list without allocating new backing arrays. */ public void reset() { _pos = 0; Arrays.fill( _data, no_entry_value ); } /** * Sets the size of the list to 0, but does not change its capacity. This method can * be used as an alternative to the {@link #clear()} method if you want to recycle a * list without allocating new backing arrays. This method differs from * {@link #reset()} in that it does not clear the old values in the backing array. * Thus, it is possible for getQuick to return stale data if this method is used and * the caller is careless about bounds checking. */ public void resetQuick() { _pos = 0; } /** {@inheritDoc} */ public boolean remove( #e# value ) { for ( int index = 0; index < _pos; index++ ) { if ( value == _data[index] ) { remove( index, 1 ); return true; } } return false; } /** {@inheritDoc} */ public #e# removeAt( int offset ) { #e# old = get( offset ); remove( offset, 1 ); return old; } /** {@inheritDoc} */ public void remove( int offset, int length ) { if ( length == 0 ) return; if ( offset < 0 || offset >= _pos ) { throw new ArrayIndexOutOfBoundsException(offset); } if ( offset == 0 ) { // data at the front System.arraycopy( _data, length, _data, 0, _pos - length ); } else if ( _pos - length == offset ) { // no copy to make, decrementing pos "deletes" values at // the end } else { // data in the middle System.arraycopy( _data, offset + length, _data, offset, _pos - ( offset + length ) ); } _pos -= length; // no need to clear old values beyond _pos, because this is a // primitive collection and 0 takes as much room as any other // value } /** {@inheritDoc} */ public T#E#Iterator iterator() { return new T#E#ArrayIterator( 0 ); } /** {@inheritDoc} */ public boolean containsAll( Collection collection ) { for ( Object element : collection ) { if ( element instanceof #ET# ) { #e# c = ( ( #ET# ) element ).#e#Value(); if ( ! contains( c ) ) { return false; } } else { return false; } } return true; } /** {@inheritDoc} */ public boolean containsAll( T#E#Collection collection ) { if ( this == collection ) { return true; } T#E#Iterator iter = collection.iterator(); while ( iter.hasNext() ) { #e# element = iter.next(); if ( ! contains( element ) ) { return false; } } return true; } /** {@inheritDoc} */ public boolean containsAll( #e#[] array ) { for ( int i = array.length; i-- > 0; ) { if ( ! contains( array[i] ) ) { return false; } } return true; } /** {@inheritDoc} */ public boolean addAll( Collection collection ) { boolean changed = false; for ( #ET# element : collection ) { #e# e = element.#e#Value(); if ( add( e ) ) { changed = true; } } return changed; } /** {@inheritDoc} */ public boolean addAll( T#E#Collection collection ) { boolean changed = false; T#E#Iterator iter = collection.iterator(); while ( iter.hasNext() ) { #e# element = iter.next(); if ( add( element ) ) { changed = true; } } return changed; } /** {@inheritDoc} */ public boolean addAll( #e#[] array ) { boolean changed = false; for ( #e# element : array ) { if ( add( element ) ) { changed = true; } } return changed; } /** {@inheritDoc} */ @SuppressWarnings({"SuspiciousMethodCalls"}) public boolean retainAll( Collection collection ) { boolean modified = false; T#E#Iterator iter = iterator(); while ( iter.hasNext() ) { if ( ! collection.contains( #ET#.valueOf ( iter.next() ) ) ) { iter.remove(); modified = true; } } return modified; } /** {@inheritDoc} */ public boolean retainAll( T#E#Collection collection ) { if ( this == collection ) { return false; } boolean modified = false; T#E#Iterator iter = iterator(); while ( iter.hasNext() ) { if ( ! collection.contains( iter.next() ) ) { iter.remove(); modified = true; } } return modified; } /** {@inheritDoc} */ public boolean retainAll( #e#[] array ) { boolean changed = false; Arrays.sort( array ); #e#[] data = _data; for ( int i = _pos; i-- > 0; ) { if ( Arrays.binarySearch( array, data[i] ) < 0 ) { remove( i, 1 ); changed = true; } } return changed; } /** {@inheritDoc} */ public boolean removeAll( Collection collection ) { boolean changed = false; for ( Object element : collection ) { if ( element instanceof #ET# ) { #e# c = ( ( #ET# ) element ).#e#Value(); if ( remove( c ) ) { changed = true; } } } return changed; } /** {@inheritDoc} */ public boolean removeAll( T#E#Collection collection ) { if ( collection == this ) { clear(); return true; } boolean changed = false; T#E#Iterator iter = collection.iterator(); while ( iter.hasNext() ) { #e# element = iter.next(); if ( remove( element ) ) { changed = true; } } return changed; } /** {@inheritDoc} */ public boolean removeAll( #e#[] array ) { boolean changed = false; for ( int i = array.length; i-- > 0; ) { if ( remove(array[i]) ) { changed = true; } } return changed; } /** {@inheritDoc} */ public void transformValues( T#E#Function function ) { for ( int i = _pos; i-- > 0; ) { _data[ i ] = function.execute( _data[ i ] ); } } /** {@inheritDoc} */ public void reverse() { reverse( 0, _pos ); } /** {@inheritDoc} */ public void reverse( int from, int to ) { if ( from == to ) { return; // nothing to do } if ( from > to ) { throw new IllegalArgumentException( "from cannot be greater than to" ); } for ( int i = from, j = to - 1; i < j; i++, j-- ) { swap( i, j ); } } /** {@inheritDoc} */ public void shuffle( Random rand ) { for ( int i = _pos; i-- > 1; ) { swap( i, rand.nextInt( i ) ); } } /** * Swap the values at offsets i and j. * * @param i an offset into the data array * @param j an offset into the data array */ private void swap( int i, int j ) { #e# tmp = _data[ i ]; _data[ i ] = _data[ j ]; _data[ j ] = tmp; } // copying /** {@inheritDoc} */ public T#E#List subList( int begin, int end ) { if ( end < begin ) { throw new IllegalArgumentException( "end index " + end + " greater than begin index " + begin ); } if ( begin < 0 ) { throw new IndexOutOfBoundsException( "begin index can not be < 0" ); } if ( end > _data.length ) { throw new IndexOutOfBoundsException( "end index < " + _data.length ); } T#E#ArrayList list = new T#E#ArrayList( end - begin ); for ( int i = begin; i < end; i++ ) { list.add( _data[ i ] ); } return list; } /** {@inheritDoc} */ public #e#[] toArray() { return toArray( 0, _pos ); } /** {@inheritDoc} */ public #e#[] toArray( int offset, int len ) { #e#[] rv = new #e#[ len ]; toArray( rv, offset, len ); return rv; } /** {@inheritDoc} */ public #e#[] toArray( #e#[] dest ) { int len = dest.length; if ( dest.length > _pos ) { len = _pos; dest[len] = no_entry_value; } toArray( dest, 0, len ); return dest; } /** {@inheritDoc} */ public #e#[] toArray( #e#[] dest, int offset, int len ) { if ( len == 0 ) { return dest; // nothing to copy } if ( offset < 0 || offset >= _pos ) { throw new ArrayIndexOutOfBoundsException( offset ); } System.arraycopy( _data, offset, dest, 0, len ); return dest; } /** {@inheritDoc} */ public #e#[] toArray( #e#[] dest, int source_pos, int dest_pos, int len ) { if ( len == 0 ) { return dest; // nothing to copy } if ( source_pos < 0 || source_pos >= _pos ) { throw new ArrayIndexOutOfBoundsException( source_pos ); } System.arraycopy( _data, source_pos, dest, dest_pos, len ); return dest; } // comparing /** {@inheritDoc} */ @Override public boolean equals( Object other ) { if ( other == this ) { return true; } else if ( other instanceof T#E#ArrayList ) { T#E#ArrayList that = ( T#E#ArrayList )other; if ( that.size() != this.size() ) return false; else { for ( int i = _pos; i-- > 0; ) { if ( this._data[ i ] != that._data[ i ] ) { return false; } } return true; } } else return false; } /** {@inheritDoc} */ @Override public int hashCode() { int h = 0; for ( int i = _pos; i-- > 0; ) { h += HashFunctions.hash( _data[ i ] ); } return h; } // procedures /** {@inheritDoc} */ public boolean forEach( T#E#Procedure procedure ) { for ( int i = 0; i < _pos; i++ ) { if ( !procedure.execute( _data[ i ] ) ) { return false; } } return true; } /** {@inheritDoc} */ public boolean forEachDescending( T#E#Procedure procedure ) { for ( int i = _pos; i-- > 0; ) { if ( !procedure.execute( _data[ i ] ) ) { return false; } } return true; } // sorting /** {@inheritDoc} */ public void sort() { Arrays.sort( _data, 0, _pos ); } /** {@inheritDoc} */ public void sort( int fromIndex, int toIndex ) { Arrays.sort( _data, fromIndex, toIndex ); } // filling /** {@inheritDoc} */ public void fill( #e# val ) { Arrays.fill( _data, 0, _pos, val ); } /** {@inheritDoc} */ public void fill( int fromIndex, int toIndex, #e# val ) { if ( toIndex > _pos ) { ensureCapacity( toIndex ); _pos = toIndex; } Arrays.fill( _data, fromIndex, toIndex, val ); } // searching /** {@inheritDoc} */ public int binarySearch( #e# value ) { return binarySearch( value, 0, _pos ); } /** {@inheritDoc} */ public int binarySearch(#e# value, int fromIndex, int toIndex) { if ( fromIndex < 0 ) { throw new ArrayIndexOutOfBoundsException( fromIndex ); } if ( toIndex > _pos ) { throw new ArrayIndexOutOfBoundsException( toIndex ); } int low = fromIndex; int high = toIndex - 1; while ( low <= high ) { int mid = ( low + high ) >>> 1; #e# midVal = _data[ mid ]; if ( midVal < value ) { low = mid + 1; } else if ( midVal > value ) { high = mid - 1; } else { return mid; // value found } } return -( low + 1 ); // value not found. } /** {@inheritDoc} */ public int indexOf( #e# value ) { return indexOf( 0, value ); } /** {@inheritDoc} */ public int indexOf( int offset, #e# value ) { for ( int i = offset; i < _pos; i++ ) { if ( _data[ i ] == value ) { return i; } } return -1; } /** {@inheritDoc} */ public int lastIndexOf( #e# value ) { return lastIndexOf( _pos, value ); } /** {@inheritDoc} */ public int lastIndexOf( int offset, #e# value ) { for ( int i = offset; i-- > 0; ) { if ( _data[ i ] == value ) { return i; } } return -1; } /** {@inheritDoc} */ public boolean contains( #e# value ) { return lastIndexOf( value ) >= 0; } /** {@inheritDoc} */ public T#E#List grep( T#E#Procedure condition ) { T#E#ArrayList list = new T#E#ArrayList(); for ( int i = 0; i < _pos; i++ ) { if ( condition.execute( _data[ i ] ) ) { list.add( _data[ i ] ); } } return list; } /** {@inheritDoc} */ public T#E#List inverseGrep( T#E#Procedure condition ) { T#E#ArrayList list = new T#E#ArrayList(); for ( int i = 0; i < _pos; i++ ) { if ( !condition.execute( _data[ i ] ) ) { list.add( _data[ i ] ); } } return list; } /** {@inheritDoc} */ public #e# max() { if ( size() == 0 ) { throw new IllegalStateException("cannot find maximum of an empty list"); } #e# max = #EMIN#; for ( int i = 0; i < _pos; i++ ) { if ( _data[ i ] > max ) { max = _data[ i ]; } } return max; } /** {@inheritDoc} */ public #e# min() { if ( size() == 0 ) { throw new IllegalStateException( "cannot find minimum of an empty list" ); } #e# min = #EMAX#; for ( int i = 0; i < _pos; i++ ) { if ( _data[i] < min ) { min = _data[i]; } } return min; } /** {@inheritDoc} */ public #e# sum() { #e# sum = 0; for ( int i = 0; i < _pos; i++ ) { sum += _data[ i ]; } return sum; } // stringification /** {@inheritDoc} */ @Override public String toString() { final StringBuilder buf = new StringBuilder( "{" ); for ( int i = 0, end = _pos - 1; i < end; i++ ) { buf.append( _data[ i ] ); buf.append( ", " ); } if ( size() > 0 ) { buf.append( _data[ _pos - 1 ] ); } buf.append( "}" ); return buf.toString(); } /** T#E#ArrayList iterator */ class T#E#ArrayIterator implements T#E#Iterator { /** Index of element to be returned by subsequent call to next. */ private int cursor = 0; /** * Index of element returned by most recent call to next or * previous. Reset to -1 if this element is deleted by a call * to remove. */ int lastRet = -1; T#E#ArrayIterator( int index ) { cursor = index; } /** {@inheritDoc} */ public boolean hasNext() { return cursor < size(); } /** {@inheritDoc} */ public #e# next() { try { #e# next = get( cursor ); lastRet = cursor++; return next; } catch ( IndexOutOfBoundsException e ) { throw new NoSuchElementException(); } } /** {@inheritDoc} */ public void remove() { if ( lastRet == -1 ) throw new IllegalStateException(); try { T#E#ArrayList.this.remove( lastRet, 1); if ( lastRet < cursor ) cursor--; lastRet = -1; } catch ( IndexOutOfBoundsException e ) { throw new ConcurrentModificationException(); } } } public void writeExternal( ObjectOutput out ) throws IOException { // VERSION out.writeByte( 0 ); // POSITION out.writeInt( _pos ); // NO_ENTRY_VALUE out.write#E#( no_entry_value ); // ENTRIES int len = _data.length; out.writeInt( len ); for( int i = 0; i < len; i++ ) { out.write#E#( _data[ i ] ); } } public void readExternal( ObjectInput in ) throws IOException, ClassNotFoundException { // VERSION in.readByte(); // POSITION _pos = in.readInt(); // NO_ENTRY_VALUE no_entry_value = in.read#E#(); // ENTRIES int len = in.readInt(); _data = new #e#[ len ]; for( int i = 0; i < len; i++ ) { _data[ i ] = in.read#E#(); } } } // T#E#ArrayList trove-3.0.3/templates/gnu/trove/impl/0000755000175000017500000000000011763017634016521 5ustar ericherichtrove-3.0.3/templates/gnu/trove/impl/sync/0000755000175000017500000000000012000515265017461 5ustar ericherichtrove-3.0.3/templates/gnu/trove/impl/sync/Synchronized_K__V_Map.template0000644000175000017500000001357311763017634025415 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2008, Robert D. Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.impl.sync; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // THIS IS AN IMPLEMENTATION CLASS. DO NOT USE DIRECTLY! // // Access to these methods should be through TCollections // //////////////////////////////////////////////////////////// import gnu.trove.iterator.*; import gnu.trove.procedure.*; import gnu.trove.set.*; import gnu.trove.list.*; import gnu.trove.function.*; import gnu.trove.map.*; import gnu.trove.*; import java.util.Collection; import java.util.Iterator; import java.util.Set; import java.util.Map; import java.util.RandomAccess; import java.util.Random; import java.io.Serializable; import java.io.ObjectOutputStream; import java.io.IOException; public class TSynchronized#K##V#Map implements T#K##V#Map, Serializable { private static final long serialVersionUID = 1978198479659022715L; private final T#K##V#Map m; // Backing Map final Object mutex; // Object on which to synchronize public TSynchronized#K##V#Map( T#K##V#Map m ) { if ( m == null ) throw new NullPointerException(); this.m = m; mutex = this; } public TSynchronized#K##V#Map( T#K##V#Map m, Object mutex ) { this.m = m; this.mutex = mutex; } public int size() { synchronized( mutex ) { return m.size(); } } public boolean isEmpty(){ synchronized( mutex ) { return m.isEmpty(); } } public boolean containsKey( #k# key ) { synchronized( mutex ) { return m.containsKey( key ); } } public boolean containsValue( #v# value ){ synchronized( mutex ) { return m.containsValue( value ); } } public #v# get( #k# key ) { synchronized( mutex ) { return m.get( key ); } } public #v# put( #k# key, #v# value ) { synchronized( mutex ) { return m.put( key, value ); } } public #v# remove( #k# key ) { synchronized( mutex ) { return m.remove( key ); } } public void putAll( Map map ) { synchronized( mutex ) { m.putAll( map ); } } public void putAll( T#K##V#Map map ) { synchronized( mutex ) { m.putAll( map ); } } public void clear() { synchronized( mutex ) { m.clear(); } } private transient T#K#Set keySet = null; private transient T#V#Collection values = null; public T#K#Set keySet() { synchronized( mutex ) { if ( keySet == null ) keySet = new TSynchronized#K#Set( m.keySet(), mutex ); return keySet; } } public #k#[] keys() { synchronized( mutex ) { return m.keys(); } } public #k#[] keys( #k#[] array ) { synchronized( mutex ) { return m.keys( array ); } } public T#V#Collection valueCollection() { synchronized( mutex ) { if ( values == null ) values = new TSynchronized#V#Collection( m.valueCollection(), mutex ); return values; } } public #v#[] values() { synchronized( mutex ) { return m.values(); } } public #v#[] values( #v#[] array ) { synchronized( mutex ) { return m.values( array ); } } public T#K##V#Iterator iterator() { return m.iterator(); // Must be manually synched by user! } // these are unchanging over the life of the map, no need to lock public #k# getNoEntryKey() { return m.getNoEntryKey(); } public #v# getNoEntryValue() { return m.getNoEntryValue(); } public #v# putIfAbsent( #k# key, #v# value ) { synchronized( mutex ) { return m.putIfAbsent( key, value ); } } public boolean forEachKey( T#K#Procedure procedure ) { synchronized( mutex ) { return m.forEachKey( procedure ); } } public boolean forEachValue( T#V#Procedure procedure ) { synchronized( mutex ) { return m.forEachValue( procedure ); } } public boolean forEachEntry( T#K##V#Procedure procedure ) { synchronized( mutex ) { return m.forEachEntry( procedure ); } } public void transformValues( T#V#Function function ) { synchronized( mutex ) { m.transformValues( function ); } } public boolean retainEntries( T#K##V#Procedure procedure ) { synchronized( mutex ) { return m.retainEntries( procedure ); } } public boolean increment( #k# key ) { synchronized( mutex ) { return m.increment( key ); } } public boolean adjustValue( #k# key, #v# amount ) { synchronized( mutex ) { return m.adjustValue( key, amount ); } } public #v# adjustOrPutValue( #k# key, #v# adjust_amount, #v# put_amount ) { synchronized( mutex ) { return m.adjustOrPutValue( key, adjust_amount, put_amount ); } } public boolean equals( Object o ) { synchronized( mutex ) { return m.equals( o ); } } public int hashCode() { synchronized( mutex ) { return m.hashCode(); } } public String toString() { synchronized( mutex ) { return m.toString(); } } private void writeObject( ObjectOutputStream s ) throws IOException { synchronized( mutex ) { s.defaultWriteObject(); } } } trove-3.0.3/templates/gnu/trove/impl/sync/Synchronized_E_Collection.template0000644000175000017500000001154011763017634026331 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2008, Robert D. Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.impl.sync; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // THIS IS AN IMPLEMENTATION CLASS. DO NOT USE DIRECTLY! // // Access to these methods should be through TCollections // //////////////////////////////////////////////////////////// import gnu.trove.iterator.*; import gnu.trove.procedure.*; import gnu.trove.set.*; import gnu.trove.list.*; import gnu.trove.function.*; import gnu.trove.map.*; import gnu.trove.*; import java.util.Collection; import java.util.Iterator; import java.util.Set; import java.util.Map; import java.util.RandomAccess; import java.util.Random; import java.io.Serializable; import java.io.ObjectOutputStream; import java.io.IOException; public class TSynchronized#E#Collection implements T#E#Collection, Serializable { private static final long serialVersionUID = 3053995032091335093L; final T#E#Collection c; // Backing Collection final Object mutex; // Object on which to synchronize public TSynchronized#E#Collection( T#E#Collection c ) { if ( c == null ) throw new NullPointerException(); this.c = c; mutex = this; } public TSynchronized#E#Collection( T#E#Collection c, Object mutex ) { this.c = c; this.mutex = mutex; } public int size() { synchronized( mutex ) { return c.size(); } } public boolean isEmpty() { synchronized( mutex ) { return c.isEmpty(); } } public boolean contains( #e# o ) { synchronized( mutex ) { return c.contains( o ); } } public #e#[] toArray() { synchronized( mutex ) { return c.toArray(); } } public #e#[] toArray( #e#[] a ) { synchronized( mutex ) { return c.toArray( a ); } } public T#E#Iterator iterator() { return c.iterator(); // Must be manually synched by user! } public boolean add( #e# e ) { synchronized (mutex ) { return c.add( e ); } } public boolean remove( #e# o ) { synchronized( mutex ) { return c.remove( o ); } } public boolean containsAll( Collection coll ) { synchronized( mutex ) { return c.containsAll( coll );} } public boolean containsAll( T#E#Collection coll ) { synchronized( mutex ) { return c.containsAll( coll );} } public boolean containsAll( #e#[] array ) { synchronized( mutex ) { return c.containsAll( array );} } public boolean addAll( Collection coll ) { synchronized( mutex ) { return c.addAll( coll ); } } public boolean addAll( T#E#Collection coll ) { synchronized( mutex ) { return c.addAll( coll ); } } public boolean addAll( #e#[] array ) { synchronized( mutex ) { return c.addAll( array ); } } public boolean removeAll( Collection coll ) { synchronized( mutex ) { return c.removeAll( coll ); } } public boolean removeAll( T#E#Collection coll ) { synchronized( mutex ) { return c.removeAll( coll ); } } public boolean removeAll( #e#[] array ) { synchronized( mutex ) { return c.removeAll( array ); } } public boolean retainAll( Collection coll ) { synchronized( mutex ) { return c.retainAll( coll ); } } public boolean retainAll( T#E#Collection coll ) { synchronized( mutex ) { return c.retainAll( coll ); } } public boolean retainAll( #e#[] array ) { synchronized( mutex ) { return c.retainAll( array ); } } public #e# getNoEntryValue() { return c.getNoEntryValue(); } public boolean forEach( T#E#Procedure procedure ) { synchronized( mutex ) { return c.forEach( procedure ); } } public void clear() { synchronized( mutex ) { c.clear(); } } public String toString() { synchronized( mutex ) { return c.toString(); } } private void writeObject( ObjectOutputStream s ) throws IOException { synchronized( mutex ) { s.defaultWriteObject(); } } }trove-3.0.3/templates/gnu/trove/impl/sync/SynchronizedObject_E_Map.template0000644000175000017500000001363211763017634026106 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2008, Robert D. Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.impl.sync; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // THIS IS AN IMPLEMENTATION CLASS. DO NOT USE DIRECTLY! // // Access to these methods should be through TCollections // //////////////////////////////////////////////////////////// import gnu.trove.iterator.*; import gnu.trove.procedure.*; import gnu.trove.set.*; import gnu.trove.list.*; import gnu.trove.function.*; import gnu.trove.map.*; import gnu.trove.*; import java.util.Collection; import java.util.Iterator; import java.util.Set; import java.util.Map; import java.util.RandomAccess; import java.util.Random; import java.io.Serializable; import java.io.ObjectOutputStream; import java.io.IOException; public class TSynchronizedObject#E#Map implements TObject#E#Map, Serializable { private static final long serialVersionUID = 1978198479659022715L; private final TObject#E#Map m; // Backing Map final Object mutex; // Object on which to synchronize public TSynchronizedObject#E#Map( TObject#E#Map m ) { if ( m == null ) throw new NullPointerException(); this.m = m; mutex = this; } public TSynchronizedObject#E#Map( TObject#E#Map m, Object mutex ) { this.m = m; this.mutex = mutex; } public int size() { synchronized( mutex ) { return m.size(); } } public boolean isEmpty(){ synchronized( mutex ) { return m.isEmpty(); } } public boolean containsKey( Object key ) { synchronized( mutex ) { return m.containsKey( key ); } } public boolean containsValue( #e# value ){ synchronized( mutex ) { return m.containsValue( value ); } } public #e# get( Object key ) { synchronized( mutex ) { return m.get( key ); } } public #e# put( K key, #e# value ) { synchronized( mutex ) { return m.put( key, value ); } } public #e# remove( Object key ) { synchronized( mutex ) { return m.remove( key ); } } public void putAll( Map map ) { synchronized( mutex ) { m.putAll( map ); } } public void putAll( TObject#E#Map map ) { synchronized( mutex ) { m.putAll( map ); } } public void clear() { synchronized( mutex ) { m.clear(); } } private transient Set keySet = null; private transient T#E#Collection values = null; public Set keySet() { synchronized( mutex ) { if ( keySet == null ) { keySet = new SynchronizedSet( m.keySet(), mutex ); } return keySet; } } public Object[] keys() { synchronized( mutex ) { return m.keys(); } } public K[] keys( K[] array ) { synchronized( mutex ) { return m.keys( array ); } } public T#E#Collection valueCollection() { synchronized( mutex ) { if ( values == null ) values = new TSynchronized#E#Collection( m.valueCollection(), mutex ); return values; } } public #e#[] values() { synchronized( mutex ) { return m.values(); } } public #e#[] values( #e#[] array ) { synchronized( mutex ) { return m.values( array ); } } public TObject#E#Iterator iterator() { return m.iterator(); // Must be manually synched by user! } // unchanging over the life of the map, no need to lock public #e# getNoEntryValue() { return m.getNoEntryValue(); } public #e# putIfAbsent( K key, #e# value ) { synchronized( mutex ) { return m.putIfAbsent( key, value ); } } public boolean forEachKey( TObjectProcedure procedure ) { synchronized( mutex ) { return m.forEachKey( procedure ); } } public boolean forEachValue( T#E#Procedure procedure ) { synchronized( mutex ) { return m.forEachValue( procedure ); } } public boolean forEachEntry( TObject#E#Procedure procedure ) { synchronized( mutex ) { return m.forEachEntry( procedure ); } } public void transformValues( T#E#Function function ) { synchronized( mutex ) { m.transformValues( function ); } } public boolean retainEntries( TObject#E#Procedure procedure ) { synchronized( mutex ) { return m.retainEntries( procedure ); } } public boolean increment( K key ) { synchronized( mutex ) { return m.increment( key ); } } public boolean adjustValue( K key, #e# amount ) { synchronized( mutex ) { return m.adjustValue( key, amount ); } } public #e# adjustOrPutValue( K key, #e# adjust_amount, #e# put_amount ) { synchronized( mutex ) { return m.adjustOrPutValue( key, adjust_amount, put_amount ); } } public boolean equals( Object o ) { synchronized( mutex ) { return m.equals( o ); } } public int hashCode() { synchronized( mutex ) { return m.hashCode(); } } public String toString() { synchronized( mutex ) { return m.toString(); } } private void writeObject( ObjectOutputStream s ) throws IOException { synchronized( mutex ) { s.defaultWriteObject(); } } } trove-3.0.3/templates/gnu/trove/impl/sync/Synchronized_E_List.template0000644000175000017500000001677111763017634025164 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2008, Robert D. Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.impl.sync; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // THIS IS AN IMPLEMENTATION CLASS. DO NOT USE DIRECTLY! // // Access to these methods should be through TCollections // //////////////////////////////////////////////////////////// import gnu.trove.iterator.*; import gnu.trove.procedure.*; import gnu.trove.set.*; import gnu.trove.list.*; import gnu.trove.function.*; import gnu.trove.map.*; import gnu.trove.*; import java.util.Collection; import java.util.Iterator; import java.util.Set; import java.util.Map; import java.util.RandomAccess; import java.util.Random; import java.io.Serializable; import java.io.ObjectOutputStream; import java.io.IOException; public class TSynchronized#E#List extends TSynchronized#E#Collection implements T#E#List { static final long serialVersionUID = -7754090372962971524L; final T#E#List list; public TSynchronized#E#List( T#E#List list ) { super( list ); this.list = list; } public TSynchronized#E#List( T#E#List list, Object mutex ) { super( list, mutex ); this.list = list; } public boolean equals( Object o ) { synchronized( mutex ) { return list.equals( o ); } } public int hashCode() { synchronized( mutex ) { return list.hashCode(); } } public #e# get( int index ) { synchronized( mutex ) { return list.get( index ); } } public #e# set( int index, #e# element) { synchronized( mutex ) { return list.set( index, element ); } } public void set( int offset, #e#[] values ) { synchronized( mutex ) { list.set( offset, values ); } } public void set( int offset, #e#[] values, int valOffset, int length ) { synchronized( mutex ) { list.set( offset, values, valOffset, length ); } } public #e# replace( int offset, #e# val ) { synchronized( mutex ) { return list.replace( offset, val ); } } public void remove( int offset, int length ) { synchronized( mutex ) { list.remove( offset, length ); } } public #e# removeAt( int offset ) { synchronized( mutex ) { return list.removeAt( offset ); } } public void add( #e#[] vals ) { synchronized( mutex ) { list.add( vals ); } } public void add( #e#[] vals, int offset, int length ) { synchronized( mutex ) { list.add( vals, offset, length ); } } public void insert( int offset, #e# value ) { synchronized( mutex ) { list.insert( offset, value ); } } public void insert( int offset, #e#[] values ) { synchronized( mutex ) { list.insert( offset, values ); } } public void insert( int offset, #e#[] values, int valOffset, int len ) { synchronized( mutex ) { list.insert( offset, values, valOffset, len ); } } public int indexOf( #e# o ) { synchronized( mutex ) { return list.indexOf( o ); } } public int lastIndexOf( #e# o ) { synchronized( mutex ) { return list.lastIndexOf( o ); } } // public TList#E#Iterator listIterator() { // return list.listIterator(); // Must be manually synched by user // } // public TList#E#Iterator listIterator( int index ) { // return list.listIterator( index ); // Must be manually synched by user // } public T#E#List subList( int fromIndex, int toIndex ) { synchronized( mutex ) { return new TSynchronized#E#List( list.subList( fromIndex, toIndex ), mutex ); } } public #e#[] toArray( int offset, int len ) { synchronized( mutex ) { return list.toArray( offset, len ); } } public #e#[] toArray( #e#[] dest, int offset, int len ) { synchronized( mutex ) { return list.toArray( dest, offset, len ); } } public #e#[] toArray( #e#[] dest, int source_pos, int dest_pos, int len ) { synchronized( mutex ) { return list.toArray( dest, source_pos, dest_pos, len ); } } public int indexOf( int offset, #e# value ) { synchronized( mutex ) { return list.indexOf( offset, value ); } } public int lastIndexOf( int offset, #e# value ) { synchronized( mutex ) { return list.lastIndexOf( offset, value ); } } public void fill( #e# val ) { synchronized( mutex ) { list.fill( val ); } } public void fill( int fromIndex, int toIndex, #e# val ) { synchronized( mutex ) { list.fill( fromIndex, toIndex, val ); } } public void reverse() { synchronized( mutex ) { list.reverse(); } } public void reverse( int from, int to ) { synchronized( mutex ) { list.reverse( from, to ); } } public void shuffle( Random rand ) { synchronized( mutex ) { list.shuffle( rand ); } } public void sort() { synchronized( mutex ) { list.sort(); } } public void sort( int fromIndex, int toIndex ) { synchronized( mutex ) { list.sort( fromIndex, toIndex ); } } public int binarySearch( #e# value ) { synchronized( mutex ) { return list.binarySearch( value ); } } public int binarySearch( #e# value, int fromIndex, int toIndex ) { synchronized( mutex ) { return list.binarySearch( value, fromIndex, toIndex ); } } public T#E#List grep( T#E#Procedure condition ) { synchronized( mutex ) { return list.grep( condition ); } } public T#E#List inverseGrep( T#E#Procedure condition ) { synchronized( mutex ) { return list.inverseGrep( condition ); } } public #e# max() { synchronized( mutex ) { return list.max(); } } public #e# min() { synchronized( mutex ) { return list.min(); } } public #e# sum() { synchronized( mutex ) { return list.sum(); } } public boolean forEachDescending( T#E#Procedure procedure ) { synchronized( mutex ) { return list.forEachDescending( procedure ); } } public void transformValues( T#E#Function function ) { synchronized( mutex ) { list.transformValues( function ); } } /** * SynchronizedRandomAccessList instances are serialized as * SynchronizedList instances to allow them to be deserialized * in pre-1.4 JREs (which do not have SynchronizedRandomAccessList). * This method inverts the transformation. As a beneficial * side-effect, it also grafts the RandomAccess marker onto * SynchronizedList instances that were serialized in pre-1.4 JREs. * * Note: Unfortunately, SynchronizedRandomAccessList instances * serialized in 1.4.1 and deserialized in 1.4 will become * SynchronizedList instances, as this method was missing in 1.4. */ private Object readResolve() { return ( list instanceof RandomAccess ? new TSynchronizedRandomAccess#E#List( list ) : this ); } } trove-3.0.3/templates/gnu/trove/impl/sync/Synchronized_E_Set.template0000644000175000017500000000455611763017634025002 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2008, Robert D. Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.impl.sync; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // THIS IS AN IMPLEMENTATION CLASS. DO NOT USE DIRECTLY! // // Access to these methods should be through TCollections // //////////////////////////////////////////////////////////// import gnu.trove.iterator.*; import gnu.trove.procedure.*; import gnu.trove.set.*; import gnu.trove.list.*; import gnu.trove.function.*; import gnu.trove.map.*; import gnu.trove.*; import java.util.Collection; import java.util.Iterator; import java.util.Set; import java.util.Map; import java.util.RandomAccess; import java.util.Random; import java.io.Serializable; import java.io.ObjectOutputStream; import java.io.IOException; public class TSynchronized#E#Set extends TSynchronized#E#Collection implements T#E#Set { private static final long serialVersionUID = 487447009682186044L; public TSynchronized#E#Set( T#E#Set s ) { super( s ); } public TSynchronized#E#Set( T#E#Set s, Object mutex ) { super( s, mutex ); } public boolean equals( Object o ) { synchronized( mutex ) { return c.equals( o ); } } public int hashCode() { synchronized( mutex ) { return c.hashCode(); } } } trove-3.0.3/templates/gnu/trove/impl/sync/SynchronizedRandomAccess_E_List.template0000644000175000017500000000535611763017634027444 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2008, Robert D. Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.impl.sync; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // THIS IS AN IMPLEMENTATION CLASS. DO NOT USE DIRECTLY! // // Access to these methods should be through TCollections // //////////////////////////////////////////////////////////// import gnu.trove.iterator.*; import gnu.trove.procedure.*; import gnu.trove.set.*; import gnu.trove.list.*; import gnu.trove.function.*; import gnu.trove.map.*; import gnu.trove.*; import java.util.Collection; import java.util.Iterator; import java.util.Set; import java.util.Map; import java.util.RandomAccess; import java.util.Random; import java.io.Serializable; import java.io.ObjectOutputStream; import java.io.IOException; public class TSynchronizedRandomAccess#E#List extends TSynchronized#E#List implements RandomAccess { static final long serialVersionUID = 1530674583602358482L; public TSynchronizedRandomAccess#E#List( T#E#List list ) { super( list ); } public TSynchronizedRandomAccess#E#List( T#E#List list, Object mutex ) { super( list, mutex ); } public T#E#List subList( int fromIndex, int toIndex ) { synchronized( mutex ) { return new TSynchronizedRandomAccess#E#List( list.subList( fromIndex, toIndex ), mutex ); } } /** * Allows instances to be deserialized in pre-1.4 JREs (which do * not have SynchronizedRandomAccessList). SynchronizedList has * a readResolve method that inverts this transformation upon * deserialization. */ private Object writeReplace() { return new TSynchronized#E#List( list ); } } trove-3.0.3/templates/gnu/trove/impl/sync/Synchronized_E_ObjectMap.template0000644000175000017500000001311211763017634026077 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2008, Robert D. Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.impl.sync; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // THIS IS AN IMPLEMENTATION CLASS. DO NOT USE DIRECTLY! // // Access to these methods should be through TCollections // //////////////////////////////////////////////////////////// import gnu.trove.iterator.*; import gnu.trove.procedure.*; import gnu.trove.set.*; import gnu.trove.list.*; import gnu.trove.function.*; import gnu.trove.map.*; import gnu.trove.*; import java.util.Collection; import java.util.Iterator; import java.util.Set; import java.util.Map; import java.util.RandomAccess; import java.util.Random; import java.io.Serializable; import java.io.ObjectOutputStream; import java.io.IOException; public class TSynchronized#E#ObjectMap implements T#E#ObjectMap, Serializable { // use serialVersionUID from JDK 1.2.2 for interoperability private static final long serialVersionUID = 1978198479659022715L; private final T#E#ObjectMap m; // Backing Map final Object mutex; // Object on which to synchronize public TSynchronized#E#ObjectMap( T#E#ObjectMap m ) { if ( m == null ) throw new NullPointerException(); this.m = m; mutex = this; } public TSynchronized#E#ObjectMap( T#E#ObjectMap m, Object mutex ) { this.m = m; this.mutex = mutex; } public int size() { synchronized( mutex ) { return m.size(); } } public boolean isEmpty(){ synchronized( mutex ) { return m.isEmpty(); } } public boolean containsKey( #e# key ) { synchronized( mutex ) { return m.containsKey( key ); } } public boolean containsValue( Object value ){ synchronized( mutex ) { return m.containsValue( value ); } } public V get( #e# key ) { synchronized( mutex ) { return m.get( key ); } } public V put( #e# key, V value ) { synchronized( mutex ) { return m.put( key, value ); } } public V remove( #e# key ) { synchronized( mutex ) { return m.remove( key ); } } public void putAll( Map map ) { synchronized( mutex ) { m.putAll( map ); } } public void putAll( T#E#ObjectMap map ) { synchronized( mutex ) { m.putAll( map ); } } public void clear() { synchronized( mutex ) { m.clear(); } } private transient T#E#Set keySet = null; private transient Collection values = null; public T#E#Set keySet() { synchronized( mutex ) { if ( keySet == null ) keySet = new TSynchronized#E#Set( m.keySet(), mutex ); return keySet; } } public #e#[] keys() { synchronized( mutex ) { return m.keys(); } } public #e#[] keys( #e#[] array ) { synchronized( mutex ) { return m.keys( array ); } } public Collection valueCollection() { synchronized( mutex ) { if ( values == null ) { values = new SynchronizedCollection( m.valueCollection(), mutex ); } return values; } } public Object[] values() { synchronized( mutex ) { return m.values(); } } public V[] values( V[] array ) { synchronized( mutex ) { return m.values( array ); } } public T#E#ObjectIterator iterator() { return m.iterator(); // Must be manually synched by user! } // unchanging over the life of the map, no need to lock public #e# getNoEntryKey() { return m.getNoEntryKey(); } public V putIfAbsent( #e# key, V value ) { synchronized( mutex ) { return m.putIfAbsent( key, value ); } } public boolean forEachKey( T#E#Procedure procedure ) { synchronized( mutex ) { return m.forEachKey( procedure ); } } public boolean forEachValue( TObjectProcedure procedure ) { synchronized( mutex ) { return m.forEachValue( procedure ); } } public boolean forEachEntry( T#E#ObjectProcedure procedure ) { synchronized( mutex ) { return m.forEachEntry( procedure ); } } public void transformValues( TObjectFunction function ) { synchronized( mutex ) { m.transformValues( function ); } } public boolean retainEntries( T#E#ObjectProcedure procedure ) { synchronized( mutex ) { return m.retainEntries( procedure ); } } public boolean equals( Object o ) { synchronized( mutex ) { return m.equals( o ); } } public int hashCode() { synchronized( mutex ) { return m.hashCode(); } } public String toString() { synchronized( mutex ) { return m.toString(); } } private void writeObject( ObjectOutputStream s ) throws IOException { synchronized( mutex ) { s.defaultWriteObject(); } } } trove-3.0.3/templates/gnu/trove/impl/unmodifiable/0000755000175000017500000000000012000515265021143 5ustar ericherichtrove-3.0.3/templates/gnu/trove/impl/unmodifiable/UnmodifiableObject_E_Map.template0000644000175000017500000001216311763017634027505 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2008, Robert D. Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.impl.unmodifiable; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // THIS IS AN IMPLEMENTATION CLASS. DO NOT USE DIRECTLY! // // Access to these methods should be through TCollections // //////////////////////////////////////////////////////////// import gnu.trove.iterator.*; import gnu.trove.procedure.*; import gnu.trove.set.*; import gnu.trove.list.*; import gnu.trove.function.*; import gnu.trove.map.*; import gnu.trove.*; import java.util.*; import java.io.Serializable; import java.io.ObjectOutputStream; import java.io.IOException; public class TUnmodifiableObject#E#Map implements TObject#E#Map, Serializable { private static final long serialVersionUID = -1034234728574286014L; private final TObject#E#Map m; public TUnmodifiableObject#E#Map( TObject#E#Map m ) { if ( m == null ) throw new NullPointerException(); this.m = m; } public int size() { return m.size(); } public boolean isEmpty() { return m.isEmpty(); } public boolean containsKey( Object key ){ return m.containsKey( key ); } public boolean containsValue( #e# val ) { return m.containsValue( val ); } public #e# get( Object key ) { return m.get( key ); } public #e# put( K key, #e# value ) { throw new UnsupportedOperationException(); } public #e# remove( Object key ) { throw new UnsupportedOperationException(); } public void putAll( TObject#E#Map m ) { throw new UnsupportedOperationException(); } public void putAll( Map map ) { throw new UnsupportedOperationException(); } public void clear() { throw new UnsupportedOperationException(); } private transient Set keySet = null; private transient T#E#Collection values = null; public Set keySet() { if ( keySet == null ) keySet = Collections.unmodifiableSet( m.keySet() ); return keySet; } public Object[] keys() { return m.keys(); } public K[] keys( K[] array ) { return m.keys( array ); } public T#E#Collection valueCollection() { if ( values == null ) values = TCollections.unmodifiableCollection( m.valueCollection() ); return values; } public #e#[] values() { return m.values(); } public #e#[] values( #e#[] array ) { return m.values( array ); } public boolean equals(Object o) { return o == this || m.equals(o); } public int hashCode() { return m.hashCode(); } public String toString() { return m.toString(); } public #e# getNoEntryValue() { return m.getNoEntryValue(); } public boolean forEachKey( TObjectProcedure procedure ) { return m.forEachKey( procedure ); } public boolean forEachValue( T#E#Procedure procedure ) { return m.forEachValue( procedure ); } public boolean forEachEntry( TObject#E#Procedure procedure ) { return m.forEachEntry( procedure ); } public TObject#E#Iterator iterator() { return new TObject#E#Iterator() { TObject#E#Iterator iter = m.iterator(); public K key() { return iter.key(); } public #e# value() { return iter.value(); } public void advance() { iter.advance(); } public boolean hasNext() { return iter.hasNext(); } public #e# setValue( #e# val ) { throw new UnsupportedOperationException(); } public void remove() { throw new UnsupportedOperationException(); } }; } public #e# putIfAbsent( K key, #e# value ) { throw new UnsupportedOperationException(); } public void transformValues( T#E#Function function ) { throw new UnsupportedOperationException(); } public boolean retainEntries( TObject#E#Procedure procedure ) { throw new UnsupportedOperationException(); } public boolean increment( K key ) { throw new UnsupportedOperationException(); } public boolean adjustValue( K key, #e# amount ) { throw new UnsupportedOperationException(); } public #e# adjustOrPutValue( K key, #e# adjust_amount, #e# put_amount ) { throw new UnsupportedOperationException(); } } trove-3.0.3/templates/gnu/trove/impl/unmodifiable/Unmodifiable_K__V_Map.template0000644000175000017500000001235111763017634027007 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2008, Robert D. Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.impl.unmodifiable; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // THIS IS AN IMPLEMENTATION CLASS. DO NOT USE DIRECTLY! // // Access to these methods should be through TCollections // //////////////////////////////////////////////////////////// import gnu.trove.iterator.*; import gnu.trove.procedure.*; import gnu.trove.set.*; import gnu.trove.list.*; import gnu.trove.function.*; import gnu.trove.map.*; import gnu.trove.*; import java.util.Collection; import java.util.Iterator; import java.util.Set; import java.util.Map; import java.util.RandomAccess; import java.util.Random; import java.io.Serializable; import java.io.ObjectOutputStream; import java.io.IOException; public class TUnmodifiable#K##V#Map implements T#K##V#Map, Serializable { private static final long serialVersionUID = -1034234728574286014L; private final T#K##V#Map m; public TUnmodifiable#K##V#Map( T#K##V#Map m ) { if ( m == null ) throw new NullPointerException(); this.m = m; } public int size() { return m.size(); } public boolean isEmpty() { return m.isEmpty(); } public boolean containsKey( #k# key ) { return m.containsKey( key ); } public boolean containsValue( #v# val ) { return m.containsValue( val ); } public #v# get( #k# key) { return m.get( key ); } public #v# put( #k# key, #v# value ) { throw new UnsupportedOperationException(); } public #v# remove( #k# key ) { throw new UnsupportedOperationException(); } public void putAll( T#K##V#Map m ) { throw new UnsupportedOperationException(); } public void putAll( Map map ) { throw new UnsupportedOperationException(); } public void clear() { throw new UnsupportedOperationException(); } private transient T#K#Set keySet = null; private transient T#V#Collection values = null; public T#K#Set keySet() { if ( keySet == null ) keySet = TCollections.unmodifiableSet( m.keySet() ); return keySet; } public #k#[] keys() { return m.keys(); } public #k#[] keys( #k#[] array ) { return m.keys( array ); } public T#V#Collection valueCollection() { if ( values == null ) values = TCollections.unmodifiableCollection( m.valueCollection() ); return values; } public #v#[] values() { return m.values(); } public #v#[] values( #v#[] array ) { return m.values( array ); } public boolean equals(Object o) { return o == this || m.equals(o); } public int hashCode() { return m.hashCode(); } public String toString() { return m.toString(); } public #k# getNoEntryKey() { return m.getNoEntryKey(); } public #v# getNoEntryValue() { return m.getNoEntryValue(); } public boolean forEachKey( T#K#Procedure procedure ) { return m.forEachKey( procedure ); } public boolean forEachValue( T#V#Procedure procedure ) { return m.forEachValue( procedure ); } public boolean forEachEntry( T#K##V#Procedure procedure ) { return m.forEachEntry( procedure ); } public T#K##V#Iterator iterator() { return new T#K##V#Iterator() { T#K##V#Iterator iter = m.iterator(); public #k# key() { return iter.key(); } public #v# value() { return iter.value(); } public void advance() { iter.advance(); } public boolean hasNext() { return iter.hasNext(); } public #v# setValue( #v# val ) { throw new UnsupportedOperationException(); } public void remove() { throw new UnsupportedOperationException(); } }; } public #v# putIfAbsent( #k# key, #v# value ) { throw new UnsupportedOperationException(); } public void transformValues( T#V#Function function ) { throw new UnsupportedOperationException(); } public boolean retainEntries( T#K##V#Procedure procedure ) { throw new UnsupportedOperationException(); } public boolean increment( #k# key ) { throw new UnsupportedOperationException(); } public boolean adjustValue( #k# key, #v# amount ) { throw new UnsupportedOperationException(); } public #v# adjustOrPutValue( #k# key, #v# adjust_amount, #v# put_amount ) { throw new UnsupportedOperationException(); } } trove-3.0.3/templates/gnu/trove/impl/unmodifiable/UnmodifiableRandomAccess_E_List.template0000644000175000017500000000514511763017634031041 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2008, Robert D. Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.impl.unmodifiable; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // THIS IS AN IMPLEMENTATION CLASS. DO NOT USE DIRECTLY! // // Access to these methods should be through TCollections // //////////////////////////////////////////////////////////// import gnu.trove.iterator.*; import gnu.trove.procedure.*; import gnu.trove.set.*; import gnu.trove.list.*; import gnu.trove.function.*; import gnu.trove.map.*; import gnu.trove.*; import java.util.Collection; import java.util.Iterator; import java.util.Set; import java.util.Map; import java.util.RandomAccess; import java.util.Random; import java.io.Serializable; import java.io.ObjectOutputStream; import java.io.IOException; public class TUnmodifiableRandomAccess#E#List extends TUnmodifiable#E#List implements RandomAccess { private static final long serialVersionUID = -2542308836966382001L; public TUnmodifiableRandomAccess#E#List( T#E#List list ) { super( list ); } public T#E#List subList( int fromIndex, int toIndex ) { return new TUnmodifiableRandomAccess#E#List( list.subList( fromIndex, toIndex ) ); } /** * Allows instances to be deserialized in pre-1.4 JREs (which do * not have UnmodifiableRandomAccessList). UnmodifiableList has * a readResolve method that inverts this transformation upon * deserialization. */ private Object writeReplace() { return new TUnmodifiable#E#List( list ); } }trove-3.0.3/templates/gnu/trove/impl/unmodifiable/Unmodifiable_E_Collection.template0000644000175000017500000001051411763017634027732 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2008, Robert D. Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.impl.unmodifiable; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // THIS IS AN IMPLEMENTATION CLASS. DO NOT USE DIRECTLY! // // Access to these methods should be through TCollections // //////////////////////////////////////////////////////////// import gnu.trove.iterator.*; import gnu.trove.procedure.*; import gnu.trove.set.*; import gnu.trove.list.*; import gnu.trove.function.*; import gnu.trove.map.*; import gnu.trove.*; import java.util.Collection; import java.util.Iterator; import java.util.Set; import java.util.Map; import java.util.RandomAccess; import java.util.Random; import java.io.Serializable; import java.io.ObjectOutputStream; import java.io.IOException; public class TUnmodifiable#E#Collection implements T#E#Collection, Serializable { private static final long serialVersionUID = 1820017752578914078L; final T#E#Collection c; public TUnmodifiable#E#Collection( T#E#Collection c ) { if ( c == null ) throw new NullPointerException(); this.c = c; } public int size() { return c.size(); } public boolean isEmpty() { return c.isEmpty(); } public boolean contains( #e# o ) { return c.contains( o ); } public #e#[] toArray() { return c.toArray(); } public #e#[] toArray( #e#[] a ) { return c.toArray( a ); } public String toString() { return c.toString(); } public #e# getNoEntryValue() { return c.getNoEntryValue(); } public boolean forEach( T#E#Procedure procedure ) { return c.forEach( procedure ); } public T#E#Iterator iterator() { return new T#E#Iterator() { T#E#Iterator i = c.iterator(); public boolean hasNext() { return i.hasNext(); } public #e# next() { return i.next(); } public void remove() { throw new UnsupportedOperationException(); } }; } public boolean add( #e# e ) { throw new UnsupportedOperationException(); } public boolean remove( #e# o ) { throw new UnsupportedOperationException(); } public boolean containsAll( Collection coll ) { return c.containsAll( coll ); } public boolean containsAll( T#E#Collection coll ) { return c.containsAll( coll ); } public boolean containsAll( #e#[] array ) { return c.containsAll( array ); } public boolean addAll( T#E#Collection coll ) { throw new UnsupportedOperationException(); } public boolean addAll( Collection coll ) { throw new UnsupportedOperationException(); } public boolean addAll( #e#[] array ) { throw new UnsupportedOperationException(); } public boolean removeAll( Collection coll ) { throw new UnsupportedOperationException(); } public boolean removeAll( T#E#Collection coll ) { throw new UnsupportedOperationException(); } public boolean removeAll( #e#[] array ) { throw new UnsupportedOperationException(); } public boolean retainAll( Collection coll ) { throw new UnsupportedOperationException(); } public boolean retainAll( T#E#Collection coll ) { throw new UnsupportedOperationException(); } public boolean retainAll( #e#[] array ) { throw new UnsupportedOperationException(); } public void clear() { throw new UnsupportedOperationException(); } } trove-3.0.3/templates/gnu/trove/impl/unmodifiable/Unmodifiable_E_ObjectMap.template0000644000175000017500000001150211763017634027501 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2008, Robert D. Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.impl.unmodifiable; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // THIS IS AN IMPLEMENTATION CLASS. DO NOT USE DIRECTLY! // // Access to these methods should be through TCollections // //////////////////////////////////////////////////////////// import gnu.trove.iterator.*; import gnu.trove.procedure.*; import gnu.trove.set.*; import gnu.trove.list.*; import gnu.trove.function.*; import gnu.trove.map.*; import gnu.trove.*; import java.util.*; import java.io.Serializable; import java.io.ObjectOutputStream; import java.io.IOException; public class TUnmodifiable#E#ObjectMap implements T#E#ObjectMap, Serializable { private static final long serialVersionUID = -1034234728574286014L; private final T#E#ObjectMap m; public TUnmodifiable#E#ObjectMap( T#E#ObjectMap m ) { if ( m == null ) throw new NullPointerException(); this.m = m; } public int size() { return m.size(); } public boolean isEmpty() { return m.isEmpty(); } public boolean containsKey( #e# key ) { return m.containsKey( key ); } public boolean containsValue( Object val ) { return m.containsValue( val ); } public V get( #e# key) { return m.get( key ); } public V put( #e# key, V value ) { throw new UnsupportedOperationException(); } public V remove( #e# key ) { throw new UnsupportedOperationException(); } public void putAll( T#E#ObjectMap m ) { throw new UnsupportedOperationException(); } public void putAll( Map map ) { throw new UnsupportedOperationException(); } public void clear() { throw new UnsupportedOperationException(); } private transient T#E#Set keySet = null; private transient Collection values = null; public T#E#Set keySet() { if ( keySet == null ) keySet = TCollections.unmodifiableSet( m.keySet() ); return keySet; } public #e#[] keys() { return m.keys(); } public #e#[] keys( #e#[] array ) { return m.keys( array ); } public Collection valueCollection() { if ( values == null ) values = Collections.unmodifiableCollection( m.valueCollection() ); return values; } public Object[] values() { return m.values(); } public V[] values( V[] array ) { return m.values( array ); } public boolean equals(Object o) { return o == this || m.equals(o); } public int hashCode() { return m.hashCode(); } public String toString() { return m.toString(); } public #e# getNoEntryKey() { return m.getNoEntryKey(); } public boolean forEachKey( T#E#Procedure procedure ) { return m.forEachKey( procedure ); } public boolean forEachValue( TObjectProcedure procedure ) { return m.forEachValue( procedure ); } public boolean forEachEntry( T#E#ObjectProcedure procedure ) { return m.forEachEntry( procedure ); } public T#E#ObjectIterator iterator() { return new T#E#ObjectIterator() { T#E#ObjectIterator iter = m.iterator(); public #e# key() { return iter.key(); } public V value() { return iter.value(); } public void advance() { iter.advance(); } public boolean hasNext() { return iter.hasNext(); } public V setValue( V val ) { throw new UnsupportedOperationException(); } public void remove() { throw new UnsupportedOperationException(); } }; } public V putIfAbsent( #e# key, V value ) { throw new UnsupportedOperationException(); } public void transformValues( TObjectFunction function ) { throw new UnsupportedOperationException(); } public boolean retainEntries( T#E#ObjectProcedure procedure ) { throw new UnsupportedOperationException(); } } trove-3.0.3/templates/gnu/trove/impl/unmodifiable/Unmodifiable_E_List.template0000644000175000017500000001662011763017634026556 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2008, Robert D. Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.impl.unmodifiable; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // THIS IS AN IMPLEMENTATION CLASS. DO NOT USE DIRECTLY! // // Access to these methods should be through TCollections // //////////////////////////////////////////////////////////// import gnu.trove.iterator.*; import gnu.trove.procedure.*; import gnu.trove.set.*; import gnu.trove.list.*; import gnu.trove.function.*; import gnu.trove.map.*; import gnu.trove.*; import java.util.Collection; import java.util.Iterator; import java.util.Set; import java.util.Map; import java.util.RandomAccess; import java.util.Random; import java.io.Serializable; import java.io.ObjectOutputStream; import java.io.IOException; public class TUnmodifiable#E#List extends TUnmodifiable#E#Collection implements T#E#List { static final long serialVersionUID = -283967356065247728L; final T#E#List list; public TUnmodifiable#E#List( T#E#List list ) { super( list ); this.list = list; } public boolean equals( Object o ) { return o == this || list.equals( o ); } public int hashCode() { return list.hashCode(); } public #e# get( int index ) { return list.get( index ); } public int indexOf( #e# o ) { return list.indexOf( o ); } public int lastIndexOf( #e# o ) { return list.lastIndexOf( o ); } public #e#[] toArray( int offset, int len ) { return list.toArray( offset, len ); } public #e#[] toArray( #e#[] dest, int offset, int len ) { return list.toArray( dest, offset, len ); } public #e#[] toArray( #e#[] dest, int source_pos, int dest_pos, int len ) { return list.toArray( dest, source_pos, dest_pos, len ); } public boolean forEachDescending( T#E#Procedure procedure ) { return list.forEachDescending( procedure ); } public int binarySearch( #e# value ) { return list.binarySearch( value ); } public int binarySearch( #e# value, int fromIndex, int toIndex ) { return list.binarySearch( value, fromIndex, toIndex ); } public int indexOf( int offset, #e# value ) { return list.indexOf( offset, value ); } public int lastIndexOf( int offset, #e# value ) { return list.lastIndexOf( offset, value ); } public T#E#List grep( T#E#Procedure condition ) { return list.grep( condition ); } public T#E#List inverseGrep( T#E#Procedure condition ) { return list.inverseGrep( condition ); } public #e# max() { return list.max(); } public #e# min() { return list.min(); } public #e# sum() { return list.sum(); } public T#E#List subList( int fromIndex, int toIndex ) { return new TUnmodifiable#E#List( list.subList( fromIndex, toIndex ) ); } // TODO: Do we want to fullt implement ListIterator? // public TIntListIterator listIterator() {return listIterator(0);} // // public ListIterator listIterator(final int index) { // return new ListIterator() { // ListIterator i = list.listIterator(index); // // public boolean hasNext() {return i.hasNext();} // public E next() {return i.next();} // public boolean hasPrevious() {return i.hasPrevious();} // public E previous() {return i.previous();} // public int nextIndex() {return i.nextIndex();} // public int previousIndex() {return i.previousIndex();} // // public void remove() { // throw new UnsupportedOperationException(); // } // public void set(E e) { // throw new UnsupportedOperationException(); // } // public void add(E e) { // throw new UnsupportedOperationException(); // } // }; // } /** * UnmodifiableRandomAccessList instances are serialized as * UnmodifiableList instances to allow them to be deserialized * in pre-1.4 JREs (which do not have UnmodifiableRandomAccessList). * This method inverts the transformation. As a beneficial * side-effect, it also grafts the RandomAccess marker onto * UnmodifiableList instances that were serialized in pre-1.4 JREs. * * Note: Unfortunately, UnmodifiableRandomAccessList instances * serialized in 1.4.1 and deserialized in 1.4 will become * UnmodifiableList instances, as this method was missing in 1.4. */ private Object readResolve() { return ( list instanceof RandomAccess ? new TUnmodifiableRandomAccess#E#List( list ) : this); } public void add( #e#[] vals ) { throw new UnsupportedOperationException(); } public void add( #e#[] vals, int offset, int length ) { throw new UnsupportedOperationException(); } public #e# removeAt( int offset ) { throw new UnsupportedOperationException(); } public void remove( int offset, int length ) { throw new UnsupportedOperationException(); } public void insert( int offset, #e# value ) { throw new UnsupportedOperationException(); } public void insert( int offset, #e#[] values ) { throw new UnsupportedOperationException(); } public void insert( int offset, #e#[] values, int valOffset, int len ) { throw new UnsupportedOperationException(); } public #e# set( int offset, #e# val ) { throw new UnsupportedOperationException(); } public void set( int offset, #e#[] values ) { throw new UnsupportedOperationException(); } public void set( int offset, #e#[] values, int valOffset, int length ) { throw new UnsupportedOperationException(); } public #e# replace( int offset, #e# val ) { throw new UnsupportedOperationException(); } public void transformValues( T#E#Function function ) { throw new UnsupportedOperationException(); } public void reverse() { throw new UnsupportedOperationException(); } public void reverse( int from, int to ) { throw new UnsupportedOperationException(); } public void shuffle( Random rand ) { throw new UnsupportedOperationException(); } public void sort() { throw new UnsupportedOperationException(); } public void sort( int fromIndex, int toIndex ) { throw new UnsupportedOperationException(); } public void fill( #e# val ) { throw new UnsupportedOperationException(); } public void fill( int fromIndex, int toIndex, #e# val ) { throw new UnsupportedOperationException(); } } trove-3.0.3/templates/gnu/trove/impl/unmodifiable/Unmodifiable_E_Set.template0000644000175000017500000000441311763017634026373 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2008, Robert D. Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.impl.unmodifiable; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // THIS IS AN IMPLEMENTATION CLASS. DO NOT USE DIRECTLY! // // Access to these methods should be through TCollections // //////////////////////////////////////////////////////////// import gnu.trove.iterator.*; import gnu.trove.procedure.*; import gnu.trove.set.*; import gnu.trove.list.*; import gnu.trove.function.*; import gnu.trove.map.*; import gnu.trove.*; import java.util.Collection; import java.util.Iterator; import java.util.Set; import java.util.Map; import java.util.RandomAccess; import java.util.Random; import java.io.Serializable; import java.io.ObjectOutputStream; import java.io.IOException; public class TUnmodifiable#E#Set extends TUnmodifiable#E#Collection implements T#E#Set, Serializable { private static final long serialVersionUID = -9215047833775013803L; public TUnmodifiable#E#Set( T#E#Set s ) { super( s ); } public boolean equals( Object o ) { return o == this || c.equals(o); } public int hashCode() { return c.hashCode(); } } trove-3.0.3/templates/gnu/trove/impl/hash/0000755000175000017500000000000012000515265017430 5ustar ericherichtrove-3.0.3/templates/gnu/trove/impl/hash/_K__V_Hash.template0000644000175000017500000003435311763017634023131 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001, Eric D. Friedman All Rights Reserved. // Copyright (c) 2009, Rob Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.impl.hash; import gnu.trove.procedure.*; import gnu.trove.impl.HashFunctions; import java.io.ObjectOutput; import java.io.ObjectInput; import java.io.IOException; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// /** * An open addressed hashing implementation for #k#/#v# primitive entries. * * Created: Sun Nov 4 08:56:06 2001 * * @author Eric D. Friedman * @author Rob Eden * @author Jeff Randall * @version $Id: _K__V_Hash.template,v 1.1.2.6 2009/11/07 03:36:44 robeden Exp $ */ abstract public class T#K##V#Hash extends TPrimitiveHash { static final long serialVersionUID = 1L; /** the set of #k#s */ public transient #k#[] _set; /** * key that represents null * * NOTE: should not be modified after the Hash is created, but is * not final because of Externalization * */ protected #k# no_entry_key; /** * value that represents null * * NOTE: should not be modified after the Hash is created, but is * not final because of Externalization * */ protected #v# no_entry_value; protected boolean consumeFreeSlot; /** * Creates a new T#E#Hash instance with the default * capacity and load factor. */ public T#K##V#Hash() { super(); no_entry_key = ( #k# ) 0; no_entry_value = ( #v# ) 0; } /** * Creates a new T#E#Hash instance whose capacity * is the next highest prime above initialCapacity + 1 * unless that value is already prime. * * @param initialCapacity an int value */ public T#K##V#Hash( int initialCapacity ) { super( initialCapacity ); no_entry_key = ( #k# ) 0; no_entry_value = ( #v# ) 0; } /** * Creates a new T#K##V#Hash instance with a prime * value at or near the specified capacity and load factor. * * @param initialCapacity used to find a prime capacity for the table. * @param loadFactor used to calculate the threshold over which * rehashing takes place. */ public T#K##V#Hash( int initialCapacity, float loadFactor ) { super(initialCapacity, loadFactor); no_entry_key = ( #k# ) 0; no_entry_value = ( #v# ) 0; } /** * Creates a new T#K##V#Hash instance with a prime * value at or near the specified capacity and load factor. * * @param initialCapacity used to find a prime capacity for the table. * @param loadFactor used to calculate the threshold over which * rehashing takes place. * @param no_entry_value value that represents null */ public T#K##V#Hash( int initialCapacity, float loadFactor, #k# no_entry_key, #v# no_entry_value ) { super(initialCapacity, loadFactor); this.no_entry_key = no_entry_key; this.no_entry_value = no_entry_value; } /** * Returns the value that is used to represent null as a key. The default * value is generally zero, but can be changed during construction * of the collection. * * @return the value that represents null */ public #k# getNoEntryKey() { return no_entry_key; } /** * Returns the value that is used to represent null. The default * value is generally zero, but can be changed during construction * of the collection. * * @return the value that represents null */ public #v# getNoEntryValue() { return no_entry_value; } /** * initializes the hashtable to a prime capacity which is at least * initialCapacity + 1. * * @param initialCapacity an int value * @return the actual capacity chosen */ protected int setUp( int initialCapacity ) { int capacity; capacity = super.setUp( initialCapacity ); _set = new #k#[capacity]; return capacity; } /** * Searches the set for val * * @param val an #k# value * @return a boolean value */ public boolean contains( #k# val ) { return index(val) >= 0; } /** * Executes procedure for each key in the map. * * @param procedure a T#K#Procedure value * @return false if the loop over the set terminated because * the procedure returned false for some value. */ public boolean forEach( T#K#Procedure procedure ) { byte[] states = _states; #k#[] set = _set; for ( int i = set.length; i-- > 0; ) { if ( states[i] == FULL && ! procedure.execute( set[i] ) ) { return false; } } return true; } /** * Releases the element currently stored at index. * * @param index an int value */ protected void removeAt( int index ) { _set[index] = no_entry_key; super.removeAt( index ); } /** * Locates the index of val. * * @param key an #k# value * @return the index of val or -1 if it isn't in the set. */ protected int index( #k# key ) { int hash, probe, index, length; final byte[] states = _states; final #k#[] set = _set; length = states.length; hash = HashFunctions.hash( key ) & 0x7fffffff; index = hash % length; byte state = states[index]; if (state == FREE) return -1; if (state == FULL && set[index] == key) return index; return indexRehashed(key, index, hash, state); } int indexRehashed(#k# key, int index, int hash, byte state) { // see Knuth, p. 529 int length = _set.length; int probe = 1 + (hash % (length - 2)); final int loopIndex = index; do { index -= probe; if (index < 0) { index += length; } state = _states[index]; // if (state == FREE) return -1; // if (key == _set[index] && state != REMOVED) return index; } while (index != loopIndex); return -1; } /** * Locates the index at which val can be inserted. if * there is already a value equal()ing val in the set, * returns that value as a negative integer. * * @param key an #k# value * @return an int value */ protected int insertKey( #k# val ) { int hash, index; hash = HashFunctions.hash(val) & 0x7fffffff; index = hash % _states.length; byte state = _states[index]; consumeFreeSlot = false; if (state == FREE) { consumeFreeSlot = true; insertKeyAt(index, val); return index; // empty, all done } if (state == FULL && _set[index] == val) { return -index - 1; // already stored } // already FULL or REMOVED, must probe return insertKeyRehash(val, index, hash, state); } int insertKeyRehash(#k# val, int index, int hash, byte state) { // compute the double hash final int length = _set.length; int probe = 1 + (hash % (length - 2)); final int loopIndex = index; int firstRemoved = -1; /** * Look until FREE slot or we start to loop */ do { // Identify first removed slot if (state == REMOVED && firstRemoved == -1) firstRemoved = index; index -= probe; if (index < 0) { index += length; } state = _states[index]; // A FREE slot stops the search if (state == FREE) { if (firstRemoved != -1) { insertKeyAt(firstRemoved, val); return firstRemoved; } else { consumeFreeSlot = true; insertKeyAt(index, val); return index; } } if (state == FULL && _set[index] == val) { return -index - 1; } // Detect loop } while (index != loopIndex); // We inspected all reachable slots and did not find a FREE one // If we found a REMOVED slot we return the first one found if (firstRemoved != -1) { insertKeyAt(firstRemoved, val); return firstRemoved; } // Can a resizing strategy be found that resizes the set? throw new IllegalStateException("No free or removed slots available. Key set full?!!"); } void insertKeyAt(int index, #k# val) { _set[index] = val; // insert value _states[index] = FULL; } protected int XinsertKey( #k# key ) { int hash, probe, index, length; final byte[] states = _states; final #k#[] set = _set; length = states.length; hash = HashFunctions.hash( key ) & 0x7fffffff; index = hash % length; byte state = states[index]; consumeFreeSlot = false; if ( state == FREE ) { consumeFreeSlot = true; set[index] = key; states[index] = FULL; return index; // empty, all done } else if ( state == FULL && set[index] == key ) { return -index -1; // already stored } else { // already FULL or REMOVED, must probe // compute the double hash probe = 1 + ( hash % ( length - 2 ) ); // if the slot we landed on is FULL (but not removed), probe // until we find an empty slot, a REMOVED slot, or an element // equal to the one we are trying to insert. // finding an empty slot means that the value is not present // and that we should use that slot as the insertion point; // finding a REMOVED slot means that we need to keep searching, // however we want to remember the offset of that REMOVED slot // so we can reuse it in case a "new" insertion (i.e. not an update) // is possible. // finding a matching value means that we've found that our desired // key is already in the table if ( state != REMOVED ) { // starting at the natural offset, probe until we find an // offset that isn't full. do { index -= probe; if (index < 0) { index += length; } state = states[index]; } while ( state == FULL && set[index] != key ); } // if the index we found was removed: continue probing until we // locate a free location or an element which equal()s the // one we have. if ( state == REMOVED) { int firstRemoved = index; while ( state != FREE && ( state == REMOVED || set[index] != key ) ) { index -= probe; if (index < 0) { index += length; } state = states[index]; } if (state == FULL) { return -index -1; } else { set[index] = key; states[index] = FULL; return firstRemoved; } } // if it's full, the key is already stored if (state == FULL) { return -index -1; } else { consumeFreeSlot = true; set[index] = key; states[index] = FULL; return index; } } } /** {@inheritDoc} */ public void writeExternal( ObjectOutput out ) throws IOException { // VERSION out.writeByte( 0 ); // SUPER super.writeExternal( out ); // NO_ENTRY_KEY out.write#K#( no_entry_key ); // NO_ENTRY_VALUE out.write#V#( no_entry_value ); } /** {@inheritDoc} */ public void readExternal( ObjectInput in ) throws IOException, ClassNotFoundException { // VERSION in.readByte(); // SUPER super.readExternal( in ); // NO_ENTRY_KEY no_entry_key = in.read#K#(); // NO_ENTRY_VALUE no_entry_value = in.read#V#(); } } // T#K##V#Hash trove-3.0.3/templates/gnu/trove/impl/hash/_E_Hash.template0000644000175000017500000002425211763017634022474 0ustar ericherich/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2001, Eric D. Friedman All Rights Reserved. // Copyright (c) 2009, Rob Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package gnu.trove.impl.hash; import gnu.trove.procedure.T#E#Procedure; import gnu.trove.impl.HashFunctions; import gnu.trove.impl.Constants; import java.util.Arrays; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// /** * An open addressed hashing implementation for #e# primitives. * * Created: Sun Nov 4 08:56:06 2001 * * @author Eric D. Friedman, Rob Eden, Jeff Randall * @version $Id: _E_Hash.template,v 1.1.2.6 2009/11/07 03:36:44 robeden Exp $ */ abstract public class T#E#Hash extends TPrimitiveHash { static final long serialVersionUID = 1L; /** the set of #e#s */ public transient #e#[] _set; /** * value that represents null * * NOTE: should not be modified after the Hash is created, but is * not final because of Externalization * */ protected #e# no_entry_value; protected boolean consumeFreeSlot; /** * Creates a new T#E#Hash instance with the default * capacity and load factor. */ public T#E#Hash() { super(); no_entry_value = Constants.DEFAULT_#EC#_NO_ENTRY_VALUE; //noinspection RedundantCast if ( no_entry_value != ( #e# ) 0 ) { Arrays.fill( _set, no_entry_value ); } } /** * Creates a new T#E#Hash instance whose capacity * is the next highest prime above initialCapacity + 1 * unless that value is already prime. * * @param initialCapacity an int value */ public T#E#Hash( int initialCapacity ) { super( initialCapacity ); no_entry_value = Constants.DEFAULT_#EC#_NO_ENTRY_VALUE; //noinspection RedundantCast if ( no_entry_value != ( #e# ) 0 ) { Arrays.fill( _set, no_entry_value ); } } /** * Creates a new T#E#Hash instance with a prime * value at or near the specified capacity and load factor. * * @param initialCapacity used to find a prime capacity for the table. * @param loadFactor used to calculate the threshold over which * rehashing takes place. */ public T#E#Hash( int initialCapacity, float loadFactor ) { super(initialCapacity, loadFactor); no_entry_value = Constants.DEFAULT_#EC#_NO_ENTRY_VALUE; //noinspection RedundantCast if ( no_entry_value != ( #e# ) 0 ) { Arrays.fill( _set, no_entry_value ); } } /** * Creates a new T#E#Hash instance with a prime * value at or near the specified capacity and load factor. * * @param initialCapacity used to find a prime capacity for the table. * @param loadFactor used to calculate the threshold over which * rehashing takes place. * @param no_entry_value value that represents null */ public T#E#Hash( int initialCapacity, float loadFactor, #e# no_entry_value ) { super(initialCapacity, loadFactor); this.no_entry_value = no_entry_value; //noinspection RedundantCast if ( no_entry_value != ( #e# ) 0 ) { Arrays.fill( _set, no_entry_value ); } } /** * Returns the value that is used to represent null. The default * value is generally zero, but can be changed during construction * of the collection. * * @return the value that represents null */ public #e# getNoEntryValue() { return no_entry_value; } /** * initializes the hashtable to a prime capacity which is at least * initialCapacity + 1. * * @param initialCapacity an int value * @return the actual capacity chosen */ protected int setUp( int initialCapacity ) { int capacity; capacity = super.setUp( initialCapacity ); _set = new #e#[capacity]; return capacity; } /** * Searches the set for val * * @param val an #e# value * @return a boolean value */ public boolean contains( #e# val ) { return index(val) >= 0; } /** * Executes procedure for each element in the set. * * @param procedure a TObjectProcedure value * @return false if the loop over the set terminated because * the procedure returned false for some value. */ public boolean forEach( T#E#Procedure procedure ) { byte[] states = _states; #e#[] set = _set; for ( int i = set.length; i-- > 0; ) { if ( states[i] == FULL && ! procedure.execute( set[i] ) ) { return false; } } return true; } /** * Releases the element currently stored at index. * * @param index an int value */ protected void removeAt( int index ) { _set[index] = no_entry_value; super.removeAt( index ); } /** * Locates the index of val. * * @param val an #e# value * @return the index of val or -1 if it isn't in the set. */ protected int index( #e# val ) { int hash, probe, index, length; final byte[] states = _states; final #e#[] set = _set; length = states.length; hash = HashFunctions.hash( val ) & 0x7fffffff; index = hash % length; byte state = states[index]; if (state == FREE) return -1; if (state == FULL && set[index] == val) return index; return indexRehashed(val, index, hash, state); } int indexRehashed(#e# key, int index, int hash, byte state) { // see Knuth, p. 529 int length = _set.length; int probe = 1 + (hash % (length - 2)); final int loopIndex = index; do { index -= probe; if (index < 0) { index += length; } state = _states[index]; // if (state == FREE) return -1; // if (key == _set[index] && state != REMOVED) return index; } while (index != loopIndex); return -1; } /** * Locates the index at which val can be inserted. if * there is already a value equal()ing val in the set, * returns that value as a negative integer. * * @param val an #e# value * @return an int value */ protected int insertKey( #e# val ) { int hash, index; hash = HashFunctions.hash(val) & 0x7fffffff; index = hash % _states.length; byte state = _states[index]; consumeFreeSlot = false; if (state == FREE) { consumeFreeSlot = true; insertKeyAt(index, val); return index; // empty, all done } if (state == FULL && _set[index] == val) { return -index - 1; // already stored } // already FULL or REMOVED, must probe return insertKeyRehash(val, index, hash, state); } int insertKeyRehash(#e# val, int index, int hash, byte state) { // compute the double hash final int length = _set.length; int probe = 1 + (hash % (length - 2)); final int loopIndex = index; int firstRemoved = -1; /** * Look until FREE slot or we start to loop */ do { // Identify first removed slot if (state == REMOVED && firstRemoved == -1) firstRemoved = index; index -= probe; if (index < 0) { index += length; } state = _states[index]; // A FREE slot stops the search if (state == FREE) { if (firstRemoved != -1) { insertKeyAt(firstRemoved, val); return firstRemoved; } else { consumeFreeSlot = true; insertKeyAt(index, val); return index; } } if (state == FULL && _set[index] == val) { return -index - 1; } // Detect loop } while (index != loopIndex); // We inspected all reachable slots and did not find a FREE one // If we found a REMOVED slot we return the first one found if (firstRemoved != -1) { insertKeyAt(firstRemoved, val); return firstRemoved; } // Can a resizing strategy be found that resizes the set? throw new IllegalStateException("No free or removed slots available. Key set full?!!"); } void insertKeyAt(int index, #e# val) { _set[index] = val; // insert value _states[index] = FULL; } } // T#E#Hash trove-3.0.3/README-idea-devel.txt0000644000175000017500000000151511763017636015331 0ustar ericherichIf you are developing using IntelliJ IDEA from JetBrains, you can use the project file contained in the "idea" directory. When you do so, you will need to define three "Path Variables" (IDEA will prompt you to do this when you open the project): - TROVE_TOP_LEVEL - Top level directory containing Trove files. Note that this directory should *NOT* contain the CVS files, but should contain the directory that does. Example: C:/Users/reden/Documents/Trove - TROVE_VCS_ROOT - Directory within TROVE_TOP_LEVEL that contains the CVS files. This should be an absoulte path. Example: C:/Users/reden/Documents/Trove/working - TROVE_JDK_NAME - Name of the JDK for Trove to use. Example: 1.6.0_17trove-3.0.3/generator_test/0000755000175000017500000000000011763017635014660 5ustar ericherichtrove-3.0.3/generator_test/gnu/0000755000175000017500000000000011763017635015451 5ustar ericherichtrove-3.0.3/generator_test/gnu/trove/0000755000175000017500000000000011763017635016610 5ustar ericherichtrove-3.0.3/generator_test/gnu/trove/generator/0000755000175000017500000000000012000515241020553 5ustar ericherichtrove-3.0.3/generator_test/gnu/trove/generator/GeneratorTest.java0000644000175000017500000001024711763017635024233 0ustar ericherich/* * /////////////////////////////////////////////////////////////////////////////// * // Copyright (c) 2009, Rob Eden All Rights Reserved. * // * // This library is free software; you can redistribute it and/or * // modify it under the terms of the GNU Lesser General Public * // License as published by the Free Software Foundation; either * // version 2.1 of the License, or (at your option) any later version. * // * // This library is distributed in the hope that it will be useful, * // but WITHOUT ANY WARRANTY; without even the implied warranty of * // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * // GNU General Public License for more details. * // * // You should have received a copy of the GNU Lesser General Public * // License along with this program; if not, write to the Free Software * // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * /////////////////////////////////////////////////////////////////////////////// */ package gnu.trove.generator; import junit.framework.TestCase; import java.io.IOException; import java.util.HashMap; import java.util.Map; /** * */ public class GeneratorTest extends TestCase { public void testReplicatedContentNoMatch() throws IOException { String test = "This is a test\nLine 2\nLine 3"; StringBuilder buf = new StringBuilder(); assertNull( Generator.findReplicatedBlocks( test, buf ) ); assertEquals( 0, buf.length() ); } public void testReplicatedContent() throws IOException { String test = "This is a test\nLine 2\n====START_REPLICATED_CONTENT #1====\n" + "Replicated 1\n=====END_REPLICATED_CONTENT #1=====\n" + "====START_REPLICATED_CONTENT #2====\n" + "Replicated 2\n=====END_REPLICATED_CONTENT #2=====\n"; StringBuilder buf = new StringBuilder(); Map map = Generator.findReplicatedBlocks( test, buf ); assertNotNull( map ); assertEquals( 2, map.size() ); assertEquals( "Replicated 1", map.get( Integer.valueOf( 1 ) ) ); assertEquals( "Replicated 2", map.get( Integer.valueOf( 2 ) ) ); assertEquals( "This is a test\nLine 2", buf.toString() ); } public void testProcessReplication() { String test = "Line 1\n#REPLICATED1#\n#REPLICATED2#\nLine 4"; Map map = new HashMap(); map.put( Integer.valueOf( 1 ), "Line 2 - #E#" ); map.put( Integer.valueOf( 2 ), "Line 3 - #K# #V#" ); String output = Generator.processReplication( test, map ); String goal = "Line 1\n" + "Line 2 - Double\n\n" + "Line 2 - Float\n\n" + "Line 2 - Int\n\n" + "Line 2 - Long\n\n" + "Line 2 - Byte\n\n" + "Line 2 - Short\n\n" + "Line 2 - Char\n" + "Line 3 - Double Double\n\n" + "Line 3 - Double Float\n\n" + "Line 3 - Double Int\n\n" + "Line 3 - Double Long\n\n" + "Line 3 - Double Byte\n\n" + "Line 3 - Double Short\n\n" + "Line 3 - Double Char\n\n" + "Line 3 - Float Double\n\n" + "Line 3 - Float Float\n\n" + "Line 3 - Float Int\n\n" + "Line 3 - Float Long\n\n" + "Line 3 - Float Byte\n\n" + "Line 3 - Float Short\n\n" + "Line 3 - Float Char\n\n" + "Line 3 - Int Double\n\n" + "Line 3 - Int Float\n\n" + "Line 3 - Int Int\n\n" + "Line 3 - Int Long\n\n" + "Line 3 - Int Byte\n\n" + "Line 3 - Int Short\n\n" + "Line 3 - Int Char\n\n" + "Line 3 - Long Double\n\n" + "Line 3 - Long Float\n\n" + "Line 3 - Long Int\n\n" + "Line 3 - Long Long\n\n" + "Line 3 - Long Byte\n\n" + "Line 3 - Long Short\n\n" + "Line 3 - Long Char\n\n" + "Line 3 - Byte Double\n\n" + "Line 3 - Byte Float\n\n" + "Line 3 - Byte Int\n\n" + "Line 3 - Byte Long\n\n" + "Line 3 - Byte Byte\n\n" + "Line 3 - Byte Short\n\n" + "Line 3 - Byte Char\n\n" + "Line 3 - Short Double\n\n" + "Line 3 - Short Float\n\n" + "Line 3 - Short Int\n\n" + "Line 3 - Short Long\n\n" + "Line 3 - Short Byte\n\n" + "Line 3 - Short Short\n\n" + "Line 3 - Short Char\n\n" + "Line 3 - Char Double\n\n" + "Line 3 - Char Float\n\n" + "Line 3 - Char Int\n\n" + "Line 3 - Char Long\n\n" + "Line 3 - Char Byte\n\n" + "Line 3 - Char Short\n\n" + "Line 3 - Char Char\n" + "Line 4"; assertEquals( goal, output ); } } trove-3.0.3/javadocs/0000755000175000017500000000000012000515263013406 5ustar ericherich