118 Commits
Author SHA1 Message Date
Speiger 865966db55 Build Fixes & Build Release Doc update 2021-12-11 13:27:33 +01:00
Speiger 6266a6293c Slight rewording 2021-12-11 12:58:02 +01:00
Speiger 70ea60aacf More doc fixes 2021-12-11 12:57:03 +01:00
Speiger 599cc44fff Fixed Doc 2021-12-11 12:56:01 +01:00
Speiger e1df59d512 We are now to 16k tests. Fixed loads of issues.
-Added: Tests for Lists and Sets.
-Fixed: SubLists are now stable (they weren't before)
-Fixed: All the bugs that the unit tests found so far.
-Updated: ReadMe/Changelog
2021-12-11 12:53:58 +01:00
Speiger eaa45976c7 Added over 6k tests...
- Fixed: ImmutableMaps issues thanks to the tests. Roughly the same as
the rest of the maps
- Fixed: RB/AVLTreeMaps issues. Roughly the same as the rest of the maps
2021-12-10 10:55:16 +01:00
Speiger 362838c434 Found something in FastUtil i needed to address too. BulkFixes coming.
- Added: Guava TestSuit
- Fixed: HashCode and toString method would crash if the Object
Key/Value was null
- Added: AbstractTypeCollection now delegates the contains check to
type-specific Collections if it detects it.
- Fixed: Map.Entry toString wasn't writing values not like it should do.
- Fixed: Set.hashCode now is the sum of the elements instead of a Unique
HashCode based on the elements.
- Fixed: Added missing NonNull Checks.
- Fixed: OpenHashMap.containsValue implementation was wrong.
- Fixed: OpenHashMap.compute/present/absent now works how it is
specified in the Java Documentation
- Fixed: OpenHashMap.merge/BulkMerge now works how it is specified in
the Java Documentation
- Fixed: OpenHashMap.keySet.remove was causing a infinite loop.
- Fixed: OpenHashMap.mapIterator now no longer crashes in certain cases.
2021-12-10 05:54:37 +01:00
Speiger 52caa9cdd2 Doc Update 2021-12-10 03:27:33 +01:00
Speiger c6afdb8762 New Tests & Fixes
- Added: Tests for the new Stream replace functions to ensure no bugs
are left.
- Fixed: Custom HashSet reduce function with a default value was
checking incorrectly for present keys.
2021-12-10 03:23:28 +01:00
Speiger c4964806f0 Loads of new features & fixes.
- Added: pour function directly into Iterable which allows to collect
all elements in the Iterable directly.
- Added: The new ToArray method from Java9 and newer into the library.
Using a functional interface. (Just a backport)
- Changed: Reworked how the Map Builder functions are created. They are
now in a SubClass that moves them out of the way. Less Clutter. (This
might break things if that was used before)
- Added: Map Builder that allows now to Build Maps like Guava
ImmutableMaps can be build. Note: This has a slight performance
overhead.
- Added: Unmodifiable and Synchronize wrapper functions direclty into
Collection Interfaces. This is mostly a quality of life thing.
- Added: Unmodifiable and Synchronized Wrapper Collections can now be
cloned. They clone the underlying map which doesn't break functionality.
(Had a usecase for it)
- Added: A boxed putAll array variant.
- Fixed: EnumMaps didn't keep track of their size and now got proper
care and implementations as needed. There might be more work required
but at least the core functionality is now up to date.
2021-12-09 09:14:55 +01:00
Speiger a2506b927a New Small feature
- Added: 2 Helper functions to find out how many bits are required to
store a Number.
2021-11-30 16:20:08 +01:00
Speiger 53061d9f78 Update Readme 2021-10-30 07:42:13 +02:00
Speiger 2555dc7fc2 Version Bump 2021-10-30 07:39:05 +02:00
Speiger 058087e15a Added some more tests for some of the new functions 2021-10-30 07:21:41 +02:00
Speiger c20c6393e5 Added Better forEach support for Iterables. 2021-10-29 17:23:52 +02:00
Speiger a25ec85ba2 Added Reduce function to all implementations 2021-10-29 16:03:39 +02:00
Speiger c930bda7a6 Added RemoveSwap 2021-10-28 23:39:19 +02:00
Speiger e7bc242292 Fixes and a lot new features. But still WIP
- Fixed: Supplier get function wasn't referencing original function.
- Added: addIfPresent/Absent to lists
- Added: distinct, limit and peek iterators
- Added: Iterable's can now reduce its contents
2021-10-27 14:09:19 +02:00
Speiger b90a9ec7d8 Added new Remove/RetainAll function to Collection 2021-10-24 01:11:11 +02:00
Speiger d18a35d9b7 Updated Readme to include deprecation of to old patches to save on space 2021-10-11 19:39:09 +02:00
Speiger ffc34a131f New Features and Bugfixes.
- Fixed: ObjectArrayList.of was causing crashes because of a Poor
implementation.
- Added: Unsorted HashMaps/Sets now throw Concurrent exceptions if they
were modified during a rehash.
- Added: Array/Collection version of enqueue and enqueueFirst to
PriorityQueues.
- Added: fillBuffer function into PrimitiveLists which allow to optimize
JavaNio buffers if needed.
2021-10-11 19:05:54 +02:00
Speiger a38e7b069a More Consistency and more features.
- Added: Wrapper now support the Optimized Lambda replacer functions to
improve performance.
- Added: FIFO Queue has now a minimum capacity and that is now checked
more consistently.
- Added: Changelog & Version Bump
2021-10-07 14:50:52 +02:00
Speiger 9c15980e68 Version Bump 2021-10-06 20:53:19 +02:00
Speiger a05689017e Update information 2021-10-06 20:33:11 +02:00
Speiger 54c9660145 New Tests & BugFixes
-Added: Tests for the Copying of Collections.
-Fixed: PriorityQueues didn't have hashCode/equals/toString implemented
2021-10-06 20:23:40 +02:00
Speiger 0c4ef7f6c4 Queues are now copyable 2021-10-06 18:47:15 +02:00
Speiger 61d7a88c82 Maps are now copyable too 2021-10-06 18:32:10 +02:00
Speiger dff173222d Collections are now copyable 2021-10-06 17:48:37 +02:00
Speiger 6eded1f4be Sets are now Copyable 2021-10-06 17:43:46 +02:00
Speiger 07b715dd4c Start of adding copyable collections. Starting with Lists. 2021-10-06 16:30:53 +02:00
Speiger 1f1aa995df Release of 0.4.1 2021-09-29 02:11:29 +02:00
Speiger 1e2703acf2 ChangelogUpdate 2021-09-28 13:23:41 +02:00
Speiger 07abba6312 New Features
-Added: Count method for Iterable
-Fixed: A couple of bugs with the new stream removers not working well in LinkedCollections
2021-09-28 13:20:05 +02:00
Speiger 3f872463b6 Fixed a Rule Break with the new ComputeIfAbsent function 2021-09-28 12:26:44 +02:00
Speiger 531443531d New Features.
-Added: Suppliers.
-Added: ComputeIfAbsent but value generator is a supplier
2021-09-28 12:06:51 +02:00
Speiger 49c5e9eadd Changes.
-Added: New Changes to Changelog
-Fixed: Missing Autogenerated Type
-Cleanup: Gradle file got cleaned up from things it no longer needs.
-Changed: Upgraded to SCG 1.0.5 for incoming new features.
2021-09-28 04:43:04 +02:00
Speiger 3c5769e0e2 Added java type support for Stream replacer functions. 2021-09-28 03:34:53 +02:00
Speiger 0e061921e9 New Features and improvements
-Added: addAll array function.
-Fixed: forEach with input now puts the input at the key instead of value
2021-09-28 03:23:21 +02:00
Speiger edca820634 Version 0.4.0 Release and Readme Update 2021-09-20 01:41:24 +02:00
Speiger bc7afad793 Last Minute Fixes 2021-09-20 00:52:23 +02:00
Speiger 86dbed4bf9 Added Essential Methods 2021-09-19 22:36:23 +02:00
Speiger 2f31d7b641 Updated Changelog a bit 2021-09-19 22:34:46 +02:00
Speiger ef0b9d23c3 Added Pairs 2021-09-19 22:31:04 +02:00
Speiger 6e30a54ead Cleanup Space are now converted into tabs. 2021-09-19 19:38:05 +02:00
Speiger fa3cf743f9 TreeSubSets (RB/AVL) got their functional implementations improved too. 2021-09-19 18:03:02 +02:00
Speiger 5b67e85009 RBTreeMap got now the same improvements like AVLTreeMap 2021-09-19 17:41:54 +02:00
Speiger 59c4d1aa90 Changelog update 2021-09-18 10:31:51 +02:00
Speiger abc1c075f5 AVLTreeMap gets some love regarding forEach/etc 2021-09-18 10:30:28 +02:00
Speiger 4aac66b6fb Updated Changelog 2021-09-16 23:56:11 +02:00
Speiger 17f0dddf20 Refactor and New Features
-Changed: Refactored some variable names because they got out of hand since they were handed for single cases instead of making actual specific rules.
-Added: mapping functions (only to objects) are now accessible to primitive collections.
-Added: Filter function for Iterables/Iterators. (Iterable implements them automatically)
2021-09-16 23:53:57 +02:00
Speiger c5720e591c Changelog update 2021-09-16 02:58:50 +02:00
Speiger 796cd7c007 New Implementations & Fixes (Tree Maps get soon more love too)
-Added: New Implementations for new Iterable functions.
-Fixed: Reduced the Conditional Code by adding better Variables.
-Changed: Removed a lot of duplicated for each methods.
2021-09-16 02:57:09 +02:00
Speiger c9cd62f5d7 New Fixes
- Fixed: Compute/ComputeIfAbsent/ComputeIfPresent/Merge/BulkMerge in
maps now behave like they should.
2021-09-15 05:44:19 +02:00
Speiger fc1a738625 Started Next larger patch.
- Changed: Iterable specific helper functions were moved out of
Iterators and moved into Iterables
- Added: New Stream replacing functions: findFirst, matchesAny/All/None
2021-09-15 05:09:14 +02:00
Speiger 854678fd3c Added Specialized Collection functions to the documentation. 2021-09-14 17:19:27 +02:00
Speiger 3fa75ba18e Updated Maven Build 2021-09-13 17:54:10 +02:00
Speiger 212f532350 Fixed small logic error in clearAndTrim (Maps/Sets) 2021-09-13 17:15:40 +02:00
Speiger 29f2b8e305 Updated Description/Version/Changelog 2021-09-13 17:09:31 +02:00
Speiger e30ca4103f Fixed recent found bugs
-Fixed: addAll with non Specific Collections was crashing lists.
-Fixed/Refactor: Clear and trim implementation was all over the place
-Fixed: Wrappers toString/hashCode/equals function wasn't implemented
-Added: Tests for addAll bug
-Refactor: Did small code style cleanups as I was fixing bugs.
2021-09-13 17:02:24 +02:00
Speiger ec817fb9c2 Added found bugs to the Readme so people can avoid them util a fix 2021-09-13 01:08:11 +02:00
Speiger 88918dfb35 Updated known bugs 2021-09-03 10:52:03 +02:00
Speiger 0f072ddd59 Updated Release Version 2021-09-02 13:49:25 +02:00
Speiger a1b422dbe8 Version Bump 2021-09-02 13:41:47 +02:00
Speiger 3af5ca49cc Small Fix
- Fixed: Dependency to SimpleCodeGenerator should be no longer a thing.
Because the resulting library doesn't need it only the builder does.
2021-09-02 13:40:33 +02:00
Speiger 117d0f36e6 New Fixes
- Fixed: ObjectLists Crashed when a null was provided as a Comparator.
(Unless the List was Initialized with the ClassType)
- Fixed: LinkedLists didn't implement add(Object)
- Fixed: Object Collections did have the JavaCollections deprecated as
the Constructor. This should only be deprecated for Primitives
- Added: Tests with 5k Random names for Object sorting.
- Changed: Object Arrays no longer require a Comparable[] it just
assumes now that the elements in the Array are Comparable
2021-09-02 13:38:25 +02:00
Speiger aa1e7da38c Code generator was wrongly added as a required dependency. 2021-08-27 07:45:41 +02:00
Speiger ea83f5017e Hotfixing a bug where ArrayLists didn't resize Properly when empty 2021-08-15 18:09:34 +02:00
Speiger efc3745690 Updated Issues list 2021-08-12 15:08:53 +02:00
Speiger 6ae4a8f582 Updated Feature List 2021-08-12 15:06:04 +02:00
Speiger b46456dd32 Fixed markdown 2021-08-12 15:03:52 +02:00
Speiger 4ae353a0bd Updated Release and added direct downloads 2021-08-12 15:03:05 +02:00
Speiger 45d118a77a New Features and bugfixes.
- Fixed: AbstractCollection bulk adding methods now link to the
specialized implementations.
- Fixed: A bug with getElements in ArrayList.
- Fixed: PriorityQueue remove/toArray function were renamed so they fit
better with other interfaces. (remove => removeFirst and toArray uses a
different genericType)
- Added: LinkedList which is a List/PriorityDequeue/Stack which allows
for more optimized use-cases and reduced boxing/unboxing.
- Added: Tests for LinkedList
2021-08-12 14:31:29 +02:00
Speiger 73916f4fd9 Fixed AVLTrees pollFirst/pollLast 2021-07-23 22:04:59 +02:00
Speiger 4a3cc66401 Added Flat/Mapping Functions for Iterables/Iterators (Object Only) 2021-07-21 16:32:30 +02:00
Speiger 0ed1208d59 Updated Latest Version 2021-06-27 21:43:37 +02:00
Speiger b99abaafec Fixed last second bugs. 2021-06-27 21:31:42 +02:00
Speiger ee02997881 Version Bump 2021-06-27 17:23:55 +02:00
Speiger 626ab29fc7 Lists.addElements(T...elements) was adding elements at the beginning of
a list instead of the end.
2021-06-27 17:23:34 +02:00
Speiger e6c4d43f6e Updated readme a bit. 2021-06-27 16:05:43 +02:00
Speiger 880a9169e5 Maps can now be created through the interface. 2021-06-27 16:02:26 +02:00
Speiger 4c68c925d3 Fixed a bug where exact duplication would break immutableMaps/sets 2021-06-25 21:14:45 +02:00
Speiger 9d17dc17fd Added ImmutableOpenHashMap that is not editable (is linked by default
for fast iteration)
2021-06-25 17:44:48 +02:00
Speiger 84bc785cdc CustomOpenHashSets now implement foreach and have less overhead. 2021-06-25 16:37:17 +02:00
Speiger b784041894 New Features
- Added: OpenHashSets now implement foreach and have less overhead.
- Added: ImmutableOpenHashSet that is not editable (is linked by default
for fast iteration)
2021-06-25 14:22:22 +02:00
Speiger 2b408fb2b2 New Features
- Added: ImmutableList.
- Added: Iterator pour function into a List or Array
- Changed: Arrays Wrap is now accessible to Objects and now is ? extends
TYPE instead of TYPE.
2021-06-25 12:28:19 +02:00
Speiger 8618c10d01 Fixed a crash with Map.put 2021-06-24 20:58:17 +02:00
Speiger dff5e534ff Updated Release Version 2021-06-24 17:21:26 +02:00
Speiger e95e0a3e8f Version Bump 2021-06-24 17:16:59 +02:00
Speiger 3b27604258 More fixes.
- Fixed: containsKey & containsValue in HashMaps were deprecated for
Object Variants.
- Fixed: HashMap wasn't deleting Keys & Values references when removing
a Object
- Fixed: AVLTreeMap didn't balance properly.
- Changed: EnumMap no longer tries to access SharedSecrets since its
gone in java11
- Added: HashMaps now implement ITrimmable
- Added: AVLTreeSet didn't balance properly
- Fixed: HashMaps & LinkedMaps weren't clearing references properly.
2021-06-24 17:16:36 +02:00
Speiger c0fef15e64 More Fixes
- Fixed: containsKey & containsValue in HashMaps were deprecated for
Object Variants.
- Fixed: HashMap wasn't deleting Keys & Values references when removing
a Object
- Fixed: AVLTreeSet didn't balance properly.
- Changed: EnumMap no longer tries to access SharedSecrets since its
gone in java11
2021-06-24 13:17:48 +02:00
Speiger 3c0f4acc05 Fixed a missing import & Updated readme. 2021-06-23 22:17:52 +02:00
Speiger 406a57bb9d Version Bump 2021-06-23 22:14:41 +02:00
Speiger b50307c88d Added PriorityQueues 2021-06-23 22:14:08 +02:00
Speiger a28149ac8d Added Shuffle & Reverse Methods and Concat Iterators. 2021-06-23 21:45:12 +02:00
Speiger b55b049508 Another set of changes.
- Changed: Maps.remove function is no longer using Suffixes unless its
absolutely necessary.
- Changed: ObjectList methods are no longer marked Deprecated even so it
was for primitive ones.
2021-06-23 19:58:31 +02:00
Speiger ce8f49cd1f Maps.get function is no longer using Suffixes unless its absolutely
necessary.
2021-06-23 19:34:32 +02:00
Speiger 357b40e670 PriorityQueues no longer extends Object Variant. 2021-06-23 19:22:19 +02:00
Speiger a669f69d99 Primitive Stacks no longer depend on the base Stack class. 2021-06-23 19:07:30 +02:00
Speiger f4c25c683f Removed Suffixes of unmodifiable & synchronize methods. 2021-06-23 18:53:40 +02:00
Speiger 9f4bede08e Small Additions & Redsign
- Added: Stack.isEmpty was missing
- Changed: remove/removeLast/enqueue/enqueueFirst no longer use Type
Suffixes
2021-06-23 18:38:23 +02:00
Speiger 3676849efc Updated Builder version that no is +Java11 Compatible 2021-06-23 00:23:08 +02:00
Speiger 5ea1e3c358 Got the If switched up. 2021-06-22 19:49:32 +02:00
Speiger 500514fb20 SharedConstants still making issues. 2021-06-22 19:40:48 +02:00
Speiger fd32f404c0 Pushing Wrapper 2021-06-22 17:34:53 +02:00
Speiger d1453fbc95 Adding more info if someone wants to contribute 2021-06-22 16:34:32 +02:00
Speiger 8fee81bd19 Keeping the Primitive Collections Name. 2021-06-22 16:19:19 +02:00
Speiger 7fd54cd094 Testing Multi Remote 2021-06-22 16:13:01 +02:00
Speiger a44e091851 Added Maven Readme 2021-06-22 15:53:52 +02:00
Speiger ed193d9fc0 Moving towards Maven Release. 2021-06-22 15:15:10 +02:00
Speiger ac4dab9d7e Updated Docs 2021-05-31 19:43:01 +02:00
Speiger cbb5dd0ee2 Added Linked Enum Maps 2021-05-31 19:41:57 +02:00
Speiger 57baeb261e Added Implementation specific functions to speed up logic. 2021-05-28 22:10:30 +02:00
Speiger bbcb290560 List Documentation cleanup & added Primitive Parallel Streams 2021-05-28 20:20:45 +02:00
Speiger 17886dde62 Fixes to SubSets.
-Fixed: ToArray implementation works now.
-Fixed: Creating SubSets from subsets is now no longer 1 element to small.
2021-05-28 20:08:04 +02:00
Speiger 998272c8d5 Added TrimAndClear function into ITrimmable 2021-05-26 13:06:52 +02:00
Speiger 13b2c727fc Added Identity HashMap support via Strategies 2021-05-22 06:08:27 +02:00
Speiger 7fcfecf308 New Features.
-Added: removeOrDefault function
-Added: New functions into implementations
2021-05-22 05:50:40 +02:00
Speiger a319e0136a Added New Utility methods.
-Added: bulk putIfAbsent & AddTo function
-Added: ArrayPut method simplify adding arrays into a map.
-Added: Bulk Replace function that uses a "Map" instead of a lambda
-Added: Bulk Merge function
2021-05-22 05:26:44 +02:00
97 changed files with 23177 additions and 1638 deletions
+1 -1
View File
@@ -38,7 +38,7 @@
<attribute name="gradle_used_by_scope" value="builder"/> <attribute name="gradle_used_by_scope" value="builder"/>
</attributes> </attributes>
</classpathentry> </classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/> <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8/"/>
<classpathentry kind="con" path="org.eclipse.buildship.core.gradleclasspathcontainer"/> <classpathentry kind="con" path="org.eclipse.buildship.core.gradleclasspathcontainer"/>
<classpathentry kind="output" path="bin/default"/> <classpathentry kind="output" path="bin/default"/>
</classpath> </classpath>
+1 -4
View File
@@ -1,13 +1,11 @@
# ---> Gradle # ---> Gradle
.gradle .gradle
/build/ /build/
gradle.properties
# Ignore Gradle GUI config # Ignore Gradle GUI config
gradle-app.setting gradle-app.setting
# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored)
!gradle-wrapper.jar
# Cache of project # Cache of project
.gradletasknamecache .gradletasknamecache
@@ -16,7 +14,6 @@ gradle-app.setting
.classpath .classpath
.project .project
gradle-wrapper.jar
---> Custom ---> Custom
!/libs/ !/libs/
+144
View File
@@ -0,0 +1,144 @@
# Changelog of versions
### Version 0.5.0
- Added: 2 Helper functions to find out how many bits are required to store a Number.
- Added: pour function directly into Iterable which allows to collect all elements in the Iterable directly.
- Added: The new ToArray method from Java9 and newer into the library. Using a functional interface. (Just a backport)
- Changed: Reworked how the Map Builder functions are created. They are now in a SubClass that moves them out of the way. Less Clutter. (This might break things if that was used before)
- Added: Map Builder that allows now to Build Maps like Guava ImmutableMaps can be build. Note: This has a slight performance overhead.
- Added: Unmodifiable and Synchronize wrapper functions direclty into Collection Interfaces. This is mostly a quality of life thing.
- Added: Unmodifiable and Synchronized Wrapper Collections can now be cloned. They clone the underlying map which doesn't break functionality. (Had a usecase for it)
- Added: A boxed putAll array variant.
- Fixed: EnumMaps didn't keep track of their size and now got proper care and implementations as needed. There might be more work required but at least the core functionality is now up to date.
- Added: Tests for the new Stream replace functions to ensure no bugs are left.
- Fixed: Custom HashSet reduce function with a default value was checking incorrectly for present keys.
- Added: Guava TestSuit
- Fixed: HashCode and toString method would crash if the Object Key/Value was null
- Added: AbstractTypeCollection now delegates the contains check to type-specific Collections if it detects it.
- Fixed: Map.Entry toString wasn't writing values not like it should do.
- Fixed: Set.hashCode now is the sum of the elements instead of a Unique HashCode based on the elements.
- Fixed: Added missing NonNull Checks.
- Fixed: Custom/OpenHashMap.containsValue implementation was wrong.
- Fixed: Custom/OpenHashMap.compute/present/absent now works how it is specified in the Java Documentation
- Fixed: Custom/OpenHashMap.merge/BulkMerge now works how it is specified in the Java Documentation
- Fixed: Custom/Linked/OpenHashMap.keySet.remove was causing a infinite loop.
- Fixed: Custom/Linked/OpenHashMap.entrySet.contains was not correctly comparing the entry.
- Fixed: Custom/OpenHashMap.mapIterator now no longer crashes in certain cases.
- Added: Custom/LinkedOpenHashMap now takes use of the improved Iterator it has for containsValue
- Fixed: CustomOpenHashMap.keySet.forEach was basically putting out keys even if they were present
- Fixed: ImmutableMaps issues thanks to the tests. Roughly the same as the rest of the maps
- Fixed: RB/AVLTreeMaps issues. Roughly the same as the rest of the maps
- Fixed: SubLists are now properly implemented.
- Fixed: HashSet Iterator bugs now fixed... That was Painful.
- Added: Tests for Lists and Sets
### Version 0.4.5
- Added: removeAll/retainAll(Collection c, Consumer r) which receives all the elements that got deleted from the collection
- Fixed: Supplier get function wasn't referencing original function.
- Added: addIfPresent/Absent to lists
- Added: distinct, limit and peek iterators
- Added: Iterable's can now reduce its contents
- Added: Better ForEach support for IterableWrappers so a Iterator chain is not created
- Added: SwapRemove to Lists which moves the last element into the desired space to be deleted
- Added: More Test cases
### Version 0.4.4
- Fixed: ObjectArrayList.of was causing crashes because of a Poor implementation.
- Added: Unsorted HashMaps/Sets now throw Concurrent exceptions if they were modified during a rehash.
- Added: Array/Collection version of enqueue and enqueueFirst to PriorityQueues.
- Added: fillBuffer function into PrimitiveLists which allow to optimize JavaNio buffers if needed.
### Version 0.4.3
- Added: Wrapper now support the Optimized Lambda replacer functions to improve performance.
- Added: FIFO Queue has now a minimum capacity and that is now checked more consistently.
### Version 0.4.2
- Added: Lists/Sets/Maps/PriorityQueues are now copy-able. with the new copy() function.
Note: subLists/subMaps/subSets or synchronize/unmodifyable wrappers do not support that function.
- Fixed: PriorityQueues didn't implement: hashCode/equals/toString
### Version 0.4.1
- Changed: ForEach with input now provides input, value instead of value, input, this improves the usage of method references greatly
- Added: addAll with Array-types in collections.
- Added: Java Iterator/Iterable support for Stream replacing methods
- Added: Suppliers.
- Added: SupplyIfAbsent. It is ComputeIfAbsent but using suppliers
- Added: Count feature into Iterable
- Fixed: A couple bugs with the new StreamReplacing functions in LinkedCollections Iterating to Infinity
### Version 0.4.0
- Changed: Iterable specific helper functions were moved out of Iterators and moved into Iterables
- Added: New Stream replacing functions: findFirst, matchesAny/All/None
- Fixed: Compute/ComputeIfAbsent/ComputeIfPresent/Merge/BulkMerge in maps now behave like they should.
- Added: Implementations for New Stream replacing functions.
- Changed: Removed a lot of duplicated forEach implementations
- Added: Flat/Mapping functions (to object) are now accessible to primitive maps.
- Added: Filter function to Iterators/Iterables (Iterable implements it by default)
- Changed: Cleanup of some variables/mappers
- Added/Fixed: AVL/RBTreeMap got reworked and SubMaps work more properly now. Also forEach support got improved a lot
- Added/Fixed: TreeSubSets (RB/AVL) got their functional implementations improved too.
- Added: Pairs are now a thing. In Mutable/Immutable Form
### Version 0.3.6
- Fixed: addAll non Type Specific Lists was causing crashes.
- Fixed/Changed: clearAndTrim's implementation was all over the place. In some cases causing crash scenarios.
- Fixed: Wrappers didn't implement toString/equals/hashCode
- Added: Tests for addAll Bug
- Changed: Cleaned up CodeStyle as bugs were fixed.
### Version 0.3.5
- Fixed: Simple Code Generator dependency was declared wrong. Its only needed for runtime. Not for Compilation.
- Fixed: ObjectLists Crashed when a null was provided as a Comparator. (Unless the List was Initialized with the ClassType)
- Fixed: LinkedLists didn't implement add(Object)
- Fixed: Object Collections did have the JavaCollections deprecated as the Constructor. This should only be deprecated for Primitives
- Added: Tests with 5k Random names for Object sorting.
- Changed: Object Arrays no longer require a Comparable[] it just assumes now that the elements in the Array are Comparable
- Fixed: Dependency to SimpleCodeGenerator should be no longer a thing. Because the resulting library doesn't need it only the builder does.
### Version 0.3.4
- Fixed: ArrayLists didn't resize properly if they were empty.
### Version 0.3.3
- Added: Flat/Mapping function for Iterables/Iterators to help avoid streams for cleaner looking code
- Fixed: AVLTrees pollFirst/Last is now keeping orders and is fixed
- Fixed: AbstractCollection bulk adding methods now link to the specialized implementations.
- Fixed: A bug with getElements in ArrayList.
- Fixed: PriorityQueue remove/toArray function were renamed so they fit better with other interfaces. (remove => removeFirst and toArray uses a different genericType)
- Added: LinkedList which is a List/PriorityDequeue/Stack which allows for more optimized use-cases and reduced boxing/unboxing.
- Added: Tests for LinkedList
### Version 0.3.2
- Fixed: Map.put wasn't referring to primitive variants.
- Added: ImmutableList.
- Added: Iterator pour function into a List or Array
- Changed: Arrays Wrap is now accessible to Objects and now is ? extends TYPE instead of TYPE.
- Added: OpenHashSets now implement foreach and have less overhead.
- Added: ImmutableOpenHashSet that is not editable (is linked by default for fast iteration)
- Added: CustomOpenHashSets now implement foreach and have less overhead.
- Added: ImmutableOpenHashMap that is not editable (is linked by default for fast iteration)
- Added: Maps can now be created through the interface.
- Fixed: Lists.addElements(T...elements) was adding elements at the beginning of a list instead of the end.
- Fixed: Bugs with the AVLTreeSet. And marked bugs with AVLTreeX that are still present.
### Version 0.3.1
- Fixed: containsKey & containsValue in HashMaps were deprecated for Object Variants.
- Fixed: HashMap wasn't deleting Keys & Values references when removing a Object
- Fixed: AVLTreeMap didn't balance properly.
- Changed: EnumMap no longer tries to access SharedSecrets since its gone in java11
- Added: HashMaps now implement ITrimmable
- Added: AVLTreeSet didn't balance properly
- Fixed: HashMaps & LinkedMaps weren't clearing references properly.
### Version 0.3.0 (Breaking 0.2.0)
- Added: Stack.isEmpty was missing
- Changed: remove/removeLast/enqueue/enqueueFirst no longer use Type Suffixes
- Removed: Suffixes for unmodifiable & synchronize functions.
- Changed: Primitive Stacks no longer depend on the base Stack class. Because seriously not needed.
- Changed: PriorityQueues no longer extends Object Variant.
- Changed: Maps.get function is no longer using Suffixes unless its absolutely necessary.
- Changed: Maps.remove function is no longer using Suffixes unless its absolutely necessary.
- Changed: ObjectList methods are no longer marked Deprecated even so it was for primitive ones.
- Added: Shuffle & Reverse Methods.
- Added: Concat Iterators.
- Added: PriorityQueues
+123 -7
View File
@@ -1,22 +1,138 @@
# Primitive-Collections (To be Renamed) # Primitive-Collections
This is a Simple Primitive Collections Library i started as a hobby Project. This is a Simple Primitive Collections Library i started as a hobby Project.
It is based on Java's Collection Library and FastUtil. It is based on Java's Collection Library and FastUtil.
But its focus is a different one. But its focus is a different one.
## Main Features: ## Main Features:
ArraysList, HashSet/Map (Linked & HashControl), TreeSet/Map (RB & AVL), Priority Queue. - ArrayLists / LinkedLists
- HashSet/Map (Linked & HashControl)
- TreeSet/Map (RB & AVL)
- EnumMap
- Immutable Maps/Lists/Sets
- Priority Queue
- Streams & Functional Queries
- SplitIterators
- Iterators
- Pairs
- Unary/Functions
- Suppliers
- Bi/Consumers
# Guide ## Current Level of Stability
Since this is a relatively new Library, stability was not perfect and some areas are not perfect yet.
Thanks to [ben-manes](https://github.com/ben-manes) we now have Roughly 16000 test covering Maps/Sets/Lists.
These tests cover Javas Collection API completely and ensuring a Stable implementation.
These freshly added tests allowed me to squash thousands of issues according to Googles Test Library (Guava-Tests).
These will be expanded on as time goes on.
The SourceCode can be already generated via: One know aspect of Instability is SubSets and SubMaps. They require full rewrites to be fully stable.
So it is not advised to use them until these issues are addressed.
PriorityQueues are tested separately and ensure basic functionality though GuavaTests are planned.
They just require a custom test implementation.
As a summary: Stability is good/excellent, unless you need SubSets/SubMaps
## Specialized Functions
New Specialized functions that were added to increase performance or reduce allocations or Quality Of life.
To highlight things that may be wanted.
- Iterable:
- map/flatMap/arrayFlatMap: A Light weight version of Stream.map().
- findFirst: Allows to find the first element of a Predicated Iterable.
- filter: Allows to filter unwanted elements for wrapped Iterable
- matchAny/matchNone/matchAll: Allows to find elements in a collection.
- count: counts all valid elements in a collection.
- forEach: Allows to input a second element into a forEach move allowing for more flexibility for Method References
- reduce/limit/peek/distinct: Light Versions of the Stream variant, to reduce Stream usage.
- pour: a function that allows to collect all elements within the Collection
- Collection:
- containsAny: Allows to test if another collection contains an of the elements of the tested collection.
- primitiveStream: Provides access to the closest Java Stream Type.
- copy: shallowCopies the collection, used instead of clone because this is better to use.
(subCollections not supported for obvious reasons)
- toArray: the ToArray function from Java9 and newer that uses a Functional interface and can use a method reference
- List:
- add/get/removeElements (From FastUtil): Allows to add/get/remove an Array into/from a list. Just with less overhead
- extractElements: Allows to remove a Range of elements from the List and get what was removed.
- Unstable Sort(From FastUtil): Uses a faster but not stable sort (Quick-Sort as example) to sort the list.
- addIfAbsent/Present: adds a element only if absent/present in the list
- swapRemove: deletes a desired element and inserts the last element in its place instead of leftshifting elements.
- SortedSet:
- addAndMoveToFirst/Last (From FastUtil but moved to Interface): Allows to add a element to the first/last position of a sorted set.
- moveToFirst/Last: Moves the desired element at the first/last position of the SortedSet.
- pollFirst/Last: Allows to poll the first/last element of the set.
- Map:
- putAll: putAll but in Array form.
- putAllIfAbsent: Puts only the elements that are absent.
- addTo (Only Primitives Values) (From FastUtil but moved to Interface): allows to add to the value of a given key. If not present it will be added. (Accumulator)
- addToAll: Same as addTo but bulkVersion.
- removeOrDefault: removes a Element and if not present returns the default value instead of the present value.
- mergeAll: BulkVersion of Merge function.
- supplyIfAbsent: A Supplier based computeIfAbsent
- Sorted Map:
- addAndMoveToFirst/Last (From FastUtil but moved to Interface): Allows to add a element to the first/last position of a sorted Map.
- moveToFirst/Last: Moves the desired element at the first/last position of the Map.
- getAndMoveToFirst/Last: gets the element and moves it to the first/last position. Replicating a Optional LinkedHashMap feature.
- pollFirst/LastKey: Allows to poll the first/last element.
- first/LastValue: Allows to get the first/last value from the Map.
# Notes about Versions
Any 0.x.0 version (Minor) can be reason for massive changes including API.
To ensure that problems can be dealt with even if it is breaking the current API.
Any breaking changes will be Documented (once 1.0 is released)
Also to save space every 0.0.x (Patch) that is 2 Minor Versions behind will be removed.
So if 0.5.0 is released every 0.3.x patch will be deleted, except for the last patch for that minor version.
# How to install
Using Gradle:
```gradle
repositories {
maven {
url = "https://maven.speiger.com/repository/main"
}
}
dependencies {
compile 'de.speiger:Primitive-Collections:0.5.0'
}
```
Direct:
| Version | Jar | Sources | Java Doc |
|--------- |------------------------------------------------------------------------------------------------------------------------------ |-------------------------------------------------------------------------------------------------------------------------------------- |-------------------------------------------------------------------------------------------------------------------------------------- |
| 0.5.0 | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.5.0/Primitive-Collections-0.5.0.jar) | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.5.0/Primitive-Collections-0.5.0-sources.jar) | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.5.0/Primitive-Collections-0.5.0-javadoc.jar) |
| 0.4.5 | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.4.5/Primitive-Collections-0.4.5.jar) | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.4.5/Primitive-Collections-0.4.5-sources.jar) | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.4.5/Primitive-Collections-0.4.5-javadoc.jar) |
| 0.4.4 | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.4.4/Primitive-Collections-0.4.4.jar) | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.4.4/Primitive-Collections-0.4.4-sources.jar) | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.4.4/Primitive-Collections-0.4.4-javadoc.jar) |
| 0.4.3 | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.4.3/Primitive-Collections-0.4.3.jar) | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.4.3/Primitive-Collections-0.4.3-sources.jar) | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.4.3/Primitive-Collections-0.4.3-javadoc.jar) |
| 0.4.2 | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.4.2/Primitive-Collections-0.4.2.jar) | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.4.2/Primitive-Collections-0.4.2-sources.jar) | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.4.2/Primitive-Collections-0.4.2-javadoc.jar) |
| 0.4.1 | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.4.1/Primitive-Collections-0.4.1.jar) | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.4.1/Primitive-Collections-0.4.1-sources.jar) | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.4.1/Primitive-Collections-0.4.1-javadoc.jar) |
| 0.4.0 | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.4.0/Primitive-Collections-0.4.0.jar) | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.4.0/Primitive-Collections-0.4.0-sources.jar) | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.4.0/Primitive-Collections-0.4.0-javadoc.jar) |
| 0.3.6 | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.3.6/Primitive-Collections-0.3.6.jar) | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.3.6/Primitive-Collections-0.3.6-sources.jar) | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.3.6/Primitive-Collections-0.3.6-javadoc.jar) |
# Contributing
If you want to contribute.
This project is created using gradle and java and my Template Library only. Nothing extra.
If you setup gradle the library will be downloaded automatically.
Where is everything stored?
- Variables and ClassNames are define [here](src/builder/java/speiger/src/builder/GlobalVariables.java)
- Templates are stored [here](src/builder/resources/speiger/assets/collections/templates)
- Tests can be found [here](src/test/java/speiger/src/collections)
Please if you want to contribute follow the [Rule-Sheet](RuleSheet.md). It keeps everything in line.
# How to Build
The SourceCode can be generated via:
/gradlew.bat generateSource /gradlew.bat generateSource
to build the jar
to build the jar:
/gradlew.bat build /gradlew.bat build
do not combine the commands because they can not be executed at the same time. do not combine the commands because they can not be executed at the same time.
## Current Down Sides (Random order) ## Current Down Sides (Random order)
- EnumMaps are only normal maps no Linked Support yet - SubMaps/Set implementation isn't perfect right now. This will be addressed slowly due to rewrites required.
- Testing for Sub Maps/Sets/Lists are only in a very basic way tested
- Documentation is only present at the lowest level for most cases and needs a typo fixing. - Documentation is only present at the lowest level for most cases and needs a typo fixing.
+48 -18
View File
@@ -8,16 +8,17 @@ tasks.withType(JavaCompile) {
apply plugin: 'java' apply plugin: 'java'
apply plugin: 'eclipse' apply plugin: 'eclipse'
apply plugin: 'maven'
repositories { repositories {
jcenter() mavenCentral()
flatDir { maven {
dirs 'libs' url = "https://maven.speiger.com/repository/main"
} }
} }
archivesBaseName = 'Primitive Collections' archivesBaseName = 'Primitive Collections'
version = 'Beta'; version = '0.5.0';
sourceCompatibility = targetCompatibility = compileJava.sourceCompatibility = compileJava.targetCompatibility = '1.8' sourceCompatibility = targetCompatibility = compileJava.sourceCompatibility = compileJava.targetCompatibility = '1.8'
@@ -29,21 +30,9 @@ eclipse {
classpath { classpath {
downloadJavadoc = true downloadJavadoc = true
downloadSources = true downloadSources = true
file {
whenMerged {
//Enforce a custom container and allowing access to the sun.misc package which is nessesary for EnumMaps
entries.find{ it.kind == 'con' && it.path.startsWith('org.eclipse.jdt')}.path = 'org.eclipse.jdt.launching.JRE_CONTAINER';
}
}
} }
} }
compileJava {
options.compilerArgs << '-XDignore.symbol.file'
options.fork = true // may not needed on 1.8
options.forkOptions.executable = 'javac' // may not needed on 1.8
}
sourceSets { sourceSets {
builder builder
} }
@@ -53,8 +42,11 @@ configurations {
} }
dependencies { dependencies {
compile 'SimpleCodeGenerator:Simple Code Generator:1.0.1' builderCompile 'de.speiger:Simple-Code-Generator:1.0.5'
runtimeOnly 'de.speiger:Simple-Code-Generator:1.0.5'
testImplementation 'junit:junit:4.12' testImplementation 'junit:junit:4.12'
testImplementation 'com.google.guava:guava-testlib:31.0.1-jre'
} }
task generateSource(type: JavaExec) { task generateSource(type: JavaExec) {
@@ -64,6 +56,14 @@ task generateSource(type: JavaExec) {
main = 'speiger.src.builder.PrimitiveCollectionsBuilder' main = 'speiger.src.builder.PrimitiveCollectionsBuilder'
} }
task forceGenerateSource(type: JavaExec) {
group = 'internal'
description = 'Builds the sourcecode forceful'
classpath = sourceSets.builder.runtimeClasspath
main = 'speiger.src.builder.PrimitiveCollectionsBuilder'
args = ['true']
}
task javadocJar(type: Jar) { task javadocJar(type: Jar) {
from javadoc from javadoc
classifier = 'javadoc' classifier = 'javadoc'
@@ -76,7 +76,6 @@ task srcJar(type: Jar) {
javadoc.failOnError = false javadoc.failOnError = false
javadoc.options.memberLevel = JavadocMemberLevel.PUBLIC javadoc.options.memberLevel = JavadocMemberLevel.PUBLIC
//javadoc.options.showAll()
javadoc.options.quiet() javadoc.options.quiet()
artifacts { artifacts {
@@ -87,3 +86,34 @@ artifacts {
test { test {
useJUnit() useJUnit()
} }
uploadArchives {
repositories.mavenDeployer {
repository(url: 'https://maven.speiger.com/repository/main') {
authentication(userName: project.properties.mavenUser, password: project.properties.mavenPassword)
}
snapshotRepository(url: 'https://maven.speiger.com/repository/main') {
authentication(userName: project.properties.mavenUser, password: project.properties.mavenPassword)
}
pom {
version = project.version
artifactId = project.archivesBaseName.replace(" ", "-")
groupId = 'de.speiger'
project {
licenses {
license {
name = 'The Apache License, Version 2.0'
url = 'http://www.apache.org/licenses/LICENSE-2.0.txt'
}
}
developers {
developer {
id = 'speiger'
name = 'Speiger'
email = 'speiger@gmx.net'
}
}
}
}
}
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -35,28 +35,51 @@ public class GlobalVariables
addSimpleMapper("CLASS_TYPE", type.getClassType()); addSimpleMapper("CLASS_TYPE", type.getClassType());
addSimpleMapper("CLASS_VALUE_TYPE", valueType.getClassValueType()); addSimpleMapper("CLASS_VALUE_TYPE", valueType.getClassValueType());
addSimpleMapper("KEY_TYPE", type.getKeyType()); addSimpleMapper("KEY_TYPE", type.getKeyType());
addSimpleMapper("KEY_SPECIAL_TYPE", type.isObject() ? "E" : type.getKeyType());
addSimpleMapper("VALUE_TYPE", valueType.getValueType()); addSimpleMapper("VALUE_TYPE", valueType.getValueType());
addSimpleMapper("VALUE_SPECIAL_TYPE", valueType.isObject() ? "E" : valueType.getKeyType());
addSimpleMapper("EMPTY_KEY_VALUE", type.getEmptyValue()); addSimpleMapper("EMPTY_KEY_VALUE", type.getEmptyValue());
addSimpleMapper("EMPTY_VALUE", valueType.getEmptyValue()); addSimpleMapper("EMPTY_VALUE", valueType.getEmptyValue());
addSimpleMapper(" KEY_GENERIC_TYPE", type.isObject() ? "<"+type.getKeyType()+">" : ""); addSimpleMapper(" KEY_GENERIC_TYPE", type.isObject() ? "<"+type.getKeyType()+">" : "");
addSimpleMapper(" KEY_KEY_GENERIC_TYPE", type.isObject() ? "<"+type.getKeyType()+", "+type.getKeyType()+">" : ""); addSimpleMapper(" KEY_KEY_GENERIC_TYPE", type.isObject() ? "<"+type.getKeyType()+", "+type.getKeyType()+">" : "");
addSimpleMapper(" VALUE_GENERIC_TYPE", valueType.isObject() ? "<"+valueType.getValueType()+">" : ""); addSimpleMapper(" VALUE_GENERIC_TYPE", valueType.isObject() ? "<"+valueType.getValueType()+">" : "");
addSimpleMapper(" VALUE_VALUE_GENERIC_TYPE", valueType.isObject() ? "<"+valueType.getValueType()+", "+valueType.getValueType()+">" : ""); addSimpleMapper(" VALUE_VALUE_GENERIC_TYPE", valueType.isObject() ? "<"+valueType.getValueType()+", "+valueType.getValueType()+">" : "");
addSimpleMapper(" KEY_VALUE_GENERIC_TYPE", type.isObject() ? (valueType.isObject() ? "<"+type.getKeyType()+", "+valueType.getValueType()+">" : "<"+type.getKeyType()+">") : (valueType.isObject() ? "<"+valueType.getValueType()+">" : "")); addSimpleMapper(" KEY_VALUE_GENERIC_TYPE", type.isObject() ? (valueType.isObject() ? "<"+type.getKeyType()+", "+valueType.getValueType()+">" : "<"+type.getKeyType()+">") : (valueType.isObject() ? "<"+valueType.getValueType()+">" : ""));
addSimpleMapper(" KEY_VALUE_VALUE_GENERIC_TYPE", type.isObject() ? (valueType.isObject() ? "<"+type.getKeyType()+", "+valueType.getValueType()+", "+valueType.getValueType()+">" : "<"+type.getKeyType()+">") : (valueType.isObject() ? "<"+valueType.getValueType()+", "+valueType.getValueType()+">" : "")); addSimpleMapper(" KEY_VALUE_VALUE_GENERIC_TYPE", type.isObject() ? (valueType.isObject() ? "<"+type.getKeyType()+", "+valueType.getValueType()+", "+valueType.getValueType()+">" : "<"+type.getKeyType()+">") : (valueType.isObject() ? "<"+valueType.getValueType()+", "+valueType.getValueType()+">" : ""));
addSimpleMapper(" NO_GENERIC_TYPE", type.isObject() ? "<?>" : ""); addSimpleMapper(" NO_GENERIC_TYPE", type.isObject() ? "<?>" : "");
addSimpleMapper(" NO_KV_GENERIC_TYPE", type.isObject() ? (valueType.isObject() ? "<?, ?>" : "<?>") : valueType.isObject() ? "<?>" : ""); addSimpleMapper(" NO_KV_GENERIC_TYPE", type.isObject() ? (valueType.isObject() ? "<?, ?>" : "<?>") : valueType.isObject() ? "<?>" : "");
addSimpleMapper(" KEY_COMPAREABLE_TYPE", type.isObject() ? "<"+type.getKeyType()+" extends Comparable<T>>" : ""); addSimpleMapper(" KEY_COMPAREABLE_TYPE", type.isObject() ? "<"+type.getKeyType()+" extends Comparable<T>>" : "");
addSimpleMapper(" KEY_SUPER_GENERIC_TYPE", type.isObject() ? "<? super "+type.getKeyType()+">" : ""); addSimpleMapper(" KEY_SUPER_GENERIC_TYPE", type.isObject() ? "<? super "+type.getKeyType()+">" : "");
addSimpleMapper(" VALUE_SUPER_GENERIC_TYPE", valueType.isObject() ? "<? super "+valueType.getValueType()+">" : ""); addSimpleMapper(" VALUE_SUPER_GENERIC_TYPE", valueType.isObject() ? "<? super "+valueType.getValueType()+">" : "");
addSimpleMapper(" KEY_VALUE_SUPER_GENERIC_TYPE", type.isObject() ? (valueType.isObject() ? "<? super "+type.getKeyType()+", ? super "+valueType.getValueType()+">" : "<? super "+type.getKeyType()+">") : (valueType.isObject() ? "<? super "+valueType.getValueType()+">" : "")); addSimpleMapper(" KEY_VALUE_SUPER_GENERIC_TYPE", type.isObject() ? (valueType.isObject() ? "<? super "+type.getKeyType()+", ? super "+valueType.getValueType()+">" : "<? super "+type.getKeyType()+">") : (valueType.isObject() ? "<? super "+valueType.getValueType()+">" : ""));
addSimpleMapper(" KEY_ENUM_VALUE_GENERIC_TYPE", type.isObject() ? (valueType.isObject() ? "<"+type.getKeyType()+" extends Enum<"+type.getKeyType()+">, "+valueType.getValueType()+">" : "<"+type.getKeyType()+" extends Enum<"+type.getKeyType()+">>") : (valueType.isObject() ? "<"+valueType.getValueType()+">" : "")); addSimpleMapper(" KEY_ENUM_VALUE_GENERIC_TYPE", type.isObject() ? (valueType.isObject() ? "<"+type.getKeyType()+" extends Enum<"+type.getKeyType()+">, "+valueType.getValueType()+">" : "<"+type.getKeyType()+" extends Enum<"+type.getKeyType()+">>") : (valueType.isObject() ? "<"+valueType.getValueType()+">" : ""));
addSimpleMapper(" KEY_VALUE_ENUM_GENERIC_TYPE", type.isObject() ? (valueType.isObject() ? "<"+type.getKeyType()+", "+valueType.getValueType()+" extends Enum<"+valueType.getValueType()+">>" : "<"+type.getKeyType()+">") : (valueType.isObject() ? "<"+valueType.getValueType()+" extends Enum<"+valueType.getValueType()+">>" : "")); addSimpleMapper(" KEY_VALUE_ENUM_GENERIC_TYPE", type.isObject() ? (valueType.isObject() ? "<"+type.getKeyType()+", "+valueType.getValueType()+" extends Enum<"+valueType.getValueType()+">>" : "<"+type.getKeyType()+">") : (valueType.isObject() ? "<"+valueType.getValueType()+" extends Enum<"+valueType.getValueType()+">>" : ""));
addInjectMapper(" KEY_SPECIAL_GENERIC_TYPE", type.isObject() ? "<%s>" : "").removeBraces().setBraceType("<>");
addInjectMapper(" VALUE_SPECIAL_GENERIC_TYPE", valueType.isObject() ? "<%s>" : "").removeBraces().setBraceType("<>");
addInjectMapper(" KSK_GENERIC_TYPE", type.isObject() ? "<%s, "+type.getKeyType()+">" : "<%s>").removeBraces().setBraceType("<>");
addInjectMapper(" KKS_GENERIC_TYPE", type.isObject() ? "<"+type.getKeyType()+", %s>" : "<%s>").removeBraces().setBraceType("<>");
addArgumentMapper(" KSS_GENERIC_TYPE", type.isObject() ? "<%1$s, %2$s>" : "<%2$s>").removeBraces().setBraceType("<>");
addInjectMapper(" VSV_GENERIC_TYPE", valueType.isObject() ? "<%s, "+valueType.getValueType()+">" : "<%s>").removeBraces().setBraceType("<>");
addInjectMapper(" VVS_GENERIC_TYPE", valueType.isObject() ? "<"+valueType.getValueType()+", %s>" : "<%s>").removeBraces().setBraceType("<>");
addArgumentMapper(" VSS_GENERIC_TYPE", valueType.isObject() ? "<%1$s, %2$s>" : "<%2$s>").removeBraces().setBraceType("<>");
addSimpleMapper(" GENERIC_KEY_BRACES", type.isObject() ? " <"+type.getKeyType()+">" : ""); addSimpleMapper(" GENERIC_KEY_BRACES", type.isObject() ? " <"+type.getKeyType()+">" : "");
addSimpleMapper(" GENERIC_VALUE_BRACES", type.isObject() ? " <"+valueType.getValueType()+">" : ""); addSimpleMapper(" GENERIC_VALUE_BRACES", valueType.isObject() ? " <"+valueType.getValueType()+">" : "");
addInjectMapper(" GENERIC_SPECIAL_KEY_BRACES", type.isObject() ? " <%s>" : "").removeBraces().setBraceType("<>");
addInjectMapper(" GENERIC_SPECIAL_VALUE_BRACES", valueType.isObject() ? " <%s>" : "").removeBraces().setBraceType("<>");
addSimpleMapper(" GENERIC_KEY_ENUM_VALUE_BRACES", type.isObject() ? (valueType.isObject() ? " <"+type.getKeyType()+" extends Enum<"+type.getKeyType()+">, "+valueType.getValueType()+">" : " <"+type.getKeyType()+" extends Enum<"+type.getKeyType()+">>") : (valueType.isObject() ? " <"+valueType.getValueType()+">" : ""));
addInjectMapper(" GENERIC_KEY_SPECIAL_BRACES", type.isObject() ? " <"+type.getKeyType()+", %s>" : " <%s>").removeBraces().setBraceType("<>");
addInjectMapper(" GENERIC_VALUE_SPECIAL_BRACES", valueType.isObject() ? " <"+valueType.getKeyType()+", %s>" : " <%s>").removeBraces().setBraceType("<>");
addSimpleMapper(" GENERIC_KEY_VALUE_BRACES", type.isObject() ? (valueType.isObject() ? " <"+type.getKeyType()+", "+valueType.getValueType()+">" : " <"+type.getKeyType()+">") : (valueType.isObject() ? " <"+valueType.getValueType()+">" : "")); addSimpleMapper(" GENERIC_KEY_VALUE_BRACES", type.isObject() ? (valueType.isObject() ? " <"+type.getKeyType()+", "+valueType.getValueType()+">" : " <"+type.getKeyType()+">") : (valueType.isObject() ? " <"+valueType.getValueType()+">" : ""));
addSimpleMapper(" COMPAREABLE_KEY_BRACES", type.isObject() ? " <"+type.getKeyType()+" extends Comparable<T>>" : ""); addSimpleMapper(" COMPAREABLE_KEY_BRACES", type.isObject() ? " <"+type.getKeyType()+" extends Comparable<T>>" : "");
addSimpleMapper("KV_BRACES", type.isObject() || valueType.isObject() ? "<>" : ""); addSimpleMapper("KV_BRACES", type.isObject() || valueType.isObject() ? "<>" : "");
@@ -78,6 +101,8 @@ public class GlobalVariables
addAnnontion("@PrimitiveOverride", "@Override"); addAnnontion("@PrimitiveOverride", "@Override");
addSimpleMapper("@PrimitiveDoc", ""); addSimpleMapper("@PrimitiveDoc", "");
addAnnontion("@Primitive", "@Deprecated"); addAnnontion("@Primitive", "@Deprecated");
addValueAnnontion("@ValuePrimitiveOverride", "@Override");
addValueAnnontion("@ValuePrimitive", "@Deprecated");
return this; return this;
} }
@@ -103,12 +128,13 @@ public class GlobalVariables
addInjectMapper("OBJ_TO_"+fix, type.isObject() ? "%s" : "%s."+type.getKeyType(value)+"Value()").removeBraces(); addInjectMapper("OBJ_TO_"+fix, type.isObject() ? "%s" : "%s."+type.getKeyType(value)+"Value()").removeBraces();
addInjectMapper("CLASS_TO_"+fix, type.isObject() ? "("+type.getKeyType(value)+")%s" : "(("+type.getClassType(value)+")%s)."+type.getKeyType(value)+"Value()").removeBraces(); addInjectMapper("CLASS_TO_"+fix, type.isObject() ? "("+type.getKeyType(value)+")%s" : "(("+type.getClassType(value)+")%s)."+type.getKeyType(value)+"Value()").removeBraces();
addInjectMapper(fix+"_TO_HASH", type.isObject() ? "%s.hashCode()" : type.getClassType(value)+".hashCode(%s)").removeBraces(); addInjectMapper(fix+"_TO_HASH", type.isObject() ? "Objects.hashCode(%s)" : type.getClassType(value)+".hashCode(%s)").removeBraces();
addInjectMapper(fix+"_TO_STRING", type.isObject() ? "%s.toString()" : type.getClassType(value)+".toString(%s)").removeBraces(); addInjectMapper(fix+"_TO_STRING", type.isObject() ? "Objects.toString(%s)" : type.getClassType(value)+".toString(%s)").removeBraces();
addSimpleMapper("CAST_"+fix+"_ARRAY ", type.isObject() ? "("+fix+"_TYPE[])" : ""); addSimpleMapper("CAST_"+fix+"_ARRAY ", type.isObject() ? "("+fix+"_TYPE[])" : "");
addSimpleMapper("EMPTY_"+fix+"_ARRAY", type.isObject() ? "("+fix+"_TYPE[])ARRAYS.EMPTY_ARRAY" : "ARRAYS.EMPTY_ARRAY"); addSimpleMapper("EMPTY_"+fix+"_ARRAY", type.isObject() ? "("+fix+"_TYPE[])ARRAYS.EMPTY_ARRAY" : "ARRAYS.EMPTY_ARRAY");
addInjectMapper("NEW_"+fix+"_ARRAY", type.isObject() ? "("+fix+"_TYPE[])new Object[%s]" : "new "+fix+"_TYPE[%s]").removeBraces(); addInjectMapper("NEW_"+fix+"_ARRAY", type.isObject() ? "("+fix+"_TYPE[])new Object[%s]" : "new "+fix+"_TYPE[%s]").removeBraces();
addInjectMapper("NEW_SPECIAL_"+fix+"_ARRAY", type.isObject() ? "(E[])new Object[%s]" : "new "+fix+"_TYPE[%s]").removeBraces();
addInjectMapper("NEW_CLASS"+(value ? "_VALUE" : "")+"_ARRAY", type.isObject() ? "(CLASS_TYPE[])new Object[%s]" : "new CLASS_TYPE[%s]").removeBraces(); addInjectMapper("NEW_CLASS"+(value ? "_VALUE" : "")+"_ARRAY", type.isObject() ? "(CLASS_TYPE[])new Object[%s]" : "new CLASS_TYPE[%s]").removeBraces();
} }
@@ -122,35 +148,45 @@ public class GlobalVariables
{ {
addSimpleMapper("JAVA_PREDICATE", type.isPrimitiveBlocking() ? "" : type.getCustomJDKType().getFileType()+"Predicate"); addSimpleMapper("JAVA_PREDICATE", type.isPrimitiveBlocking() ? "" : type.getCustomJDKType().getFileType()+"Predicate");
addSimpleMapper("JAVA_CONSUMER", type.isPrimitiveBlocking() ? "" : "java.util.function."+type.getCustomJDKType().getFileType()+"Consumer"); addSimpleMapper("JAVA_CONSUMER", type.isPrimitiveBlocking() ? "" : "java.util.function."+type.getCustomJDKType().getFileType()+"Consumer");
addSimpleMapper("JAVA_SUPPLIER", type.isPrimitiveBlocking() ? "" : "java.util.function."+type.getCustomJDKType().getFileType()+"Supplier");
addSimpleMapper("JAVA_FUNCTION", type.getFunctionClass(valueType)); addSimpleMapper("JAVA_FUNCTION", type.getFunctionClass(valueType));
addSimpleMapper("JAVA_BINARY_OPERATOR", type == ClassType.BOOLEAN ? "" : (type.isObject() ? "java.util.function.BinaryOperator" : "java.util.function."+type.getCustomJDKType().getFileType()+"BinaryOperator")); addSimpleMapper("JAVA_BINARY_OPERATOR", type == ClassType.BOOLEAN ? "" : (type.isObject() ? "java.util.function.BinaryOperator" : "java.util.function."+type.getCustomJDKType().getFileType()+"BinaryOperator"));
addSimpleMapper("JAVA_UNARY_OPERATOR", type.isObject() ? "BinaryOperator" : type == ClassType.BOOLEAN ? "" : type.getCustomJDKType().getFileType()+"UnaryOperator"); addSimpleMapper("JAVA_UNARY_OPERATOR", type.isObject() ? "BinaryOperator" : type == ClassType.BOOLEAN ? "" : type.getCustomJDKType().getFileType()+"UnaryOperator");
addSimpleMapper("JAVA_SPLIT_ITERATOR", type.isPrimitiveBlocking() ? "Spliterator" : "Of"+type.getCustomJDKType().getFileType()); addSimpleMapper("JAVA_SPLIT_ITERATOR", type.isPrimitiveBlocking() ? "Spliterator" : "Of"+type.getCustomJDKType().getFileType());
addSimpleMapper("JAVA_STREAM", type.isPrimitiveBlocking() ? "" : type.getCustomJDKType().getFileType()+"Stream"); addSimpleMapper("JAVA_STREAM", type.isPrimitiveBlocking() ? "" : type.getCustomJDKType().getFileType()+"Stream");
addSimpleMapper("JAVA_BUFFER", type.getFileType()+"Buffer");
//Final Classes //Final Classes
addClassMapper("ARRAY_LIST", "ArrayList"); addClassMapper("ARRAY_LIST", "ArrayList");
addClassMapper("LINKED_LIST", "LinkedList");
addAbstractMapper("IMMUTABLE_LIST", "Immutable%sList");
addClassMapper("ARRAY_FIFO_QUEUE", "ArrayFIFOQueue"); addClassMapper("ARRAY_FIFO_QUEUE", "ArrayFIFOQueue");
addClassMapper("ARRAY_PRIORITY_QUEUE", "ArrayPriorityQueue"); addClassMapper("ARRAY_PRIORITY_QUEUE", "ArrayPriorityQueue");
addClassMapper("HEAP_PRIORITY_QUEUE", "HeapPriorityQueue"); addClassMapper("HEAP_PRIORITY_QUEUE", "HeapPriorityQueue");
addClassMapper("LINKED_CUSTOM_HASH_SET", "LinkedOpenCustomHashSet"); addClassMapper("LINKED_CUSTOM_HASH_SET", "LinkedOpenCustomHashSet");
addClassMapper("LINKED_HASH_SET", "LinkedOpenHashSet"); addClassMapper("LINKED_HASH_SET", "LinkedOpenHashSet");
addAbstractMapper("IMMUTABLE_HASH_SET", "Immutable%sOpenHashSet");
addClassMapper("CUSTOM_HASH_SET", "OpenCustomHashSet"); addClassMapper("CUSTOM_HASH_SET", "OpenCustomHashSet");
addClassMapper("HASH_SET", "OpenHashSet"); addClassMapper("HASH_SET", "OpenHashSet");
addAbstractBiMapper("IMMUTABLE_HASH_MAP", "Immutable%sOpenHashMap", "2");
addBiClassMapper("LINKED_CUSTOM_HASH_MAP", "LinkedOpenCustomHashMap", "2"); addBiClassMapper("LINKED_CUSTOM_HASH_MAP", "LinkedOpenCustomHashMap", "2");
addBiClassMapper("LINKED_HASH_MAP", "LinkedOpenHashMap", "2"); addBiClassMapper("LINKED_HASH_MAP", "LinkedOpenHashMap", "2");
addBiClassMapper("CUSTOM_HASH_MAP", "OpenCustomHashMap", "2"); addBiClassMapper("CUSTOM_HASH_MAP", "OpenCustomHashMap", "2");
addBiClassMapper("AVL_TREE_MAP", "AVLTreeMap", "2"); addBiClassMapper("AVL_TREE_MAP", "AVLTreeMap", "2");
addBiClassMapper("RB_TREE_MAP", "RBTreeMap", "2"); addBiClassMapper("RB_TREE_MAP", "RBTreeMap", "2");
addFunctionValueMappers("LINKED_ENUM_MAP", valueType.isObject() ? "LinkedEnum2ObjectMap" : "LinkedEnum2%sMap");
addFunctionValueMappers("ENUM_MAP", valueType.isObject() ? "Enum2ObjectMap" : "Enum2%sMap"); addFunctionValueMappers("ENUM_MAP", valueType.isObject() ? "Enum2ObjectMap" : "Enum2%sMap");
addBiClassMapper("HASH_MAP", "OpenHashMap", "2"); addBiClassMapper("HASH_MAP", "OpenHashMap", "2");
addBiClassMapper("ARRAY_MAP", "ArrayMap", "2"); addBiClassMapper("ARRAY_MAP", "ArrayMap", "2");
addBiClassMapper("IMMUTABLE_PAIR", "ImmutablePair", "");
addBiClassMapper("MUTABLE_PAIR", "MutablePair", "");
addClassMapper("RB_TREE_SET", "RBTreeSet"); addClassMapper("RB_TREE_SET", "RBTreeSet");
addClassMapper("AVL_TREE_SET", "AVLTreeSet"); addClassMapper("AVL_TREE_SET", "AVLTreeSet");
addClassMapper("ARRAY_SET", "ArraySet"); addClassMapper("ARRAY_SET", "ArraySet");
//Abstract Classes //Abstract Classes
addAbstractMapper("ABSTRACT_COLLECTION", "Abstract%sCollection"); addAbstractMapper("ABSTRACT_COLLECTION", "Abstract%sCollection");
addAbstractMapper("ABSTRACT_PRIORITY_QUEUE", "Abstract%sPriorityQueue");
addAbstractMapper("ABSTRACT_SET", "Abstract%sSet"); addAbstractMapper("ABSTRACT_SET", "Abstract%sSet");
addAbstractMapper("ABSTRACT_LIST", "Abstract%sList"); addAbstractMapper("ABSTRACT_LIST", "Abstract%sList");
addAbstractBiMapper("ABSTRACT_MAP", "Abstract%sMap", "2"); addAbstractBiMapper("ABSTRACT_MAP", "Abstract%sMap", "2");
@@ -161,18 +197,23 @@ public class GlobalVariables
addClassMapper("SETS", "Sets"); addClassMapper("SETS", "Sets");
addClassMapper("COLLECTIONS", "Collections"); addClassMapper("COLLECTIONS", "Collections");
addClassMapper("ARRAYS", "Arrays"); addClassMapper("ARRAYS", "Arrays");
addClassMapper("PRIORITY_QUEUES", "PriorityQueues");
addClassMapper("SPLIT_ITERATORS", "Splititerators"); addClassMapper("SPLIT_ITERATORS", "Splititerators");
addClassMapper("ITERATORS", "Iterators"); addClassMapper("ITERATORS", "Iterators");
addClassMapper("ITERABLES", "Iterables");
addBiClassMapper("MAPS", "Maps", "2"); addBiClassMapper("MAPS", "Maps", "2");
//Interfaces //Interfaces
addClassMapper("LIST_ITERATOR", "ListIterator"); addClassMapper("LIST_ITERATOR", "ListIterator");
addClassMapper("BI_ITERATOR", "BidirectionalIterator"); addClassMapper("BI_ITERATOR", "BidirectionalIterator");
addBiClassMapper("BI_CONSUMER", "Consumer", ""); addBiClassMapper("BI_CONSUMER", "Consumer", "");
addClassMapper("BI_TO_OBJECT_CONSUMER", "ObjectConsumer");
addAbstractMapper("BI_FROM_OBJECT_CONSUMER", "Object%sConsumer");
addClassMapper("SPLIT_ITERATOR", "Splititerator"); addClassMapper("SPLIT_ITERATOR", "Splititerator");
addClassMapper("ITERATOR", "Iterator"); addClassMapper("ITERATOR", "Iterator");
addClassMapper("ITERABLE", "Iterable"); addClassMapper("ITERABLE", "Iterable");
addClassMapper("COLLECTION", "Collection"); addClassMapper("COLLECTION", "Collection");
addClassMapper("TO_OBJECT_FUNCTION", "2ObjectFunction");
addBiClassMapper("FUNCTION", "Function", "2"); addBiClassMapper("FUNCTION", "Function", "2");
addClassMapper("LIST_ITER", "ListIter"); addClassMapper("LIST_ITER", "ListIter");
addClassMapper("LIST", "List"); addClassMapper("LIST", "List");
@@ -180,26 +221,33 @@ public class GlobalVariables
addBiClassMapper("SORTED_MAP", "SortedMap", "2"); addBiClassMapper("SORTED_MAP", "SortedMap", "2");
addBiClassMapper("MAP", "Map", "2"); addBiClassMapper("MAP", "Map", "2");
addClassMapper("NAVIGABLE_SET", "NavigableSet"); addClassMapper("NAVIGABLE_SET", "NavigableSet");
addBiClassMapper("PAIR", "Pair", "");
addClassMapper("PRIORITY_QUEUE", "PriorityQueue"); addClassMapper("PRIORITY_QUEUE", "PriorityQueue");
addClassMapper("PRIORITY_DEQUEUE", "PriorityDequeue"); addClassMapper("PRIORITY_DEQUEUE", "PriorityDequeue");
addClassMapper("PREDICATE", "2BooleanFunction");
addClassMapper("SORTED_SET", "SortedSet"); addClassMapper("SORTED_SET", "SortedSet");
addClassMapper("SET", "Set"); addClassMapper("SET", "Set");
addClassMapper("STRATEGY", "Strategy"); addClassMapper("STRATEGY", "Strategy");
addClassMapper("STACK", "Stack"); addClassMapper("STACK", "Stack");
addClassMapper("SUPPLIER", "Supplier");
addAbstractMapper("SINGLE_UNARY_OPERATOR", "%1$s%1$sUnaryOperator");
addBiClassMapper("UNARY_OPERATOR", "UnaryOperator", ""); addBiClassMapper("UNARY_OPERATOR", "UnaryOperator", "");
if(type.isObject()) if(type.isObject())
{ {
if(!valueType.isObject()) if(!valueType.isObject()) addSimpleMapper("VALUE_CONSUMER", valueType.getFileType()+"Consumer");
{ else addSimpleMapper("VALUE_CONSUMER", "Consumer");
addSimpleMapper("VALUE_CONSUMER", valueType.getFileType()+"Consumer");
}
addSimpleMapper("CONSUMER", "Consumer"); addSimpleMapper("CONSUMER", "Consumer");
addSimpleMapper("COMPARATOR", "Comparator"); addSimpleMapper("COMPARATOR", "Comparator");
addSimpleMapper("IARRAY", "IObjectArray"); addSimpleMapper("IARRAY", "IObjectArray");
} }
else else
{ {
addClassMapper("CONSUMER", "Consumer"); if(valueType.isObject())
{
addSimpleMapper("VALUE_CONSUMER", "Consumer");
addSimpleMapper("CONSUMER", type.getFileType()+"Consumer");
}
else addClassMapper("CONSUMER", "Consumer");
addClassMapper("COMPARATOR", "Comparator"); addClassMapper("COMPARATOR", "Comparator");
addFunctionMappers("IARRAY", "I%sArray"); addFunctionMappers("IARRAY", "I%sArray");
} }
@@ -208,14 +256,14 @@ public class GlobalVariables
public GlobalVariables createFunctions() public GlobalVariables createFunctions()
{ {
addSimpleMapper("APPLY_KEY_VALUE", type.isObject() ? "apply" : "applyAs"+type.getNonFileType());
addSimpleMapper("APPLY_VALUE", valueType.isObject() ? "apply" : "applyAs"+valueType.getNonFileType()); addSimpleMapper("APPLY_VALUE", valueType.isObject() ? "apply" : "applyAs"+valueType.getNonFileType());
addSimpleMapper("APPLY_CAST", "applyAs"+type.getCustomJDKType().getNonFileType()); addSimpleMapper("APPLY_CAST", "applyAs"+type.getCustomJDKType().getNonFileType());
addSimpleMapper("APPLY", type.isObject() ? "apply" : "applyAs"+type.getNonFileType()); addSimpleMapper("APPLY", type.isObject() ? "apply" : "applyAs"+type.getNonFileType());
addFunctionValueMapper("BULK_MERGE", "mergeAll");
addFunctionValueMappers("COMPUTE_IF_ABSENT", "compute%sIfAbsent"); addFunctionValueMappers("COMPUTE_IF_ABSENT", "compute%sIfAbsent");
addFunctionValueMappers("COMPUTE_IF_PRESENT", "compute%sIfPresent"); addFunctionValueMappers("COMPUTE_IF_PRESENT", "compute%sIfPresent");
addFunctionValueMapper("COMPUTE", "compute"); addFunctionValueMapper("COMPUTE", "compute");
addFunctionMapper("ENQUEUE_FIRST", "enqueueFirst");
addFunctionMapper("ENQUEUE", "enqueue");
addFunctionMapper("DEQUEUE_LAST", "dequeueLast"); addFunctionMapper("DEQUEUE_LAST", "dequeueLast");
addFunctionMapper("DEQUEUE", "dequeue"); addFunctionMapper("DEQUEUE", "dequeue");
addFunctionMappers("POLL_FIRST_ENTRY_KEY", "pollFirst%sKey"); addFunctionMappers("POLL_FIRST_ENTRY_KEY", "pollFirst%sKey");
@@ -229,24 +277,31 @@ public class GlobalVariables
addFunctionValueMappers("LAST_ENTRY_VALUE", "last%sValue"); addFunctionValueMappers("LAST_ENTRY_VALUE", "last%sValue");
addFunctionMappers("ENTRY_KEY", "get%sKey"); addFunctionMappers("ENTRY_KEY", "get%sKey");
addFunctionValueMappers("ENTRY_VALUE", "get%sValue"); addFunctionValueMappers("ENTRY_VALUE", "get%sValue");
addFunctionMappers("KEY_ENTRY", "set%sKey");
addFunctionValueMappers("VALUE_ENTRY", "set%sValue");
addFunctionMapper("GET_KEY", "get"); addFunctionMapper("GET_KEY", "get");
addFunctionValueMapper("GET_VALUE", valueType.isObject() ? "getObject" : "get"); if(type.isObject()) addFunctionValueMapper("GET_VALUE", valueType.isObject() ? "getObject" : "get");
else addSimpleMapper("GET_VALUE", "get");
addSimpleMapper("GET_JAVA", type.isObject() ? "get" : "getAs"+type.getCustomJDKType().getNonFileType());
addFunctionMapper("LAST_KEY", "last"); addFunctionMapper("LAST_KEY", "last");
addFunctionValueMapper("MERGE", "merge"); addFunctionValueMapper("MERGE", "merge");
addFunctionMapper("NEXT", "next"); addFunctionMapper("NEXT", "next");
addFunctionMapper("PREVIOUS", "previous"); addFunctionMapper("PREVIOUS", "previous");
addFunctionMapper("PEEK", "peek"); addFunctionMapper("REMOVE_SWAP", "swapRemove");
addFunctionMapper("POP", "pop"); if(type.isObject()) addFunctionMapper("REMOVE_VALUE", "rem");
addFunctionMapper("PUSH", "push"); else addSimpleMapper("REMOVE_VALUE", "remove");
addFunctionMapper("REMOVE_KEY", "rem"); addFunctionMapper("REMOVE_KEY", "rem");
addFunctionMapper("REMOVE_LAST", "removeLast"); addFunctionMapper("REMOVE_LAST", "removeLast");
addFunctionMapper("REMOVE", "remove"); addFunctionMapper("REMOVE", "remove");
addFunctionValueMappers("REPLACE_VALUES", valueType.isObject() ? "replaceObjects" : "replace%ss"); addFunctionValueMappers("REPLACE_VALUES", valueType.isObject() ? "replaceObjects" : "replace%ss");
addFunctionMappers("REPLACE", type.isObject() ? "replaceObjects" : "replace%ss"); addFunctionMappers("REPLACE", type.isObject() ? "replaceObjects" : "replace%ss");
addFunctionMappers("SORT", "sort%ss"); addFunctionMappers("SORT", "sort%ss");
addFunctionValueMappers("SUPPLY_IF_ABSENT", "supply%sIfAbsent");
addSimpleMapper("VALUE_TEST_VALUE", valueType.isObject() ? "getBoolean" : "get");
addSimpleMapper("TEST_VALUE", type.isObject() ? "getBoolean" : "get");
addSimpleMapper("NEW_STREAM", type.isPrimitiveBlocking() ? "" : type.getCustomJDKType().getKeyType()+"Stream"); addSimpleMapper("NEW_STREAM", type.isPrimitiveBlocking() ? "" : type.getCustomJDKType().getKeyType()+"Stream");
addSimpleMapper("TO_ARRAY", "to"+type.getNonFileType()+"Array"); addSimpleMapper("TO_ARRAY", "to"+type.getNonFileType()+"Array");
addFunctionMapper("TOP", "top"); addSimpleMapper("[SPACE]", " ");
return this; return this;
} }
@@ -334,6 +389,12 @@ public class GlobalVariables
else operators.add(new SimpleMapper(type.name()+"["+pattern+"]", pattern, value)); else operators.add(new SimpleMapper(type.name()+"["+pattern+"]", pattern, value));
} }
private void addValueAnnontion(String pattern, String value)
{
if(valueType == ClassType.OBJECT) operators.add(new LineMapper(valueType.name()+"["+pattern+"]", pattern));
else operators.add(new SimpleMapper(valueType.name()+"["+pattern+"]", pattern, value));
}
private void addComment(String pattern, String value) private void addComment(String pattern, String value)
{ {
if(type == ClassType.OBJECT) operators.add(new InjectMapper(type.name()+"["+pattern+"]", pattern, value).removeBraces()); if(type == ClassType.OBJECT) operators.add(new InjectMapper(type.name()+"["+pattern+"]", pattern, value).removeBraces());
@@ -67,19 +67,29 @@ public class PrimitiveCollectionsBuilder extends TemplateProcessor
} }
} }
enumRequired.add("EnumMap"); enumRequired.add("EnumMap");
enumRequired.add("LinkedEnumMap");
biRequired.put("BiConsumer", ""); biRequired.put("BiConsumer", "");
biRequired.put("UnaryOperator", ""); biRequired.put("UnaryOperator", "");
addBiClass("Function", "Maps", "Map", "SortedMap", "NavigableMap", "AbstractMap", "OpenHashMap", "LinkedOpenHashMap", "OpenCustomHashMap", "LinkedOpenCustomHashMap", "ArrayMap", "RBTreeMap", "AVLTreeMap"); biRequired.put("Pair", "");
biRequired.put("MutablePair", "");
biRequired.put("ImmutablePair", "");
addBiClass("Function", "Maps", "Map", "SortedMap", "NavigableMap", "AbstractMap", "ImmutableOpenHashMap", "OpenHashMap", "LinkedOpenHashMap", "OpenCustomHashMap", "LinkedOpenCustomHashMap", "ArrayMap", "RBTreeMap", "AVLTreeMap");
nameRemapper.put("BiConsumer", "%sConsumer"); nameRemapper.put("BiConsumer", "%sConsumer");
nameRemapper.put("IArray", "I%sArray"); nameRemapper.put("IArray", "I%sArray");
nameRemapper.put("AbstractMap", "Abstract%sMap"); nameRemapper.put("AbstractMap", "Abstract%sMap");
nameRemapper.put("AbstractCollection", "Abstract%sCollection"); nameRemapper.put("AbstractCollection", "Abstract%sCollection");
nameRemapper.put("AbstractPriorityQueue", "Abstract%sPriorityQueue");
nameRemapper.put("AbstractSet", "Abstract%sSet"); nameRemapper.put("AbstractSet", "Abstract%sSet");
nameRemapper.put("AbstractList", "Abstract%sList"); nameRemapper.put("AbstractList", "Abstract%sList");
nameRemapper.put("EnumMap", "Enum2%sMap"); nameRemapper.put("EnumMap", "Enum2%sMap");
nameRemapper.put("LinkedEnumMap", "LinkedEnum2%sMap");
nameRemapper.put("ImmutableList", "Immutable%sList");
nameRemapper.put("ImmutableOpenHashSet", "Immutable%sOpenHashSet");
nameRemapper.put("ImmutableOpenHashMap", "Immutable%sOpenHashMap");
addBlockage(ClassType.OBJECT, "Consumer", "Comparator", "Stack"); addBlockage(ClassType.OBJECT, "Consumer", "Comparator", "Stack");
addBlockage(ClassType.BOOLEAN, "ArraySet", "AVLTreeSet", "RBTreeSet", "SortedSet", "NavigableSet", "OpenHashSet", "OpenCustomHashSet", "LinkedOpenHashSet", "LinkedOpenCustomHashSet"); addBlockage(ClassType.BOOLEAN, "ArraySet", "AVLTreeSet", "RBTreeSet", "SortedSet", "NavigableSet", "OpenHashSet", "OpenCustomHashSet", "LinkedOpenHashSet", "LinkedOpenCustomHashSet");
addBlockage(ClassType.BOOLEAN, "SortedMap", "NavigableMap", "OpenHashMap", "LinkedOpenHashMap", "OpenCustomHashMap", "LinkedOpenCustomHashMap", "ArrayMap", "RBTreeMap", "AVLTreeMap"); addBlockage(ClassType.BOOLEAN, "ImmutableOpenHashMap", "ImmutableOpenHashSet", "SortedMap", "NavigableMap", "OpenHashMap", "LinkedOpenHashMap", "OpenCustomHashMap", "LinkedOpenCustomHashMap", "ArrayMap", "RBTreeMap", "AVLTreeMap");
} }
protected void create(ClassType mainType, ClassType subType) protected void create(ClassType mainType, ClassType subType)
@@ -147,9 +157,13 @@ public class PrimitiveCollectionsBuilder extends TemplateProcessor
{ {
if(args.length == 0) { if(args.length == 0) {
new PrimitiveCollectionsBuilder().process(false); new PrimitiveCollectionsBuilder().process(false);
} else if(args.length == 1) {
new PrimitiveCollectionsBuilder().process(Boolean.parseBoolean(args[0]));
} else if(args.length == 3) { } else if(args.length == 3) {
new PrimitiveCollectionsBuilder(Paths.get(args[0]), Paths.get(args[1]), Paths.get(args[2])).process(false); new PrimitiveCollectionsBuilder(Paths.get(args[0]), Paths.get(args[1]), Paths.get(args[2])).process(false);
} else { } else if(args.length == 4) {
new PrimitiveCollectionsBuilder(Paths.get(args[0]), Paths.get(args[1]), Paths.get(args[2])).process(Boolean.parseBoolean(args[3]));
} else {
System.out.println("Invalid argument count passed in"); System.out.println("Invalid argument count passed in");
System.exit(1); System.exit(1);
} }
@@ -3,9 +3,13 @@ package speiger.src.collections.PACKAGE.collections;
import java.util.Collection; import java.util.Collection;
import java.util.Objects; import java.util.Objects;
import java.util.AbstractCollection; import java.util.AbstractCollection;
#if TYPE_OBJECT
import java.util.function.Consumer;
#endif
import speiger.src.collections.PACKAGE.collections.COLLECTION; import speiger.src.collections.PACKAGE.collections.COLLECTION;
#if !TYPE_OBJECT #if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.functions.CONSUMER;
import speiger.src.collections.PACKAGE.utils.ITERATORS; import speiger.src.collections.PACKAGE.utils.ITERATORS;
#endif #endif
@@ -35,6 +39,9 @@ public abstract class ABSTRACT_COLLECTION KEY_GENERIC_TYPE extends AbstractColle
return modified; return modified;
} }
@Override
public COLLECTION KEY_GENERIC_TYPE copy() { throw new UnsupportedOperationException(); }
#if !TYPE_OBJECT #if !TYPE_OBJECT
/** {@inheritDoc} /** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function. * <p>This default implementation delegates to the corresponding type-specific function.
@@ -55,8 +62,6 @@ public abstract class ABSTRACT_COLLECTION KEY_GENERIC_TYPE extends AbstractColle
return false; return false;
} }
#endif
/** {@inheritDoc} /** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function. * <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead. * @deprecated Please use the corresponding type-specific function instead.
@@ -67,6 +72,7 @@ public abstract class ABSTRACT_COLLECTION KEY_GENERIC_TYPE extends AbstractColle
{ {
return c instanceof COLLECTION ? addAll((COLLECTION KEY_GENERIC_TYPE)c) : super.addAll(c); return c instanceof COLLECTION ? addAll((COLLECTION KEY_GENERIC_TYPE)c) : super.addAll(c);
} }
#endif
/** /**
* A Type-Specific implementation of containsAll. This implementation iterates over all elements and checks all elements are present in the other collection. * A Type-Specific implementation of containsAll. This implementation iterates over all elements and checks all elements are present in the other collection.
@@ -77,12 +83,19 @@ public abstract class ABSTRACT_COLLECTION KEY_GENERIC_TYPE extends AbstractColle
@Override @Override
public boolean containsAll(COLLECTION KEY_GENERIC_TYPE c) { public boolean containsAll(COLLECTION KEY_GENERIC_TYPE c) {
Objects.requireNonNull(c); Objects.requireNonNull(c);
if(c.isEmpty()) return true;
for(ITERATOR KEY_GENERIC_TYPE iter = c.iterator();iter.hasNext();) for(ITERATOR KEY_GENERIC_TYPE iter = c.iterator();iter.hasNext();)
if(!contains(iter.NEXT())) if(!contains(iter.NEXT()))
return false; return false;
return true; return true;
} }
@Override
public boolean containsAll(Collection<?> c) {
Objects.requireNonNull(c);
return c instanceof COLLECTION ? containsAll((COLLECTION KEY_GENERIC_TYPE)c) : super.containsAll(c);
}
/** /**
* This implementation iterates over the elements of the collection and checks if they are stored in this collection * This implementation iterates over the elements of the collection and checks if they are stored in this collection
* @param c the elements that should be checked for * @param c the elements that should be checked for
@@ -94,6 +107,7 @@ public abstract class ABSTRACT_COLLECTION KEY_GENERIC_TYPE extends AbstractColle
@Primitive @Primitive
public boolean containsAny(Collection<?> c) { public boolean containsAny(Collection<?> c) {
Objects.requireNonNull(c); Objects.requireNonNull(c);
if(c.isEmpty()) return false;
for(Object e : c) for(Object e : c)
if(contains(e)) if(contains(e))
return true; return true;
@@ -109,6 +123,7 @@ public abstract class ABSTRACT_COLLECTION KEY_GENERIC_TYPE extends AbstractColle
@Override @Override
public boolean containsAny(COLLECTION KEY_GENERIC_TYPE c) { public boolean containsAny(COLLECTION KEY_GENERIC_TYPE c) {
Objects.requireNonNull(c); Objects.requireNonNull(c);
if(c.isEmpty()) return false;
for(ITERATOR KEY_GENERIC_TYPE iter = c.iterator();iter.hasNext();) for(ITERATOR KEY_GENERIC_TYPE iter = c.iterator();iter.hasNext();)
if(contains(iter.NEXT())) if(contains(iter.NEXT()))
return true; return true;
@@ -151,6 +166,7 @@ public abstract class ABSTRACT_COLLECTION KEY_GENERIC_TYPE extends AbstractColle
@Override @Override
public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c) { public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c) {
Objects.requireNonNull(c); Objects.requireNonNull(c);
if(c.isEmpty()) return false;
boolean modified = false; boolean modified = false;
for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) { for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) {
if(c.contains(iter.NEXT())) { if(c.contains(iter.NEXT())) {
@@ -161,6 +177,23 @@ public abstract class ABSTRACT_COLLECTION KEY_GENERIC_TYPE extends AbstractColle
return modified; return modified;
} }
@Override
public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c, CONSUMER KEY_GENERIC_TYPE r) {
Objects.requireNonNull(c);
if(c.isEmpty()) return false;
Objects.requireNonNull(r);
boolean modified = false;
for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) {
KEY_TYPE e = iter.NEXT();
if(c.contains(e)) {
r.accept(e);
iter.remove();
modified = true;
}
}
return modified;
}
/** /**
* A Type-Specific implementation of retainAll. This Implementation iterates over all elements and removes them as they were not found in the other collection. * A Type-Specific implementation of retainAll. This Implementation iterates over all elements and removes them as they were not found in the other collection.
* @param c the elements that should be kept * @param c the elements that should be kept
@@ -185,10 +218,31 @@ public abstract class ABSTRACT_COLLECTION KEY_GENERIC_TYPE extends AbstractColle
return modified; return modified;
} }
@Override
public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c, CONSUMER KEY_GENERIC_TYPE r) {
Objects.requireNonNull(c);
Objects.requireNonNull(r);
if(c.isEmpty()) {
boolean modified = !isEmpty();
forEach(r);
clear();
return modified;
}
boolean modified = false;
for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) {
KEY_TYPE e = iter.NEXT();
if(!c.contains(e)) {
iter.remove();
modified = true;
}
}
return modified;
}
#if !TYPE_OBJECT #if !TYPE_OBJECT
/** /**
* A Type-Specific implementation of toArray that links to {@link #TO_ARRAY(KEY_TYPE[])} with a newly created array. * A Type-Specific implementation of toArray that links to {@link #TO_ARRAY(KEY_TYPE[])} with a newly created array.
* @return an array containing all of the elements in this collection * @return an array containing all of the elements in this collection
*/ */
@Override @Override
public KEY_TYPE[] TO_ARRAY() { public KEY_TYPE[] TO_ARRAY() {
@@ -198,7 +252,7 @@ public abstract class ABSTRACT_COLLECTION KEY_GENERIC_TYPE extends AbstractColle
/** /**
* A Type-Specific implementation of toArray. This implementation iterates over all elements and unwraps them into primitive type. * A Type-Specific implementation of toArray. This implementation iterates over all elements and unwraps them into primitive type.
* @param a array that the elements should be injected to. If null or to small a new array with the right size is created * @param a array that the elements should be injected to. If null or to small a new array with the right size is created
* @return an array containing all of the elements in this collection * @return an array containing all of the elements in this collection
*/ */
@Override @Override
public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] a) { public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] a) {
@@ -8,12 +8,16 @@ import java.util.function.Predicate;
import java.util.stream.JAVA_STREAM; import java.util.stream.JAVA_STREAM;
import java.util.stream.StreamSupport; import java.util.stream.StreamSupport;
#endif #endif
#if TYPE_OBJECT
import java.util.function.Consumer;
import speiger.src.collections.ints.functions.function.Int2ObjectFunction;
#else
import speiger.src.collections.PACKAGE.functions.CONSUMER;
#endif
import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS; import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS;
import speiger.src.collections.PACKAGE.utils.COLLECTIONS;
#if TYPE_BYTE || TYPE_SHORT || TYPE_CHAR || TYPE_FLOAT
import speiger.src.collections.utils.SanityChecks; import speiger.src.collections.utils.SanityChecks;
#endif
/** /**
* A Type-Specific {@link Collection} that reduces (un)boxing * A Type-Specific {@link Collection} that reduces (un)boxing
* @Type(T) * @Type(T)
@@ -36,6 +40,38 @@ public interface COLLECTION KEY_GENERIC_TYPE extends Collection<CLASS_TYPE>, ITE
*/ */
public boolean addAll(COLLECTION KEY_GENERIC_TYPE c); public boolean addAll(COLLECTION KEY_GENERIC_TYPE c);
/**
* A Type-Specific Array based addAll method to reduce the amount of Wrapping
* @param e the elements that should be added
* @return if the collection was modified
*/
public default boolean addAll(KEY_TYPE... e) { return addAll(e, 0, e.length); }
/**
* A Type-Specific Array based addAll method to reduce the amount of Wrapping
* @param e the elements that should be added
* @param length how many elements of the array should be added
* @return if the collection was modified
*/
public default boolean addAll(KEY_TYPE[] e, int length) { return addAll(e, 0, length); }
/**
* A Type-Specific Array based addAll method to reduce the amount of Wrapping
* @param e the elements that should be added
* @param offset where to start within the array
* @param length how many elements of the array should be added
* @return if the collection was modified
*/
public default boolean addAll(KEY_TYPE[] e, int offset, int length) {
if(length <= 0) return false;
SanityChecks.checkArrayCapacity(e.length, offset, length);
boolean added = false;
for(int i = 0;i<length;i++) {
if(add(e[offset+i])) added = true;
}
return added;
}
#if !TYPE_OBJECT #if !TYPE_OBJECT
/** /**
* A Type-Specific contains function to reduce (un)boxing * A Type-Specific contains function to reduce (un)boxing
@@ -68,7 +104,7 @@ public interface COLLECTION KEY_GENERIC_TYPE extends Collection<CLASS_TYPE>, ITE
@Primitive @Primitive
public boolean containsAny(Collection<?> c); public boolean containsAny(Collection<?> c);
#if !TYPE_OBJECT #if !TYPE_OBJECT
/** /**
* A Type-Specific remove function that reduces (un)boxing. * A Type-Specific remove function that reduces (un)boxing.
* @param o the element that should be removed * @param o the element that should be removed
@@ -86,6 +122,16 @@ public interface COLLECTION KEY_GENERIC_TYPE extends Collection<CLASS_TYPE>, ITE
*/ */
public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c); public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c);
/**
* A Type-Specific removeAll function that reduces (un)boxing.
* It also notifies the remover of which exact element is going to be removed.
* @param c the collection of elements that should be removed
* @param r elements that got removed
* @return true if any element was removed
* @see Collection#removeAll(Collection)
*/
public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c, CONSUMER KEY_GENERIC_TYPE r);
/** /**
* A Type-Specific retainAll function that reduces (un)boxing. * A Type-Specific retainAll function that reduces (un)boxing.
* @param c the collection of elements that should be kept * @param c the collection of elements that should be kept
@@ -94,10 +140,51 @@ public interface COLLECTION KEY_GENERIC_TYPE extends Collection<CLASS_TYPE>, ITE
*/ */
public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c); public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c);
#if !TYPE_OBJECT /**
* A Type-Specific retainAll function that reduces (un)boxing.
* It also notifies the remover of which exact element is going to be removed.
* @param c the collection of elements that should be kept
* @param r elements that got removed
* @return true if any element was removed
* @see Collection#retainAll(Collection)
*/
public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c, CONSUMER KEY_GENERIC_TYPE r);
/**
* A Helper function to reduce the usage of Streams and allows to collect all elements
* @param collection that the elements should be inserted to
* @param <E> the collection type
* @return the input with the desired elements
*/
default <E extends COLLECTION KEY_GENERIC_TYPE> E pour(E collection) {
collection.addAll(this);
return collection;
}
/**
* A Function that does a shallow clone of the Collection itself.
* This function is more optimized then a copy constructor since the Collection does not have to be unsorted/resorted.
* It can be compared to Cloneable but with less exception risk
* @return a Shallow Copy of the collection
* @note Wrappers and view collections will not support this feature
*/
public COLLECTION KEY_GENERIC_TYPE copy();
#if TYPE_OBJECT
/**
* A Helper function that simplifies the process of creating a new Array.
* @param action the array creation function
* @return an array containing all of the elements in this collection
* @see Collection#toArray(Object[])
*/
default KEY_TYPE[] TO_ARRAY(Int2ObjectFunction<KEY_TYPE[]> action) {
return TO_ARRAY(action.get(size()));
}
#else
/** /**
* A Type-Specific toArray function that delegates to {@link #TO_ARRAY(KEY_TYPE[])} with a newly created array. * A Type-Specific toArray function that delegates to {@link #TO_ARRAY(KEY_TYPE[])} with a newly created array.
* @return an array containing all of the elements in this collection * @return an array containing all of the elements in this collection
* @see Collection#toArray() * @see Collection#toArray()
*/ */
public KEY_TYPE[] TO_ARRAY(); public KEY_TYPE[] TO_ARRAY();
@@ -105,8 +192,8 @@ public interface COLLECTION KEY_GENERIC_TYPE extends Collection<CLASS_TYPE>, ITE
/** /**
* A Type-Specific toArray function that reduces (un)boxing. * A Type-Specific toArray function that reduces (un)boxing.
* @param a array that the elements should be injected to. If null or to small a new array with the right size is created * @param a array that the elements should be injected to. If null or to small a new array with the right size is created
* @return an array containing all of the elements in this collection * @return an array containing all of the elements in this collection
* @see Collection#toArray(Object[]) * @see Collection#toArray(Object[])
*/ */
public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] a); public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] a);
@@ -135,16 +222,16 @@ public interface COLLECTION KEY_GENERIC_TYPE extends Collection<CLASS_TYPE>, ITE
* @throws java.lang.NullPointerException if filter is null * @throws java.lang.NullPointerException if filter is null
*/ */
public default boolean remIf(JAVA_PREDICATE filter) { public default boolean remIf(JAVA_PREDICATE filter) {
Objects.requireNonNull(filter); Objects.requireNonNull(filter);
boolean removed = false; boolean removed = false;
final ITERATOR each = iterator(); final ITERATOR each = iterator();
while (each.hasNext()) { while (each.hasNext()) {
if (filter.test(each.NEXT())) { if (filter.test(each.NEXT())) {
each.remove(); each.remove();
removed = true; removed = true;
} }
} }
return removed; return removed;
} }
#endif #endif
@@ -164,7 +251,7 @@ public interface COLLECTION KEY_GENERIC_TYPE extends Collection<CLASS_TYPE>, ITE
@Deprecated @Deprecated
public default boolean contains(Object o) { return o != null && contains(CLASS_TO_KEY(o)); } public default boolean contains(Object o) { return o != null && contains(CLASS_TO_KEY(o)); }
/** {@inheritDoc} /** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function. * <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead. * @deprecated Please use the corresponding type-specific function instead.
*/ */
@@ -181,6 +268,28 @@ public interface COLLECTION KEY_GENERIC_TYPE extends Collection<CLASS_TYPE>, ITE
@Override @Override
public ITERATOR KEY_GENERIC_TYPE iterator(); public ITERATOR KEY_GENERIC_TYPE iterator();
/**
* Creates a Wrapped Collection that is Synchronized
* @return a new Collection that is synchronized
* @see COLLECTIONS#synchronize
*/
public default COLLECTION KEY_GENERIC_TYPE synchronize() { return COLLECTIONS.synchronize(this); }
/**
* Creates a Wrapped Collection that is Synchronized
* @param mutex is the controller of the synchronization block
* @return a new Collection Wrapper that is synchronized
* @see COLLECTIONS#synchronize
*/
public default COLLECTION KEY_GENERIC_TYPE synchronize(Object mutex) { return COLLECTIONS.synchronize(this, mutex); }
/**
* Creates a Wrapped Collection that is unmodifiable
* @return a new Collection Wrapper that is unmodifiable
* @see COLLECTIONS#unmodifiable
*/
public default COLLECTION KEY_GENERIC_TYPE unmodifiable() { return COLLECTIONS.unmodifiable(this); }
#if PRIMITIVES #if PRIMITIVES
/** /**
* Returns a Java-Type-Specific Stream to reduce boxing/unboxing. * Returns a Java-Type-Specific Stream to reduce boxing/unboxing.
@@ -188,6 +297,11 @@ public interface COLLECTION KEY_GENERIC_TYPE extends Collection<CLASS_TYPE>, ITE
*/ */
default JAVA_STREAM primitiveStream() { return StreamSupport.NEW_STREAM(SPLIT_ITERATORS.createJavaSplititerator(this, 0), false); } default JAVA_STREAM primitiveStream() { return StreamSupport.NEW_STREAM(SPLIT_ITERATORS.createJavaSplititerator(this, 0), false); }
/**
* Returns a Java-Type-Specific Parallel Stream to reduce boxing/unboxing.
* @return a Stream of the closest java type
*/
default JAVA_STREAM parallelPrimitiveStream() { return StreamSupport.NEW_STREAM(SPLIT_ITERATORS.createJavaSplititerator(this, 0), true); }
#endif #endif
/** /**
* A Type Specific Type Splititerator to reduce boxing/unboxing * A Type Specific Type Splititerator to reduce boxing/unboxing
@@ -1,13 +1,23 @@
package speiger.src.collections.PACKAGE.collections; package speiger.src.collections.PACKAGE.collections;
#if !TYPE_OBJECT
import java.util.Objects; import java.util.Objects;
import java.util.function.Consumer; import java.util.function.Consumer;
#if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.functions.CONSUMER; import speiger.src.collections.PACKAGE.functions.CONSUMER;
import speiger.src.collections.objects.collections.ObjectIterable;
#else
import java.util.function.BiFunction;
#endif #endif
import speiger.src.collections.PACKAGE.functions.function.TO_OBJECT_FUNCTION;
import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER;
import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR;
import speiger.src.collections.PACKAGE.collections.SPLIT_ITERATOR; import speiger.src.collections.PACKAGE.collections.SPLIT_ITERATOR;
import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS; import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS;
import speiger.src.collections.PACKAGE.utils.ITERABLES;
import speiger.src.collections.PACKAGE.utils.ITERATORS;
/** /**
* A Type-Specific {@link Iterable} that reduces (un)boxing * A Type-Specific {@link Iterable} that reduces (un)boxing
@@ -15,28 +25,28 @@ import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS;
*/ */
public interface ITERABLE KEY_GENERIC_TYPE extends Iterable<CLASS_TYPE> public interface ITERABLE KEY_GENERIC_TYPE extends Iterable<CLASS_TYPE>
{ {
/** /**
* Returns an iterator over elements of type {@code T}. * Returns an iterator over elements of type {@code T}.
* *
* @return an Iterator. * @return an Iterator.
*/ */
@Override @Override
ITERATOR KEY_GENERIC_TYPE iterator(); ITERATOR KEY_GENERIC_TYPE iterator();
#if !TYPE_OBJECT
#if !TYPE_OBJECT
/** /**
* A Type Specific foreach function that reduces (un)boxing * A Type Specific foreach function that reduces (un)boxing
* *
* @implSpec * @implSpec
* <p>The default implementation behaves as if: * <p>The default implementation behaves as if:
* <pre>{@code * <pre>{@code
* iterator().forEachRemaining(action); * iterator().forEachRemaining(action);
* }</pre> * }</pre>
* *
* @param action The action to be performed for each element * @param action The action to be performed for each element
* @throws NullPointerException if the specified action is null * @throws NullPointerException if the specified action is null
* @see Iterable#forEach(Consumer) * @see Iterable#forEach(Consumer)
*/ */
default void forEach(CONSUMER action) { default void forEach(CONSUMER action) {
Objects.requireNonNull(action); Objects.requireNonNull(action);
iterator().forEachRemaining(action); iterator().forEachRemaining(action);
@@ -48,11 +58,23 @@ public interface ITERABLE KEY_GENERIC_TYPE extends Iterable<CLASS_TYPE>
*/ */
@Deprecated @Deprecated
@Override @Override
default void forEach(Consumer<? super CLASS_TYPE> action) { default void forEach(Consumer<? super CLASS_TYPE> action) {
Objects.requireNonNull(action); Objects.requireNonNull(action);
iterator().forEachRemaining(action); iterator().forEachRemaining(action);
} }
#endif #endif
/**
* Helper function to reduce Lambda usage and allow for more method references, since these are faster/cleaner.
* @param input the object that should be included
* @param action The action to be performed for each element
* @param <E> the generic type of the Object
* @throws java.lang.NullPointerException if the specified action is null
*/
default <E> void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
iterator().forEachRemaining(input, action);
}
/** /**
* A Type Specific Type Splititerator to reduce boxing/unboxing * A Type Specific Type Splititerator to reduce boxing/unboxing
@@ -60,4 +82,205 @@ public interface ITERABLE KEY_GENERIC_TYPE extends Iterable<CLASS_TYPE>
*/ */
@Override @Override
default SPLIT_ITERATOR KEY_GENERIC_TYPE spliterator() { return SPLIT_ITERATORS.createUnknownSplititerator(iterator(), 0); } default SPLIT_ITERATOR KEY_GENERIC_TYPE spliterator() { return SPLIT_ITERATORS.createUnknownSplititerator(iterator(), 0); }
/**
* A Helper function to reduce the usage of Streams and allows to convert a Iterable to something else.
* @param mapper the mapping function
* @param <E> The return type.
* @return a new Iterable that returns the desired result
*/
default <E> ObjectIterable<E> map(TO_OBJECT_FUNCTION KKS_GENERIC_TYPE<E> mapper) {
return ITERABLES.map(this, mapper);
}
/**
* A Helper function to reduce the usage of Streams and allows to convert a Iterable to something else.
* @param mapper the flatMapping function
* @param <V> The return type supplier.
* @param <E> The return type.
* @return a new Iterable that returns the desired result
*/
default <E, V extends Iterable<E>> ObjectIterable<E> flatMap(TO_OBJECT_FUNCTION KKS_GENERIC_TYPE<V> mapper) {
return ITERABLES.flatMap(this, mapper);
}
/**
* A Helper function to reduce the usage of Streams and allows to convert a Iterable to something else.
* @param mapper the flatMapping function
* @param <E> The return type.
* @return a new Iterable that returns the desired result
*/
default <E> ObjectIterable<E> arrayflatMap(TO_OBJECT_FUNCTION KKS_GENERIC_TYPE<E[]> mapper) {
return ITERABLES.arrayFlatMap(this, mapper);
}
/**
* A Helper function to reduce the usage of Streams and allows to filter out unwanted elements
* @param filter the elements that should be kept.
* @return a Iterable that filtered out all unwanted elements
*/
default ITERABLE KEY_GENERIC_TYPE filter(PREDICATE KEY_GENERIC_TYPE filter) {
return ITERABLES.filter(this, filter);
}
/**
* A Helper function to reduce the usage of Streams and allows to filter out duplicated elements
* @return a Iterable that filtered out all duplicated elements
*/
default ITERABLE KEY_GENERIC_TYPE distinct() {
return ITERABLES.distinct(this);
}
/**
* A Helper function to reduce the usage of Streams and allows to limit the amount of elements
* @param limit the amount of elements it should be limited to
* @return a Iterable that is limited in length
*/
default ITERABLE KEY_GENERIC_TYPE limit(long limit) {
return ITERABLES.limit(this, limit);
}
/**
* A Helper function to reduce the usage of Streams and allows to preview elements before they are iterated through
* @param action the action that should be applied
* @return a Peeked Iterable
*/
default ITERABLE KEY_GENERIC_TYPE peek(CONSUMER KEY_GENERIC_TYPE action) {
return ITERABLES.peek(this, action);
}
/**
* A Helper function to reduce the usage of Streams and allows to collect all elements
* @param collection that the elements should be inserted to
* @param <E> the collection type
* @return the input with the desired elements
*/
default <E extends COLLECTION KEY_GENERIC_TYPE> E pour(E collection) {
ITERATORS.pour(iterator(), collection);
return collection;
}
/**
* Helper function to reduce stream usage that allows to filter for any matches.
* @param filter that should be applied
* @return true if any matches were found
*/
default boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) {
if(filter.TEST_VALUE(iter.NEXT())) return true;
}
return false;
}
/**
* Helper function to reduce stream usage that allows to filter for no matches.
* @param filter that should be applied
* @return true if no matches were found
*/
default boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) {
if(filter.TEST_VALUE(iter.NEXT())) return false;
}
return true;
}
/**
* Helper function to reduce stream usage that allows to filter for all matches.
* @param filter that should be applied
* @return true if all matches.
*/
default boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) {
if(!filter.TEST_VALUE(iter.NEXT())) return false;
}
return true;
}
/**
* Helper function to reduce stream usage that allows to filter for the first match.
* @param filter that should be applied
* @return the found value or the null equivalent variant.
*/
default KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) {
KEY_TYPE entry = iter.NEXT();
if(filter.TEST_VALUE(entry)) return entry;
}
return EMPTY_VALUE;
}
#if !TYPE_OBJECT
/**
* Performs a <a href="package-summary.html#Reduction">reduction</a> on the
* elements of this Iterable
* @param operator the operation that should be applied
* @param identity the start value
* @return the reduction result, returns identity if nothing was found
*/
default KEY_TYPE reduce(KEY_TYPE identity, UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
KEY_TYPE state = identity;
for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) {
state = operator.APPLY_VALUE(state, iter.NEXT());
}
return state;
}
#else
/**
* Performs a <a href="package-summary.html#Reduction">reduction</a> on the
* elements of this Iterable
* @param operator the operation that should be applied
* @param identity the start value
* @Type(E)
* @return the reduction result, returns identity if nothing was found
*/
default <KEY_SPECIAL_TYPE> KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction<KEY_SPECIAL_TYPE, KEY_TYPE, KEY_SPECIAL_TYPE> operator) {
Objects.requireNonNull(operator);
KEY_SPECIAL_TYPE state = identity;
for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) {
state = operator.APPLY_VALUE(state, iter.NEXT());
}
return state;
}
#endif
/**
* Performs a <a href="package-summary.html#Reduction">reduction</a> on the
* elements of this Iterable
* @param operator the operation that should be applied
* @return the reduction result, returns null value if nothing was found
*/
default KEY_TYPE reduce(UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
KEY_TYPE state = EMPTY_VALUE;
boolean empty = true;
for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) {
if(empty) {
empty = false;
state = iter.NEXT();
continue;
}
state = operator.APPLY_VALUE(state, iter.NEXT());
}
return state;
}
/**
* Helper function to reduce stream usage that allows to count the valid elements.
* @param filter that should be applied
* @return the amount of Valid Elements
*/
default int count(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
int result = 0;
for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) {
if(filter.TEST_VALUE(iter.NEXT())) result++;
}
return result;
}
} }
@@ -1,13 +1,14 @@
package speiger.src.collections.PACKAGE.collections; package speiger.src.collections.PACKAGE.collections;
import java.util.Iterator; import java.util.Iterator;
#if !TYPE_OBJECT
import java.util.Objects; import java.util.Objects;
#if !TYPE_OBJECT
import java.util.function.Consumer; import java.util.function.Consumer;
import speiger.src.collections.PACKAGE.functions.CONSUMER; import speiger.src.collections.PACKAGE.functions.CONSUMER;
#endif #endif
import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER;
/** /**
* A Type-Specific {@link Iterator} that reduces (un)boxing * A Type-Specific {@link Iterator} that reduces (un)boxing
@@ -33,25 +34,25 @@ public interface ITERATOR KEY_GENERIC_TYPE extends Iterator<CLASS_TYPE>
@Deprecated @Deprecated
public default CLASS_TYPE next() { return KEY_TO_OBJ(NEXT()); } public default CLASS_TYPE next() { return KEY_TO_OBJ(NEXT()); }
/** /**
* Performs the given action for each remaining element until all elements * Performs the given action for each remaining element until all elements
* have been processed or the action throws an exception. Actions are * have been processed or the action throws an exception. Actions are
* performed in the order of iteration, if that order is specified. * performed in the order of iteration, if that order is specified.
* Exceptions thrown by the action are relayed to the caller. * Exceptions thrown by the action are relayed to the caller.
* *
* @implSpec * @implSpec
* <p>The default implementation behaves as if: * <p>The default implementation behaves as if:
* <pre>{@code * <pre>{@code
* while (hasNext()) action.accept(NEXT()); * while (hasNext()) action.accept(NEXT());
* }</pre> * }</pre>
* *
* @param action The action to be performed for each element * @param action The action to be performed for each element
* @throws java.lang.NullPointerException if the specified action is null * @throws java.lang.NullPointerException if the specified action is null
* @see Iterator#forEachRemaining(Consumer) * @see Iterator#forEachRemaining(Consumer)
*/ */
public default void forEachRemaining(CONSUMER action) { public default void forEachRemaining(CONSUMER action) {
Objects.requireNonNull(action); Objects.requireNonNull(action);
while(hasNext()) { action.accept(NEXT()); } while(hasNext()) { action.accept(NEXT()); }
} }
/** {@inheritDoc} /** {@inheritDoc}
@@ -61,11 +62,23 @@ public interface ITERATOR KEY_GENERIC_TYPE extends Iterator<CLASS_TYPE>
@Deprecated @Deprecated
@Override @Override
default void forEachRemaining(Consumer<? super CLASS_TYPE> action) { default void forEachRemaining(Consumer<? super CLASS_TYPE> action) {
Objects.requireNonNull(action); Objects.requireNonNull(action);
forEachRemaining(action::accept); forEachRemaining(action::accept);
} }
#endif #endif
/**
* Helper function to reduce Lambda usage and allow for more method references, since these are faster/cleaner.
* @param input the object that should be included
* @param action The action to be performed for each element
* @param <E> the generic type of the Object
* @throws java.lang.NullPointerException if the specified action is null
*/
default <E> void forEachRemaining(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
while(hasNext()) { action.accept(input, NEXT()); }
}
/** /**
* Skips the Given amount of elements if possible. A Optimization function to skip elements faster if the implementation allows it. * Skips the Given amount of elements if possible. A Optimization function to skip elements faster if the implementation allows it.
* @param amount the amount of elements that should be skipped * @param amount the amount of elements that should be skipped
@@ -5,14 +5,14 @@ import speiger.src.collections.utils.Stack;
/** /**
* A Type-Specific {@link Stack} that reduces (un)boxing * A Type-Specific {@link Stack} that reduces (un)boxing
*/ */
public interface STACK extends Stack<CLASS_TYPE> public interface STACK
{ {
/** /**
* Inserts a given Object on top of the stack * Inserts a given Object on top of the stack
* @param e the Object to insert * @param e the Object to insert
* @see Stack#push(Object) * @see Stack#push(Object)
*/ */
public void PUSH(KEY_TYPE e); public void push(KEY_TYPE e);
/** /**
* Removes the Object on top of the stack. * Removes the Object on top of the stack.
@@ -20,7 +20,7 @@ public interface STACK extends Stack<CLASS_TYPE>
* @throws ArrayIndexOutOfBoundsException if the stack is empty * @throws ArrayIndexOutOfBoundsException if the stack is empty
* @see Stack#pop() * @see Stack#pop()
*/ */
public KEY_TYPE POP(); public KEY_TYPE pop();
/** /**
* Provides the Object on top of the stack * Provides the Object on top of the stack
@@ -28,8 +28,8 @@ public interface STACK extends Stack<CLASS_TYPE>
* @throws ArrayIndexOutOfBoundsException if the stack is empty * @throws ArrayIndexOutOfBoundsException if the stack is empty
* @see Stack#top() * @see Stack#top()
*/ */
public default KEY_TYPE TOP() { public default KEY_TYPE top() {
return PEEK(0); return peek(0);
} }
/** /**
@@ -40,41 +40,23 @@ public interface STACK extends Stack<CLASS_TYPE>
* @throws ArrayIndexOutOfBoundsException if the index is out of bounds * @throws ArrayIndexOutOfBoundsException if the index is out of bounds
* @see Stack#peek(int) * @see Stack#peek(int)
*/ */
public KEY_TYPE PEEK(int index); public KEY_TYPE peek(int index);
#if !OBJECT_TYPE /**
/** {@inheritDoc} * Clears the stack
* <p>This default implementation delegates to the corresponding type-specific function. */
* @deprecated Please use the corresponding type-specific function instead. public void clear();
*/
@Override
@Deprecated
public default void push(CLASS_TYPE e) { PUSH(OBJ_TO_KEY(e)); }
/** {@inheritDoc} /**
* <p>This default implementation delegates to the corresponding type-specific function. * Provides the amount of elements currently in the stack
* @deprecated Please use the corresponding type-specific function instead. * @return amount of elements in the list
*/ */
@Override public int size();
@Deprecated
public default CLASS_TYPE pop() { return KEY_TO_OBJ(POP()); }
/** {@inheritDoc} /**
* <p>This default implementation delegates to the corresponding type-specific function. * @return if the stack is empty
* @deprecated Please use the corresponding type-specific function instead. */
*/ public default boolean isEmpty() {
@Override return size() == 0;
@Deprecated
public default CLASS_TYPE top() {
return peek(size() - 1);
} }
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
public default CLASS_TYPE peek(int index) { return KEY_TO_OBJ(PEEK(index)); }
#endif
} }
@@ -10,17 +10,17 @@ public interface COMPARATOR extends Comparator<CLASS_TYPE>
{ {
/** /**
* Type-Specific compare function to reduce (un)boxing * Type-Specific compare function to reduce (un)boxing
* @param o1 the first object to be compared. * @param o1 the first object to be compared.
* @param o2 the second object to be compared. * @param o2 the second object to be compared.
* @return a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second. * @return a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
* @see Comparator#compare(Object, Object) * @see Comparator#compare(Object, Object)
*/ */
int compare(KEY_TYPE o1, KEY_TYPE o2); int compare(KEY_TYPE o1, KEY_TYPE o2);
/** {@inheritDoc} /** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function. * <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead. * @deprecated Please use the corresponding type-specific function instead.
*/ */
@Override @Override
@Deprecated @Deprecated
default int compare(CLASS_TYPE o1, CLASS_TYPE o2) { default int compare(CLASS_TYPE o1, CLASS_TYPE o2) {
@@ -12,12 +12,12 @@ public interface CONSUMER extends Consumer<CLASS_TYPE>, JAVA_CONSUMER
public interface CONSUMER extends Consumer<CLASS_TYPE> public interface CONSUMER extends Consumer<CLASS_TYPE>
#endif #endif
{ {
/** /**
* Type-Specific function to reduce (un)boxing. * Type-Specific function to reduce (un)boxing.
* Performs this operation on the given argument. * Performs this operation on the given argument.
* *
* @param t the input argument * @param t the input argument
*/ */
void accept(KEY_TYPE t); void accept(KEY_TYPE t);
/** /**
@@ -0,0 +1,26 @@
package speiger.src.collections.PACKAGE.functions;
/**
* Type-Specific Supplier interface that reduces (un)boxing and allows to merge other consumer types into this interface
* @Type(T)
*/
#if TYPE_OBJECT
public interface SUPPLIER KEY_GENERIC_TYPE extends java.util.function.Supplier<KEY_TYPE>
#else if JDK_TYPE && !TYPE_BOOLEAN
public interface SUPPLIER KEY_GENERIC_TYPE extends JAVA_SUPPLIER
#else
public interface SUPPLIER KEY_GENERIC_TYPE
#endif
{
/**
* @return the supplied value
*/
public KEY_TYPE GET_KEY();
#if JDK_TYPE && PRIMITIVES
@Override
public default KEY_TYPE GET_JAVA() {
return GET_KEY();
}
#endif
}
@@ -10,13 +10,13 @@ import java.util.function.BiConsumer;
*/ */
public interface BI_CONSUMER KEY_VALUE_GENERIC_TYPE extends BiConsumer<CLASS_TYPE, CLASS_VALUE_TYPE> public interface BI_CONSUMER KEY_VALUE_GENERIC_TYPE extends BiConsumer<CLASS_TYPE, CLASS_VALUE_TYPE>
{ {
/** /**
* A Type Specific operation method to reduce boxing/unboxing * A Type Specific operation method to reduce boxing/unboxing
* Performs this operation on the given arguments. * Performs this operation on the given arguments.
* *
* @param k the first input argument * @param k the first input argument
* @param v the second input argument * @param v the second input argument
*/ */
void accept(KEY_TYPE k, VALUE_TYPE v); void accept(KEY_TYPE k, VALUE_TYPE v);
/** /**
@@ -34,15 +34,15 @@ public interface FUNCTION KEY_VALUE_GENERIC_TYPE
* @return a function that compares values in a and comparason * @return a function that compares values in a and comparason
*/ */
public default FUNCTION KEY_VALUE_GENERIC_TYPE andType(FUNCTION KEY_VALUE_GENERIC_TYPE other) { public default FUNCTION KEY_VALUE_GENERIC_TYPE andType(FUNCTION KEY_VALUE_GENERIC_TYPE other) {
Objects.requireNonNull(other); Objects.requireNonNull(other);
return T -> GET_VALUE(T) && other.GET_VALUE(T); return T -> GET_VALUE(T) && other.GET_VALUE(T);
} }
@Override @Override
@Deprecated @Deprecated
public default FUNCTION KEY_VALUE_GENERIC_TYPE and(JAVA_FUNCTION KEY_VALUE_SUPER_GENERIC_TYPE other) { public default FUNCTION KEY_VALUE_GENERIC_TYPE and(JAVA_FUNCTION KEY_VALUE_SUPER_GENERIC_TYPE other) {
Objects.requireNonNull(other); Objects.requireNonNull(other);
return T -> GET_VALUE(T) && other.test(T); return T -> GET_VALUE(T) && other.test(T);
} }
@Override @Override
@@ -56,15 +56,15 @@ public interface FUNCTION KEY_VALUE_GENERIC_TYPE
* @return a function that compares values in a or comparason * @return a function that compares values in a or comparason
*/ */
public default FUNCTION KEY_VALUE_GENERIC_TYPE orType(FUNCTION KEY_VALUE_GENERIC_TYPE other) { public default FUNCTION KEY_VALUE_GENERIC_TYPE orType(FUNCTION KEY_VALUE_GENERIC_TYPE other) {
Objects.requireNonNull(other); Objects.requireNonNull(other);
return T -> GET_VALUE(T) || other.GET_VALUE(T); return T -> GET_VALUE(T) || other.GET_VALUE(T);
} }
@Override @Override
@Deprecated @Deprecated
public default FUNCTION KEY_VALUE_GENERIC_TYPE or(JAVA_FUNCTION KEY_VALUE_SUPER_GENERIC_TYPE other) { public default FUNCTION KEY_VALUE_GENERIC_TYPE or(JAVA_FUNCTION KEY_VALUE_SUPER_GENERIC_TYPE other) {
Objects.requireNonNull(other); Objects.requireNonNull(other);
return T -> GET_VALUE(T) || other.test(T); return T -> GET_VALUE(T) || other.test(T);
} }
#else if VALUE_OBJECT #else if VALUE_OBJECT
@@ -24,12 +24,12 @@ public interface UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE extends BiFunction<CLASS_
#else #else
/** /**
* A Type Specifc apply method to reduce boxing/unboxing. * A Type Specifc apply method to reduce boxing/unboxing.
* Applies this function to the given arguments. * Applies this function to the given arguments.
* *
* @param k the first function argument * @param k the first function argument
* @param v the second function argument * @param v the second function argument
* @return the function result * @return the function result
*/ */
public VALUE_TYPE APPLY_VALUE(KEY_TYPE k, VALUE_TYPE v); public VALUE_TYPE APPLY_VALUE(KEY_TYPE k, VALUE_TYPE v);
@Override @Override
@@ -3,11 +3,15 @@ package speiger.src.collections.PACKAGE.lists;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.ListIterator; import java.util.ListIterator;
import java.util.NoSuchElementException;
import java.util.Objects; import java.util.Objects;
import speiger.src.collections.PACKAGE.collections.ABSTRACT_COLLECTION; import speiger.src.collections.PACKAGE.collections.ABSTRACT_COLLECTION;
import speiger.src.collections.PACKAGE.collections.COLLECTION; import speiger.src.collections.PACKAGE.collections.COLLECTION;
import speiger.src.collections.PACKAGE.collections.ITERATOR; import speiger.src.collections.PACKAGE.collections.ITERATOR;
import speiger.src.collections.PACKAGE.collections.SPLIT_ITERATOR;
import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS;
import speiger.src.collections.utils.SanityChecks;
/** /**
* Abstract implementation of the {@link LIST} interface. * Abstract implementation of the {@link LIST} interface.
@@ -15,9 +19,8 @@ import speiger.src.collections.PACKAGE.collections.ITERATOR;
*/ */
public abstract class ABSTRACT_LIST KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION KEY_GENERIC_TYPE implements LIST KEY_GENERIC_TYPE public abstract class ABSTRACT_LIST KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION KEY_GENERIC_TYPE implements LIST KEY_GENERIC_TYPE
{ {
#if !TYPE_OBJECT
/** /**
* A Type-Specific implementation of add function that delegates to {@link #add(int, KEY_TYPE)} * A Type-Specific implementation of add function that delegates to {@link List#add(int, Object)}
*/ */
@Override @Override
public boolean add(KEY_TYPE e) { public boolean add(KEY_TYPE e) {
@@ -25,6 +28,7 @@ public abstract class ABSTRACT_LIST KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION
return true; return true;
} }
#if !TYPE_OBJECT
/** {@inheritDoc} /** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function. * <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead. * @deprecated Please use the corresponding type-specific function instead.
@@ -43,9 +47,7 @@ public abstract class ABSTRACT_LIST KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION
*/ */
@Override @Override
public boolean addAll(COLLECTION KEY_GENERIC_TYPE c) { public boolean addAll(COLLECTION KEY_GENERIC_TYPE c) {
boolean modified = false; return addAll(size(), c);
for(ITERATOR KEY_GENERIC_TYPE iter = c.iterator();iter.hasNext();modified |= add(iter.NEXT()));
return modified;
} }
/** /**
@@ -55,9 +57,18 @@ public abstract class ABSTRACT_LIST KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION
*/ */
@Override @Override
public boolean addAll(LIST KEY_GENERIC_TYPE c) { public boolean addAll(LIST KEY_GENERIC_TYPE c) {
boolean modified = false; return addAll(size(), c);
for(ITERATOR KEY_GENERIC_TYPE iter = c.iterator();iter.hasNext();modified |= add(iter.NEXT())); }
return modified;
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
public boolean addAll(Collection<? extends CLASS_TYPE> c)
{
return c instanceof COLLECTION ? addAll((COLLECTION KEY_GENERIC_TYPE)c) : addAll(size(), c);
} }
/** /**
@@ -148,36 +159,44 @@ public abstract class ABSTRACT_LIST KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION
} }
#endif #endif
@Override
public boolean REMOVE_SWAP(KEY_TYPE e) {
int index = indexOf(e);
if(index == -1) return false;
swapRemove(index);
return true;
}
/** /**
* Compares if the list are the same. * Compares if the list are the same.
*/ */
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (o == this) if (o == this)
return true; return true;
if (!(o instanceof List)) if (!(o instanceof List))
return false; return false;
List<?> l = (List<?>)o; List<?> l = (List<?>)o;
if(l.size() != size()) return false; if(l.size() != size()) return false;
#if !TYPE_OBJECT #if !TYPE_OBJECT
if(l instanceof LIST) if(l instanceof LIST)
{ {
LIST_ITERATOR e1 = listIterator(); LIST_ITERATOR e1 = listIterator();
LIST_ITERATOR e2 = ((LIST)l).listIterator(); LIST_ITERATOR e2 = ((LIST)l).listIterator();
while (e1.hasNext() && e2.hasNext()) { while (e1.hasNext() && e2.hasNext()) {
if(!(KEY_EQUALS(e1.NEXT(), e2.NEXT()))) if(!(KEY_EQUALS(e1.NEXT(), e2.NEXT())))
return false; return false;
} }
return !(e1.hasNext() || e2.hasNext()); return !(e1.hasNext() || e2.hasNext());
} }
#endif #endif
ListIterator<CLASS_TYPE> e1 = listIterator(); ListIterator<CLASS_TYPE> e1 = listIterator();
ListIterator<?> e2 = l.listIterator(); ListIterator<?> e2 = l.listIterator();
while (e1.hasNext() && e2.hasNext()) { while (e1.hasNext() && e2.hasNext()) {
if(!Objects.equals(e1.next(), e2.next())) if(!Objects.equals(e1.next(), e2.next()))
return false; return false;
} }
return !(e1.hasNext() || e2.hasNext()); return !(e1.hasNext() || e2.hasNext());
} }
/** /**
@@ -185,20 +204,21 @@ public abstract class ABSTRACT_LIST KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION
*/ */
@Override @Override
public int hashCode() { public int hashCode() {
int hashCode = 1; int hashCode = 1;
LIST_ITERATOR KEY_GENERIC_TYPE i = listIterator(); LIST_ITERATOR KEY_GENERIC_TYPE i = listIterator();
while(i.hasNext()) while(i.hasNext())
#if TYPE_OBJECT #if TYPE_OBJECT
hashCode = 31 * hashCode + i.next().hashCode(); hashCode = 31 * hashCode + i.next().hashCode();
#else #else
hashCode = 31 * hashCode + KEY_TO_HASH(i.NEXT()); hashCode = 31 * hashCode + KEY_TO_HASH(i.NEXT());
#endif #endif
return hashCode; return hashCode;
} }
@Override @Override
public LIST KEY_GENERIC_TYPE subList(int fromIndex, int toIndex) { public LIST KEY_GENERIC_TYPE subList(int fromIndex, int toIndex) {
return new SUB_LIST(this, fromIndex, toIndex); SanityChecks.checkArrayCapacity(size(), fromIndex, toIndex-fromIndex);
return new SubList(this, 0, fromIndex, toIndex);
} }
@Override @Override
@@ -213,6 +233,7 @@ public abstract class ABSTRACT_LIST KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION
@Override @Override
public LIST_ITERATOR KEY_GENERIC_TYPE listIterator(int index) { public LIST_ITERATOR KEY_GENERIC_TYPE listIterator(int index) {
if(index < 0 || index > size()) throw new IndexOutOfBoundsException();
return new LIST_ITER(index); return new LIST_ITER(index);
} }
@@ -222,116 +243,130 @@ public abstract class ABSTRACT_LIST KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION
while(size < size()) REMOVE(size() - 1); while(size < size()) REMOVE(size() - 1);
} }
private class SUB_LIST extends ABSTRACT_LIST KEY_GENERIC_TYPE { public ABSTRACT_LIST KEY_GENERIC_TYPE copy() { throw new UnsupportedOperationException(); }
ABSTRACT_LIST KEY_GENERIC_TYPE l;
int offset; private class SubList extends ABSTRACT_LIST KEY_GENERIC_TYPE
{
final ABSTRACT_LIST KEY_GENERIC_TYPE list;
final int parentOffset;
final int offset;
int size; int size;
SUB_LIST(ABSTRACT_LIST KEY_GENERIC_TYPE l, int from, int to) { public SubList(ABSTRACT_LIST KEY_GENERIC_TYPE list, int offset, int from, int to) {
if (from < 0) throw new IndexOutOfBoundsException("fromIndex = " + from); this.list = list;
else if (to > l.size()) throw new IndexOutOfBoundsException("toIndex = " + to); this.parentOffset = from;
else if (from > to) throw new IllegalArgumentException("fromIndex(" + from + ") > toIndex(" + to + ")"); this.offset = offset + from;
this.l = l; this.size = to - from;
offset = from;
size = to - from;
} }
@Override @Override
public void add(int index, KEY_TYPE e) { public void add(int index, KEY_TYPE element) {
checkAddRange(index); checkAddSubRange(index);
l.add(index+offset, e); list.add(parentOffset+index, element);
size++; size++;
} }
@Override @Override
public boolean addAll(int index, Collection<? extends CLASS_TYPE> c) { public boolean addAll(int index, Collection<? extends CLASS_TYPE> c) {
checkAddRange(index); checkAddSubRange(index);
int size = c.size(); int add = c.size();
if(size == 0) return false; if(add <= 0) return false;
l.addAll(index + offset, l); list.addAll(parentOffset+index, c);
offset += size; this.size += add;
return true; return true;
} }
@Override @Override
public boolean addAll(int index, COLLECTION KEY_GENERIC_TYPE c) { public boolean addAll(int index, COLLECTION KEY_GENERIC_TYPE c) {
checkAddRange(index); checkAddSubRange(index);
int size = c.size(); int add = c.size();
if(size == 0) return false; if(add <= 0) return false;
l.addAll(index + offset, l); list.addAll(parentOffset+index, c);
offset += size; this.size += add;
return true; return true;
} }
@Override @Override
public boolean addAll(int index, LIST KEY_GENERIC_TYPE c) { public boolean addAll(int index, LIST KEY_GENERIC_TYPE c) {
checkAddRange(index); checkAddSubRange(index);
int size = c.size(); int add = c.size();
if(size == 0) return false; if(add <= 0) return false;
l.addAll(index + offset, l); list.addAll(parentOffset+index, c);
offset += size; this.size += add;
return true; return true;
} }
@Override @Override
public void addElements(int from, KEY_TYPE[] a, int offset, int length) { public void addElements(int from, KEY_TYPE[] a, int offset, int length) {
checkRange(from); checkAddSubRange(from);
l.addElements(from + this.offset, a, offset, length); if(length <= 0) return;
size += length; list.addElements(parentOffset+from, a, offset, length);
this.size += length;
} }
@Override @Override
public KEY_TYPE[] getElements(int from, KEY_TYPE[] a, int offset, int length) { public KEY_TYPE[] getElements(int from, KEY_TYPE[] a, int offset, int length) {
checkRange(from); SanityChecks.checkArrayCapacity(size, from, length);
return l.getElements(from + this.offset, a, offset, length); SanityChecks.checkArrayCapacity(a.length, offset, length);
return list.getElements(from+this.offset, a, offset, length);
} }
@Override @Override
public void removeElements(int from, int to) { public void removeElements(int from, int to) {
checkRange(from); if(to-from <= 0) return;
checkRange(to); checkSubRange(from);
l.removeElements(from + offset, to + offset); checkSubRange(to);
list.removeElements(from+parentOffset, to+parentOffset);
size -= to - from; size -= to - from;
} }
#if TYPE_OBJECT #if TYPE_OBJECT
@Override @Override
public <K> K[] extractElements(int from, int to, Class<K> clz) { public <K> K[] extractElements(int from, int to, Class<K> type) {
checkRange(from); checkSubRange(from);
checkRange(to); checkSubRange(to);
K[] a = l.extractElements(from + offset, to + offset, clz); K[] result = list.extractElements(from+parentOffset, to+parentOffset, type);
size -= to - from; size -= to - from;
return a; return result;
} }
#else #else
@Override @Override
public KEY_TYPE[] extractElements(int from, int to) { public KEY_TYPE[] extractElements(int from, int to) {
checkRange(from); checkSubRange(from);
checkRange(to); checkSubRange(to);
KEY_TYPE[] a = l.extractElements(from + offset, to + offset); KEY_TYPE[] result = list.extractElements(from+parentOffset, to+parentOffset);
size -= to - from; size -= to - from;
return a; return result;
} }
#endif #endif
@Override @Override
public KEY_TYPE GET_KEY(int index) { public KEY_TYPE GET_KEY(int index) {
checkRange(index); checkSubRange(index);
return l.GET_KEY(index + offset); return list.GET_KEY(offset+index);
} }
@Override @Override
public KEY_TYPE set(int index, KEY_TYPE e) { public KEY_TYPE set(int index, KEY_TYPE element) {
checkRange(index); checkSubRange(index);
return l.set(index + offset, e); return list.set(offset+index, element);
}
@Override
public KEY_TYPE swapRemove(int index) {
checkSubRange(index);
KEY_TYPE result = list.swapRemove(index+parentOffset);
size--;
return result;
} }
@Override @Override
public KEY_TYPE REMOVE(int index) { public KEY_TYPE REMOVE(int index) {
checkRange(index); checkSubRange(index);
KEY_TYPE result = list.REMOVE(index+parentOffset);
size--; size--;
return l.REMOVE(index + offset); return result;
} }
@Override @Override
@@ -339,15 +374,112 @@ public abstract class ABSTRACT_LIST KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION
return size; return size;
} }
private void checkRange(int index) { @Override
public SPLIT_ITERATOR KEY_GENERIC_TYPE spliterator() { return SPLIT_ITERATORS.createSplititerator(this, 16464); }
@Override
public LIST_ITERATOR KEY_GENERIC_TYPE listIterator(int index) {
if(index < 0 || index > size()) throw new IndexOutOfBoundsException();
return new SubListIterator(this, index);
}
@Override
public LIST KEY_GENERIC_TYPE subList(int fromIndex, int toIndex) {
SanityChecks.checkArrayCapacity(size, fromIndex, toIndex-fromIndex);
return new SubList(list, offset, fromIndex, toIndex);
}
protected void checkSubRange(int index) {
if (index < 0 || index >= size) if (index < 0 || index >= size)
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size); throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
} }
private void checkAddRange(int index) { protected void checkAddSubRange(int index) {
if (index < 0 || index > size) if (index < 0 || index > size)
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size); throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
} }
private class SubListIterator implements LIST_ITERATOR KEY_GENERIC_TYPE
{
ABSTRACT_LIST KEY_GENERIC_TYPE list;
int index;
int lastReturned = -1;
SubListIterator(ABSTRACT_LIST KEY_GENERIC_TYPE list, int index) {
this.list = list;
this.index = index;
}
@Override
public boolean hasNext() {
return index < list.size();
}
@Override
public KEY_TYPE NEXT() {
if(!hasNext()) throw new NoSuchElementException();
int i = index++;
return list.GET_KEY((lastReturned = i));
}
@Override
public boolean hasPrevious() {
return index > 0;
}
@Override
public KEY_TYPE PREVIOUS() {
if(!hasPrevious()) throw new NoSuchElementException();
index--;
return list.GET_KEY((lastReturned = index));
}
@Override
public int nextIndex() {
return index;
}
@Override
public int previousIndex() {
return index-1;
}
@Override
public void remove() {
if(lastReturned == -1) throw new IllegalStateException();
list.REMOVE(lastReturned);
index = lastReturned;
lastReturned = -1;
}
@Override
public void set(KEY_TYPE e) {
if(lastReturned == -1) throw new IllegalStateException();
list.set(lastReturned, e);
}
@Override
public void add(KEY_TYPE e) {
list.add(index++, e);
lastReturned = -1;
}
@Override
public int skip(int amount) {
if(amount < 0) throw new IllegalStateException("Negative Numbers are not allowed");
int steps = Math.min(amount, (list.size() - 1) - index);
index += steps;
return steps;
}
@Override
public int back(int amount) {
if(amount < 0) throw new IllegalStateException("Negative Numbers are not allowed");
int steps = Math.min(amount, index);
index -= steps;
return steps;
}
}
} }
private class LIST_ITER implements LIST_ITERATOR KEY_GENERIC_TYPE { private class LIST_ITER implements LIST_ITERATOR KEY_GENERIC_TYPE {
@@ -365,8 +497,9 @@ public abstract class ABSTRACT_LIST KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION
@Override @Override
public KEY_TYPE NEXT() { public KEY_TYPE NEXT() {
lastReturned = index; if(!hasNext()) throw new NoSuchElementException();
return GET_KEY(index++); int i = index++;
return GET_KEY((lastReturned = i));
} }
@Override @Override
@@ -376,8 +509,9 @@ public abstract class ABSTRACT_LIST KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION
@Override @Override
public KEY_TYPE PREVIOUS() { public KEY_TYPE PREVIOUS() {
lastReturned = index; if(!hasPrevious()) throw new NoSuchElementException();
return GET_KEY(index--); index--;
return GET_KEY((lastReturned = index));
} }
@Override @Override
@@ -392,25 +526,20 @@ public abstract class ABSTRACT_LIST KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION
@Override @Override
public void remove() { public void remove() {
if(lastReturned == -1) if(lastReturned == -1) throw new IllegalStateException();
throw new IllegalStateException();
ABSTRACT_LIST.this.REMOVE(lastReturned); ABSTRACT_LIST.this.REMOVE(lastReturned);
if(lastReturned < index) index = lastReturned;
index--;
lastReturned = -1; lastReturned = -1;
} }
@Override @Override
public void set(KEY_TYPE e) { public void set(KEY_TYPE e) {
if(lastReturned == -1) if(lastReturned == -1) throw new IllegalStateException();
throw new IllegalStateException();
ABSTRACT_LIST.this.set(lastReturned, e); ABSTRACT_LIST.this.set(lastReturned, e);
} }
@Override @Override
public void add(KEY_TYPE e) { public void add(KEY_TYPE e) {
if(lastReturned == -1)
throw new IllegalStateException();
ABSTRACT_LIST.this.add(index++, e); ABSTRACT_LIST.this.add(index++, e);
lastReturned = -1; lastReturned = -1;
} }
@@ -9,12 +9,14 @@ import java.util.Iterator;
import java.util.Objects; import java.util.Objects;
#if TYPE_OBJECT #if TYPE_OBJECT
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.function.BiFunction;
#endif #endif
import java.util.function.Predicate; import java.util.function.Predicate;
import java.util.function.UnaryOperator; import java.util.function.UnaryOperator;
#if PRIMITIVES #if PRIMITIVES
import java.util.function.JAVA_PREDICATE; import java.util.function.JAVA_PREDICATE;
import java.util.function.JAVA_UNARY_OPERATOR; import java.util.function.JAVA_UNARY_OPERATOR;
import java.nio.JAVA_BUFFER;
#endif #endif
import speiger.src.collections.PACKAGE.collections.COLLECTION; import speiger.src.collections.PACKAGE.collections.COLLECTION;
@@ -26,6 +28,9 @@ import speiger.src.collections.PACKAGE.collections.ITERATOR;
import speiger.src.collections.PACKAGE.functions.COMPARATOR; import speiger.src.collections.PACKAGE.functions.COMPARATOR;
import speiger.src.collections.PACKAGE.functions.CONSUMER; import speiger.src.collections.PACKAGE.functions.CONSUMER;
#endif #endif
import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER;
import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR;
import speiger.src.collections.PACKAGE.utils.ARRAYS; import speiger.src.collections.PACKAGE.utils.ARRAYS;
import speiger.src.collections.PACKAGE.utils.ITERATORS; import speiger.src.collections.PACKAGE.utils.ITERATORS;
#if TYPE_OBJECT #if TYPE_OBJECT
@@ -88,6 +93,7 @@ public class ARRAY_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
* Creates a new ArrayList a copy with the contents of the Collection. * Creates a new ArrayList a copy with the contents of the Collection.
* @param c the elements that should be added into the list * @param c the elements that should be added into the list
*/ */
@Primitive
public ARRAY_LIST(Collection<? extends CLASS_TYPE> c) { public ARRAY_LIST(Collection<? extends CLASS_TYPE> c) {
this(c.size()); this(c.size());
size = ITERATORS.unwrap(data, c.iterator()); size = ITERATORS.unwrap(data, c.iterator());
@@ -116,7 +122,7 @@ public class ARRAY_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
* Creates a new ArrayList with a Copy of the array * Creates a new ArrayList with a Copy of the array
* @param a the array that should be copied * @param a the array that should be copied
*/ */
public ARRAY_LIST(KEY_TYPE[] a) { public ARRAY_LIST(KEY_TYPE... a) {
this(a, 0, a.length); this(a, 0, a.length);
} }
@@ -178,7 +184,7 @@ public class ARRAY_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
*/ */
public static GENERIC_KEY_BRACES ARRAY_LIST KEY_GENERIC_TYPE of(Class<KEY_TYPE> c) { public static GENERIC_KEY_BRACES ARRAY_LIST KEY_GENERIC_TYPE of(Class<KEY_TYPE> c) {
ARRAY_LIST KEY_GENERIC_TYPE list = new ARRAY_LISTBRACES(); ARRAY_LIST KEY_GENERIC_TYPE list = new ARRAY_LISTBRACES();
list.data = (KEY_TYPE[])ObjectArrays.newArray(c.getClass().getComponentType(), 0); list.data = (KEY_TYPE[])ObjectArrays.newArray(c, 0);
return list; return list;
} }
@@ -201,7 +207,7 @@ public class ARRAY_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
* @param e element to be appended to this Stack * @param e element to be appended to this Stack
*/ */
@Override @Override
public void PUSH(KEY_TYPE e) { public void push(KEY_TYPE e) {
add(e); add(e);
} }
@@ -226,7 +232,6 @@ public class ARRAY_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
* @param index the index where to append the elements to * @param index the index where to append the elements to
* @param c the elements to append to the list * @param c the elements to append to the list
* @throws IndexOutOfBoundsException if index is outside of the lists range * @throws IndexOutOfBoundsException if index is outside of the lists range
* @deprecated if type is primitive
*/ */
@Override @Override
@Primitive @Primitive
@@ -238,7 +243,7 @@ public class ARRAY_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
if(index != size) System.arraycopy(data, index, data, index+add, size - index); if(index != size) System.arraycopy(data, index, data, index+add, size - index);
size+=add; size+=add;
Iterator<? extends CLASS_TYPE> iter = c.iterator(); Iterator<? extends CLASS_TYPE> iter = c.iterator();
while(add != 0) data[index++] = OBJ_TO_KEY(iter.next()); while(add-- != 0) data[index++] = OBJ_TO_KEY(iter.next());
return true; return true;
} }
@@ -248,7 +253,6 @@ public class ARRAY_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
* @param index the index where to append the elements to * @param index the index where to append the elements to
* @param c the elements to append to the list * @param c the elements to append to the list
* @throws IndexOutOfBoundsException if index is outside of the lists range * @throws IndexOutOfBoundsException if index is outside of the lists range
* @deprecated if type is primitive
*/ */
@Override @Override
public boolean addAll(int index, COLLECTION KEY_GENERIC_TYPE c) { public boolean addAll(int index, COLLECTION KEY_GENERIC_TYPE c) {
@@ -268,7 +272,6 @@ public class ARRAY_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
* @param index the index where to append the elements to * @param index the index where to append the elements to
* @param c the elements to append to the list * @param c the elements to append to the list
* @throws IndexOutOfBoundsException if index is outside of the lists range * @throws IndexOutOfBoundsException if index is outside of the lists range
* @deprecated if type is primitive
*/ */
@Override @Override
public boolean addAll(int index, LIST KEY_GENERIC_TYPE c) { public boolean addAll(int index, LIST KEY_GENERIC_TYPE c) {
@@ -282,6 +285,16 @@ public class ARRAY_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
return true; return true;
} }
@Override
public boolean addAll(KEY_TYPE[] e, int offset, int length) {
if(length <= 0) return false;
SanityChecks.checkArrayCapacity(e.length, offset, length);
grow(size + length);
System.arraycopy(e, offset, data, size, length);
size+=length;
return true;
}
/** /**
* Appends the specified array elements to the index of the list. * Appends the specified array elements to the index of the list.
* @param from the index where to append the elements to * @param from the index where to append the elements to
@@ -289,7 +302,6 @@ public class ARRAY_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
* @param offset where to start ino the array * @param offset where to start ino the array
* @param length the amount of elements to insert * @param length the amount of elements to insert
* @throws IndexOutOfBoundsException if index is outside of the lists range * @throws IndexOutOfBoundsException if index is outside of the lists range
* @deprecated if type is primitive
*/ */
@Override @Override
public void addElements(int from, KEY_TYPE[] a, int offset, int length) { public void addElements(int from, KEY_TYPE[] a, int offset, int length) {
@@ -314,7 +326,8 @@ public class ARRAY_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
*/ */
@Override @Override
public KEY_TYPE[] getElements(int from, KEY_TYPE[] a, int offset, int length) { public KEY_TYPE[] getElements(int from, KEY_TYPE[] a, int offset, int length) {
SanityChecks.checkArrayCapacity(size, offset, length); SanityChecks.checkArrayCapacity(size, from, length);
SanityChecks.checkArrayCapacity(a.length, offset, length);
System.arraycopy(data, from, a, offset, length); System.arraycopy(data, from, a, offset, length);
return a; return a;
} }
@@ -380,12 +393,17 @@ public class ARRAY_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
} }
#endif #endif
#if PRIMITIVES
@Override
public void fillBuffer(JAVA_BUFFER buffer) {
buffer.put(data, 0, size);
}
#endif
/** /**
* A function to find if the Element is present in this list. * A function to find if the Element is present in this list.
* @param o the element that is searched for * @param o the element that is searched for
* @return if the element was found. * @return if the element was found.
* @deprecated if type-specific but still supported because of special edgecase Object-Comparason features
*/ */
@Override @Override
@Primitive @Primitive
@@ -397,7 +415,6 @@ public class ARRAY_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
* A function to find the index of a given element * A function to find the index of a given element
* @param o the element that is searched for * @param o the element that is searched for
* @return the index of the element if found. (if not found then -1) * @return the index of the element if found. (if not found then -1)
* @deprecated if type-specific but still supported because of special edgecase Object-Comparason features
*/ */
@Override @Override
@Primitive @Primitive
@@ -421,7 +438,6 @@ public class ARRAY_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
* A function to find the last index of a given element * A function to find the last index of a given element
* @param o the element that is searched for * @param o the element that is searched for
* @return the last index of the element if found. (if not found then -1) * @return the last index of the element if found. (if not found then -1)
* @deprecated if type-specific but still supported because of special edgecase Object-Comparason features
*/ */
@Override @Override
@Primitive @Primitive
@@ -450,7 +466,7 @@ public class ARRAY_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
@Override @Override
public void sort(Comparator<? super CLASS_TYPE> c) { public void sort(Comparator<? super CLASS_TYPE> c) {
if(c != null) ARRAYS.stableSort(data, size, c); if(c != null) ARRAYS.stableSort(data, size, c);
else ARRAYS.stableSort((Comparable[])data, size); else ARRAYS.stableSort(data, size);
} }
/** /**
@@ -461,7 +477,7 @@ public class ARRAY_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
@Override @Override
public void unstableSort(Comparator<? super CLASS_TYPE> c) { public void unstableSort(Comparator<? super CLASS_TYPE> c) {
if(c != null) ARRAYS.unstableSort(data, size, c); if(c != null) ARRAYS.unstableSort(data, size, c);
else ARRAYS.unstableSort((Comparable[])data, size); else ARRAYS.unstableSort(data, size);
} }
#else #else
@@ -547,7 +563,7 @@ public class ARRAY_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
* @see speiger.src.collections.utils.Stack#peek(int) * @see speiger.src.collections.utils.Stack#peek(int)
*/ */
@Override @Override
public KEY_TYPE PEEK(int index) { public KEY_TYPE peek(int index) {
checkRange((size() - 1) - index); checkRange((size() - 1) - index);
return data[(size() - 1) - index]; return data[(size() - 1) - index];
} }
@@ -575,17 +591,17 @@ public class ARRAY_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
/** /**
* A Type Specific foreach function that reduces (un)boxing * A Type Specific foreach function that reduces (un)boxing
* *
* @implSpec * @implSpec
* <p>The default implementation behaves as if: * <p>The default implementation behaves as if:
* <pre>{@code * <pre>{@code
* for(int i = 0;i<size;i++) * for(int i = 0;i<size;i++)
* action.accept(data[i]); * action.accept(data[i]);
* }</pre> * }</pre>
* *
* @param action The action to be performed for each element * @param action The action to be performed for each element
* @throws NullPointerException if the specified action is null * @throws NullPointerException if the specified action is null
* @see Iterable#forEach(java.util.function.Consumer) * @see Iterable#forEach(java.util.function.Consumer)
*/ */
@Override @Override
public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) { public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) {
Objects.requireNonNull(action); Objects.requireNonNull(action);
@@ -593,6 +609,98 @@ public class ARRAY_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
action.accept(data[i]); action.accept(data[i]);
} }
@Override
public <E> void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
for(int i = 0;i<size;i++)
action.accept(input, data[i]);
}
@Override
public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(int i = 0;i<size;i++) {
if(filter.TEST_VALUE(data[i])) return true;
}
return false;
}
@Override
public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(int i = 0;i<size;i++) {
if(filter.TEST_VALUE(data[i])) return false;
}
return true;
}
@Override
public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(int i = 0;i<size;i++) {
if(!filter.TEST_VALUE(data[i])) return false;
}
return true;
}
@Override
public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(int i = 0;i<size;i++) {
if(filter.TEST_VALUE(data[i])) return data[i];
}
return EMPTY_VALUE;
}
#if !TYPE_OBJECT
@Override
public KEY_TYPE reduce(KEY_TYPE identity, UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
KEY_TYPE state = identity;
for(int i = 0;i<size;i++) {
state = operator.APPLY_VALUE(state, data[i]);
}
return state;
}
#else
@Override
public <KEY_SPECIAL_TYPE> KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction<KEY_SPECIAL_TYPE, KEY_TYPE, KEY_SPECIAL_TYPE> operator) {
Objects.requireNonNull(operator);
KEY_SPECIAL_TYPE state = identity;
for(int i = 0;i<size;i++) {
state = operator.APPLY_VALUE(state, data[i]);
}
return state;
}
#endif
@Override
public KEY_TYPE reduce(UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
KEY_TYPE state = EMPTY_VALUE;
boolean empty = true;
for(int i = 0;i<size;i++) {
if(empty) {
empty = false;
state = data[i];
continue;
}
state = operator.APPLY_VALUE(state, data[i]);
}
return state;
}
@Override
public int count(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
int result = 0;
for(int i = 0;i<size;i++) {
if(filter.TEST_VALUE(data[i])) result++;
}
return result;
}
/** /**
* A Type-Specific set function to reduce (un)boxing * A Type-Specific set function to reduce (un)boxing
* @param index the index of the element to set * @param index the index of the element to set
@@ -638,6 +746,7 @@ public class ARRAY_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
*/ */
@Override @Override
public void REPLACE(JAVA_UNARY_OPERATOR o) { public void REPLACE(JAVA_UNARY_OPERATOR o) {
Objects.requireNonNull(o);
for(int i = 0;i<size;i++) for(int i = 0;i<size;i++)
#if TYPE_BYTE || TYPE_SHORT || TYPE_CHAR || TYPE_FLOAT #if TYPE_BYTE || TYPE_SHORT || TYPE_CHAR || TYPE_FLOAT
data[i] = SanityChecks.SANITY_CAST(o.APPLY_CAST(data[i])); data[i] = SanityChecks.SANITY_CAST(o.APPLY_CAST(data[i]));
@@ -665,6 +774,17 @@ public class ARRAY_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
return old; return old;
} }
public KEY_TYPE swapRemove(int index) {
checkRange(index);
KEY_TYPE old = data[index];
size--;
data[index] = data[size];
#if TYPE_OBJECT
data[size] = null;
#endif
return old;
}
#if !TYPE_OBJECT #if !TYPE_OBJECT
/** /**
* A Type-Specific implementation of remove. This implementation iterates over the elements until it finds the element that is searched for or it runs out of elements. * A Type-Specific implementation of remove. This implementation iterates over the elements until it finds the element that is searched for or it runs out of elements.
@@ -680,6 +800,15 @@ public class ARRAY_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
return true; return true;
} }
#else
@Override
public boolean remove(Object type) {
int index = indexOf(type);
if(index == -1) return false;
REMOVE(index);
return true;
}
#endif #endif
/** /**
* A Type-Specific pop function to reduce (un)boxing * A Type-Specific pop function to reduce (un)boxing
@@ -687,7 +816,7 @@ public class ARRAY_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
* @throws IndexOutOfBoundsException if the index is out of range * @throws IndexOutOfBoundsException if the index is out of range
*/ */
@Override @Override
public KEY_TYPE POP() { public KEY_TYPE pop() {
return REMOVE(size() - 1); return REMOVE(size() - 1);
} }
@@ -697,7 +826,6 @@ public class ARRAY_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
* @param c the elements that should be removed * @param c the elements that should be removed
* @return true if the collection was modified * @return true if the collection was modified
* @throws NullPointerException if the collection is null * @throws NullPointerException if the collection is null
* @deprecated if the collection is type-specific
*/ */
@Override @Override
@Primitive @Primitive
@@ -722,7 +850,6 @@ public class ARRAY_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
* @param c the elements that should be kept. If empty, ARRAY_LIST#clear is called. * @param c the elements that should be kept. If empty, ARRAY_LIST#clear is called.
* @return true if the collection was modified * @return true if the collection was modified
* @throws NullPointerException if the collection is null * @throws NullPointerException if the collection is null
* @deprecated if the collection is type-specific
*/ */
@Override @Override
@Primitive @Primitive
@@ -749,7 +876,6 @@ public class ARRAY_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
* A optimized List#removeIf(Predicate) that more quickly removes elements from the list then the ArrayList implementation * A optimized List#removeIf(Predicate) that more quickly removes elements from the list then the ArrayList implementation
* @param filter the filter to remove elements * @param filter the filter to remove elements
* @return true if the list was modified * @return true if the list was modified
* @deprecated if Type-Specific, use #remIf instead
*/ */
@Override @Override
@Primitive @Primitive
@@ -790,6 +916,22 @@ public class ARRAY_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
return modified; return modified;
} }
@Override
public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c, CONSUMER KEY_GENERIC_TYPE r) {
if(c.isEmpty()) return false;
int j = 0;
for(int i = 0;i<size;i++) {
if(!c.contains(data[i])) data[j++] = data[i];
else r.accept(data[i]);
}
boolean modified = j != size;
#if TYPE_OBJECT
Arrays.fill(data, j, size, null);
#endif
size = j;
return modified;
}
/** /**
* A function to retain all elements that were provided in the other collection * A function to retain all elements that were provided in the other collection
* This function might delegate to a more appropriate function if necessary * This function might delegate to a more appropriate function if necessary
@@ -817,6 +959,27 @@ public class ARRAY_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
return modified; return modified;
} }
@Override
public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c, CONSUMER KEY_GENERIC_TYPE r) {
if(c.isEmpty()) {
boolean modifed = size > 0;
forEach(r);
clear();
return modifed;
}
int j = 0;
for(int i = 0;i<size;i++) {
if(c.contains(data[i])) data[j++] = data[i];
else r.accept(data[i]);
}
boolean modified = j != size;
#if TYPE_OBJECT
Arrays.fill(data, j, size, null);
#endif
size = j;
return modified;
}
#if PRIMITIVES #if PRIMITIVES
/** /**
* A optimized List#removeIf(Predicate) that more quickly removes elements from the list then the ArrayList implementation * A optimized List#removeIf(Predicate) that more quickly removes elements from the list then the ArrayList implementation
@@ -860,8 +1023,13 @@ public class ARRAY_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
public <E> E[] toArray(E[] a) { public <E> E[] toArray(E[] a) {
if(a == null) a = (E[])new Object[size]; if(a == null) a = (E[])new Object[size];
else if(a.length < size) a = (E[])ObjectArrays.newArray(a.getClass().getComponentType(), size); else if(a.length < size) a = (E[])ObjectArrays.newArray(a.getClass().getComponentType(), size);
#if TYPE_OBJECT
System.arraycopy(data, 0, a, 0, size);
#else
for(int i = 0;i<size;i++) for(int i = 0;i<size;i++)
a[i] = (E)KEY_TO_OBJ(data[i]); a[i] = (E)KEY_TO_OBJ(data[i]);
#endif
if (a.length > size) a[size] = null;
return a; return a;
} }
@@ -870,6 +1038,7 @@ public class ARRAY_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] a) { public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] a) {
if(a.length < size) a = new KEY_TYPE[size]; if(a.length < size) a = new KEY_TYPE[size];
System.arraycopy(data, 0, a, 0, size); System.arraycopy(data, 0, a, 0, size);
if (a.length > size) a[size] = EMPTY_KEY_VALUE;
return a; return a;
} }
@@ -921,6 +1090,21 @@ public class ARRAY_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
return true; return true;
} }
/**
* Trims the collection down to the requested size and clears all elements while doing so
* @param size the amount of elements that should be allowed
* @note this will enforce minimum size of the collection itself
*/
@Override
public void clearAndTrim(int size) {
if(data.length <= size) {
clear();
return;
}
data = size == 0 ? EMPTY_KEY_ARRAY : NEW_KEY_ARRAY(size);
this.size = size;
}
/** /**
* Increases the capacity of this implementation instance, if necessary, * Increases the capacity of this implementation instance, if necessary,
* to ensure that it can hold at least the number of elements specified by * to ensure that it can hold at least the number of elements specified by
@@ -933,9 +1117,17 @@ public class ARRAY_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
grow(size); grow(size);
} }
@Override
public ARRAY_LIST KEY_GENERIC_TYPE copy() {
ARRAY_LIST KEY_GENERIC_TYPE list = new ARRAY_LISTBRACES();
list.data = Arrays.copyOf(data, data.length);
list.size = size;
return list;
}
protected void grow(int capacity) { protected void grow(int capacity) {
if(capacity < data.length) return; if(capacity < data.length) return;
data = Arrays.copyOf(data, data == ARRAYS.EMPTY_ARRAY ? DEFAULT_ARRAY_SIZE : (int)Math.max(Math.min((long)data.length + (data.length >> 1), SanityChecks.MAX_ARRAY_SIZE), capacity)); data = Arrays.copyOf(data, data == ARRAYS.EMPTY_ARRAY ? Math.max(DEFAULT_ARRAY_SIZE, capacity) : (int)Math.max(Math.min((long)data.length + (data.length >> 1), SanityChecks.MAX_ARRAY_SIZE), capacity));
} }
protected void checkRange(int index) { protected void checkRange(int index) {
@@ -948,6 +1140,7 @@ public class ARRAY_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size); throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
} }
#if PRIMITIVES #if PRIMITIVES
/** /**
* Returns a Java-Type-Specific Stream to reduce boxing/unboxing. * Returns a Java-Type-Specific Stream to reduce boxing/unboxing.
@@ -0,0 +1,572 @@
package speiger.src.collections.PACKAGE.lists;
import java.util.Arrays;
#if TYPE_OBJECT
import java.util.Comparator;
#endif
import java.util.Collection;
import java.util.NoSuchElementException;
import java.util.Objects;
#if TYPE_OBJECT
import java.util.function.BiFunction;
import java.util.function.Consumer;
#endif
import java.util.function.Predicate;
import java.util.function.UnaryOperator;
#if PRIMITIVES
import java.util.function.JAVA_PREDICATE;
import java.util.function.JAVA_UNARY_OPERATOR;
#endif
import speiger.src.collections.PACKAGE.collections.COLLECTION;
#if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.functions.COMPARATOR;
import speiger.src.collections.PACKAGE.functions.CONSUMER;
import speiger.src.collections.PACKAGE.utils.ARRAYS;
#endif
import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER;
import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR;
import speiger.src.collections.objects.utils.ObjectArrays;
import speiger.src.collections.PACKAGE.utils.ITERATORS;
#if PRIMITIVES
import java.util.stream.JAVA_STREAM;
import java.util.stream.StreamSupport;
#endif
import speiger.src.collections.PACKAGE.collections.SPLIT_ITERATOR;
import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS;
import speiger.src.collections.utils.SanityChecks;
#if TYPE_OBJECT
/**
* A Type-Specific Immutable implementation of list that is written to reduce (un)boxing
*
* @Type(T)
*/
public class IMMUTABLE_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
#else
/**
* A Type-Specific Immutable implementation of list that is written to reduce (un)boxing
*/
public class IMMUTABLE_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
#endif
{
/** The backing array */
protected transient KEY_TYPE[] data;
/**
* Creates a new Immutable copy of the contents of the Collection.
* @param c the elements that should be added into the list
*/
@Primitive
public IMMUTABLE_LIST(Collection<? extends CLASS_TYPE> c) {
data = ARRAYS.pour(ITERATORS.wrap(c.iterator()));
}
/**
* Creates a new Immutable copy of the contents of the Collection.
* @param c the elements that should be added into the list
*/
public IMMUTABLE_LIST(COLLECTION KEY_GENERIC_TYPE c) {
data = ARRAYS.pour(c.iterator());
}
/**
* Creates a new Immutable copy of the contents of the List.
* @param l the elements that should be added into the list
*/
public IMMUTABLE_LIST(LIST KEY_GENERIC_TYPE l) {
KEY_TYPE[] temp = NEW_KEY_ARRAY(l.size());
l.getElements(0, temp, 0, l.size());
data = temp;
}
/**
* Creates a new Immutable copy of the contents of the Array.
* @param a the array that should be copied
*/
public IMMUTABLE_LIST(KEY_TYPE... a) {
this(a, 0, a.length);
}
/**
* Creates a new ImmutableList copy of the array with a custom length
* @param a the array that should be copied
* @param length the desired length that should be copied
*/
public IMMUTABLE_LIST(KEY_TYPE[] a, int length) {
this(a, 0, length);
}
/**
* Creates a new ImmutableList copy of the array with in the custom range.
* @param a the array that should be copied
* @param offset the starting offset of where the array should be copied from
* @param length the desired length that should be copied
* @throws IllegalStateException if offset is smaller then 0
* @throws IllegalStateException if the offset + length exceeds the array length
*/
public IMMUTABLE_LIST(KEY_TYPE[] a, int offset, int length) {
SanityChecks.checkArrayCapacity(a.length, offset, length);
data = Arrays.copyOfRange(a, offset, offset+length);
}
@Override
public boolean add(KEY_TYPE e) { throw new UnsupportedOperationException(); }
@Override
public void add(int index, KEY_TYPE e) { throw new UnsupportedOperationException(); }
@Override
@Primitive
public boolean addAll(int index, Collection<? extends CLASS_TYPE> c) { throw new UnsupportedOperationException(); }
@Override
public boolean addAll(int index, COLLECTION KEY_GENERIC_TYPE c) { throw new UnsupportedOperationException(); }
@Override
public boolean addAll(int index, LIST KEY_GENERIC_TYPE c) { throw new UnsupportedOperationException(); }
@Override
public boolean addAll(KEY_TYPE[] e, int offset, int length) { throw new UnsupportedOperationException(); }
@Override
public void addElements(int from, KEY_TYPE[] a, int offset, int length) { throw new UnsupportedOperationException(); }
@Override
public KEY_TYPE[] getElements(int from, KEY_TYPE[] a, int offset, int length) {
SanityChecks.checkArrayCapacity(data.length, offset, length);
System.arraycopy(data, from, a, offset, length);
return a;
}
@Override
public void removeElements(int from, int to) { throw new UnsupportedOperationException(); }
#if TYPE_OBJECT
@Override
public <K> K[] extractElements(int from, int to, Class<K> type) { throw new UnsupportedOperationException(); }
#else
@Override
public KEY_TYPE[] extractElements(int from, int to) { throw new UnsupportedOperationException(); }
#endif
/**
* A function to find if the Element is present in this list.
* @param o the element that is searched for
* @return if the element was found.
*/
@Override
@Primitive
public boolean contains(Object o) {
return indexOf(o) != -1;
}
/**
* A function to find the index of a given element
* @param o the element that is searched for
* @return the index of the element if found. (if not found then -1)
*/
@Override
@Primitive
public int indexOf(Object o) {
#if TYPE_OBJECT
if(o == null) {
for(int i = 0,m=data.length;i<m;i++)
if(data[i] == null) return i;
return -1;
}
#else
if(o == null) return -1;
#endif
for(int i = 0,m=data.length;i<m;i++) {
if(EQUALS_KEY_TYPE(data[i], o)) return i;
}
return -1;
}
/**
* A function to find the last index of a given element
* @param o the element that is searched for
* @return the last index of the element if found. (if not found then -1)
*/
@Override
@Primitive
public int lastIndexOf(Object o) {
#if TYPE_OBJECT
if(o == null) {
for(int i = data.length - 1;i>=0;i--)
if(data[i] == null) return i;
return -1;
}
#else
if(o == null) return -1;
#endif
for(int i = data.length - 1;i>=0;i--) {
if(EQUALS_KEY_TYPE(data[i], o)) return i;
}
return -1;
}
#if TYPE_OBJECT
@Override
public void sort(Comparator<? super CLASS_TYPE> c) { throw new UnsupportedOperationException(); }
@Override
public void unstableSort(Comparator<? super CLASS_TYPE> c) { throw new UnsupportedOperationException(); }
#else
/**
* A Type Specific implementation of the Collection#contains function.
* @param e the element that is searched for.
* @return if the element was found
*/
@Override
public boolean contains(KEY_TYPE e) {
return indexOf(e) != -1;
}
/**
* A Type-Specific function to find the index of a given element
* @param e the element that is searched for
* @return the index of the element if found. (if not found then -1)
*/
@Override
public int indexOf(KEY_TYPE e) {
for(int i = 0,m=data.length;i<m;i++) {
if(KEY_EQUALS(data[i], e)) return i;
}
return -1;
}
/**
* A Type-Specific function to find the last index of a given element
* @param e the element that is searched for
* @return the last index of the element if found. (if not found then -1)
*/
@Override
public int lastIndexOf(KEY_TYPE e) {
for(int i = data.length - 1;i>=0;i--) {
if(KEY_EQUALS(data[i], e)) return i;
}
return -1;
}
@Override
public void sort(COMPARATOR c) { throw new UnsupportedOperationException(); }
@Override
public void unstableSort(COMPARATOR c) { throw new UnsupportedOperationException(); }
#endif
/**
* A Type-Specific get function to reduce (un)boxing
* @param index the index of the element to fetch
* @return the value of the requested index
* @throws IndexOutOfBoundsException if the index is out of range
*/
@Override
public KEY_TYPE GET_KEY(int index) {
checkRange(index);
return data[index];
}
@Override
public IMMUTABLE_LIST KEY_GENERIC_TYPE copy() {
return new IMMUTABLE_LISTBRACES(Arrays.copyOf(data, data.length));
}
/**
* A Type Specific foreach function that reduces (un)boxing
*
* @implSpec
* <p>The default implementation behaves as if:
* <pre>{@code
* for(int i = 0;i<size;i++)
* action.accept(data[i]);
* }</pre>
*
* @param action The action to be performed for each element
* @throws NullPointerException if the specified action is null
* @see Iterable#forEach(java.util.function.Consumer)
*/
@Override
public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) {
Objects.requireNonNull(action);
for(int i = 0,m=data.length;i<m;i++)
action.accept(data[i]);
}
@Override
public <E> void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
for(int i = 0,m=data.length;i<m;i++)
action.accept(input, data[i]);
}
@Override
public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(int i = 0,m=data.length;i<m;i++) {
if(filter.TEST_VALUE(data[i])) return true;
}
return false;
}
@Override
public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(int i = 0,m=data.length;i<m;i++) {
if(filter.TEST_VALUE(data[i])) return false;
}
return true;
}
@Override
public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(int i = 0,m=data.length;i<m;i++) {
if(!filter.TEST_VALUE(data[i])) return false;
}
return true;
}
@Override
public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(int i = 0,m=data.length;i<m;i++) {
if(filter.TEST_VALUE(data[i])) return data[i];
}
return EMPTY_VALUE;
}
#if !TYPE_OBJECT
@Override
public KEY_TYPE reduce(KEY_TYPE identity, UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
KEY_TYPE state = identity;
for(int i = 0,m=data.length;i<m;i++) {
state = operator.APPLY_VALUE(state, data[i]);
}
return state;
}
#else
@Override
public <KEY_SPECIAL_TYPE> KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction<KEY_SPECIAL_TYPE, KEY_TYPE, KEY_SPECIAL_TYPE> operator) {
Objects.requireNonNull(operator);
KEY_SPECIAL_TYPE state = identity;
for(int i = 0,m=data.length;i<m;i++) {
state = operator.APPLY_VALUE(state, data[i]);
}
return state;
}
#endif
@Override
public KEY_TYPE reduce(UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
KEY_TYPE state = EMPTY_VALUE;
boolean empty = true;
for(int i = 0,m=data.length;i<m;i++) {
if(empty) {
empty = false;
state = data[i];
continue;
}
state = operator.APPLY_VALUE(state, data[i]);
}
return state;
}
@Override
public int count(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
int result = 0;
for(int i = 0,m=data.length;i<m;i++) {
if(filter.TEST_VALUE(data[i])) result++;
}
return result;
}
@Override
public LIST_ITERATOR KEY_GENERIC_TYPE listIterator(int index) {
if(index < 0 || index > size()) throw new IndexOutOfBoundsException();
return new LIST_ITER(index);
}
@Override
public KEY_TYPE set(int index, KEY_TYPE e) { throw new UnsupportedOperationException(); }
@Override
@Primitive
public void replaceAll(UnaryOperator<CLASS_TYPE> o) { throw new UnsupportedOperationException(); }
#if PRIMITIVES
@Override
public void REPLACE(JAVA_UNARY_OPERATOR o) { throw new UnsupportedOperationException(); }
#endif
@Override
public KEY_TYPE REMOVE(int index) { throw new UnsupportedOperationException(); }
@Override
public KEY_TYPE swapRemove(int index) { throw new UnsupportedOperationException(); }
#if !TYPE_OBJECT
@Override
public boolean REMOVE_KEY(KEY_TYPE type) { throw new UnsupportedOperationException(); }
#endif
@Override
@Primitive
public boolean removeAll(Collection<?> c) { throw new UnsupportedOperationException(); }
@Override
@Primitive
public boolean retainAll(Collection<?> c) { throw new UnsupportedOperationException(); }
@Override
@Primitive
public boolean removeIf(Predicate<? super CLASS_TYPE> filter) { throw new UnsupportedOperationException(); }
@Override
public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c) { throw new UnsupportedOperationException(); }
@Override
public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c) { throw new UnsupportedOperationException(); }
@Override
public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c, CONSUMER KEY_GENERIC_TYPE r) { throw new UnsupportedOperationException(); }
@Override
public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c, CONSUMER KEY_GENERIC_TYPE r) { throw new UnsupportedOperationException(); }
#if PRIMITIVES
@Override
public boolean remIf(JAVA_PREDICATE filter) { throw new UnsupportedOperationException(); }
#endif
/**
* A toArray implementation that ensures the Array itself is a Object.
* @return a Array of the elements in the list
*/
@Override
@Primitive
public Object[] toArray() {
Object[] obj = new Object[data.length];
for(int i = 0,m=data.length;i<m;i++)
obj[i] = KEY_TO_OBJ(data[i]);
return obj;
}
/**
* A toArray implementation that ensures the Array itself is a Object.
* @param a original array. If null a Object array with the right size is created. If to small the Array of the same type is created with the right size
* @return a Array of the elements in the list
*/
@Override
@Primitive
public <E> E[] toArray(E[] a) {
if(a == null) a = (E[])new Object[data.length];
else if(a.length < data.length) a = (E[])ObjectArrays.newArray(a.getClass().getComponentType(), data.length);
for(int i = 0,m=data.length;i<m;i++)
a[i] = (E)KEY_TO_OBJ(data[i]);
if (a.length > data.length) a[data.length] = null;
return a;
}
#if !TYPE_OBJECT
@Override
public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] a) {
if(a.length < data.length) a = new KEY_TYPE[data.length];
System.arraycopy(data, 0, a, 0, data.length);
if (a.length > data.length) a[data.length] = EMPTY_KEY_VALUE;
return a;
}
#endif
/**
* A function to return the size of the list
* @return the size of elements in the list
*/
@Override
public int size() {
return data.length;
}
@Override
public void size(int size) { throw new UnsupportedOperationException(); }
@Override
public void clear() { throw new UnsupportedOperationException(); }
protected void checkRange(int index) {
if (index < 0 || index >= data.length)
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + data.length);
}
#if PRIMITIVES
/**
* Returns a Java-Type-Specific Stream to reduce boxing/unboxing.
* @return a Stream of the closest java type
* @note characteristics are ordered, sized, subsized
*/
@Override
public JAVA_STREAM primitiveStream() { return StreamSupport.NEW_STREAM(SPLIT_ITERATORS.createArrayJavaSplititerator(data, data.length, 16464), false); }
#endif
/**
* A Type Specific Type Splititerator to reduce boxing/unboxing
* @return type specific splititerator
* @note characteristics are ordered, sized, subsized
*/
@Override
public SPLIT_ITERATOR KEY_GENERIC_TYPE spliterator() { return SPLIT_ITERATORS.createArraySplititerator(data, data.length, 16464); }
private class LIST_ITER implements LIST_ITERATOR KEY_GENERIC_TYPE {
int index;
LIST_ITER(int index) {
this.index = index;
}
@Override
public boolean hasNext() {
return index < size();
}
@Override
public KEY_TYPE NEXT() {
if(!hasNext()) throw new NoSuchElementException();
return GET_KEY(index++);
}
@Override
public boolean hasPrevious() {
return index > 0;
}
@Override
public KEY_TYPE PREVIOUS() {
if(!hasPrevious()) throw new NoSuchElementException();
return GET_KEY(--index);
}
@Override
public int nextIndex() {
return index;
}
@Override
public int previousIndex() {
return index-1;
}
@Override
public void remove() { throw new UnsupportedOperationException(); }
@Override
public void set(KEY_TYPE e) { throw new UnsupportedOperationException(); }
@Override
public void add(KEY_TYPE e) { throw new UnsupportedOperationException(); }
@Override
public int skip(int amount) {
if(amount < 0) throw new IllegalStateException("Negative Numbers are not allowed");
int steps = Math.min(amount, (size() - 1) - index);
index += steps;
return steps;
}
@Override
public int back(int amount) {
if(amount < 0) throw new IllegalStateException("Negative Numbers are not allowed");
int steps = Math.min(amount, index);
index -= steps;
return steps;
}
}
}
@@ -1,5 +1,8 @@
package speiger.src.collections.PACKAGE.lists; package speiger.src.collections.PACKAGE.lists;
#if PRIMITIVES
import java.nio.JAVA_BUFFER;
#endif
import java.util.List; import java.util.List;
#if !TYPE_OBJECT && !TYPE_BOOLEAN #if !TYPE_OBJECT && !TYPE_BOOLEAN
import java.util.Objects; import java.util.Objects;
@@ -17,6 +20,7 @@ import speiger.src.collections.PACKAGE.collections.SPLIT_ITERATOR;
import speiger.src.collections.PACKAGE.functions.COMPARATOR; import speiger.src.collections.PACKAGE.functions.COMPARATOR;
#endif #endif
import speiger.src.collections.PACKAGE.utils.ARRAYS; import speiger.src.collections.PACKAGE.utils.ARRAYS;
import speiger.src.collections.PACKAGE.utils.LISTS;
import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS; import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS;
#if TYPE_BYTE || TYPE_SHORT || TYPE_CHAR || TYPE_FLOAT #if TYPE_BYTE || TYPE_SHORT || TYPE_CHAR || TYPE_FLOAT
import speiger.src.collections.utils.SanityChecks; import speiger.src.collections.utils.SanityChecks;
@@ -41,16 +45,36 @@ public interface LIST KEY_GENERIC_TYPE extends COLLECTION KEY_GENERIC_TYPE, List
/** /**
* A Type-Specific add Function to reduce (un)boxing * A Type-Specific add Function to reduce (un)boxing
* @param e the element to add * @param e the element to add
* @param index index at which the specified element is to be inserted * @param index index at which the specified element is to be inserted
* @see List#add(int, Object) * @see List#add(int, Object)
*/ */
public void add(int index, KEY_TYPE e); public void add(int index, KEY_TYPE e);
#endif #endif
/**
* A Helper function that will only add elements if it is not present.
* @param e the element to add
* @return true if the list was modified
*/
public default boolean addIfAbsent(KEY_TYPE e) {
if(indexOf(e) == -1) return add(e);
return false;
}
/**
* A Helper function that will only add elements if it is present.
* @param e the element to add
* @return true if the list was modified
*/
public default boolean addIfPresent(KEY_TYPE e) {
if(indexOf(e) != -1) return add(e);
return false;
}
/** /**
* A Type-Specific addAll Function to reduce (un)boxing * A Type-Specific addAll Function to reduce (un)boxing
* @param c the elements that need to be added * @param c the elements that need to be added
* @param index index at which the specified elements is to be inserted * @param index index at which the specified elements is to be inserted
* @return true if the list was modified * @return true if the list was modified
* @see java.util.List#addAll(int, java.util.Collection) * @see java.util.List#addAll(int, java.util.Collection)
*/ */
@@ -66,7 +90,7 @@ public interface LIST KEY_GENERIC_TYPE extends COLLECTION KEY_GENERIC_TYPE, List
/** /**
* A Type-Specific and optimized addAll function that allows a faster transfer of elements * A Type-Specific and optimized addAll function that allows a faster transfer of elements
* @param c the elements that need to be added * @param c the elements that need to be added
* @param index index at which the specified elements is to be inserted * @param index index at which the specified elements is to be inserted
* @return true if the list was modified * @return true if the list was modified
*/ */
public boolean addAll(int index, LIST KEY_GENERIC_TYPE c); public boolean addAll(int index, LIST KEY_GENERIC_TYPE c);
@@ -83,19 +107,19 @@ public interface LIST KEY_GENERIC_TYPE extends COLLECTION KEY_GENERIC_TYPE, List
/** /**
* A Type-Specific set function to reduce (un)boxing * A Type-Specific set function to reduce (un)boxing
* @param index index of the element to replace * @param index index of the element to replace
* @param e element to be stored at the specified position * @param e element to be stored at the specified position
* @return the element previously at the specified position * @return the element previously at the specified position
* @throws IndexOutOfBoundsException if the index is not within the list range * @throws IndexOutOfBoundsException if the index is not within the list range
* @see List#set(int, Object) * @see List#set(int, Object)
*/ */
public KEY_TYPE set(int index, KEY_TYPE e); public KEY_TYPE set(int index, KEY_TYPE e);
/** /**
* A Type-Specific remove function to reduce (un)boxing * A Type-Specific remove function to reduce (un)boxing
* @param index the index of the element to be removed * @param index the index of the element to be removed
* @return the element previously at the specified position * @return the element previously at the specified position
* @see List#remove(int) * @see List#remove(int)
*/ */
public KEY_TYPE REMOVE(int index); public KEY_TYPE REMOVE(int index);
@@ -122,11 +146,11 @@ public interface LIST KEY_GENERIC_TYPE extends COLLECTION KEY_GENERIC_TYPE, List
* @throws NullPointerException if o is null * @throws NullPointerException if o is null
*/ */
public default void REPLACE(JAVA_UNARY_OPERATOR o) { public default void REPLACE(JAVA_UNARY_OPERATOR o) {
Objects.requireNonNull(o); Objects.requireNonNull(o);
LIST_ITERATOR iter = listIterator(); LIST_ITERATOR iter = listIterator();
while (iter.hasNext()) while (iter.hasNext())
#if TYPE_BYTE || TYPE_SHORT || TYPE_CHAR || TYPE_FLOAT #if TYPE_BYTE || TYPE_SHORT || TYPE_CHAR || TYPE_FLOAT
iter.set(SanityChecks.SANITY_CAST(o.APPLY_CAST(iter.NEXT()))); iter.set(SanityChecks.SANITY_CAST(o.APPLY_CAST(iter.NEXT())));
#else #else
iter.set(o.APPLY(iter.NEXT())); iter.set(o.APPLY(iter.NEXT()));
#endif #endif
@@ -141,18 +165,18 @@ public interface LIST KEY_GENERIC_TYPE extends COLLECTION KEY_GENERIC_TYPE, List
*/ */
@Override @Override
public default void replaceAll(UnaryOperator<CLASS_TYPE> o) { public default void replaceAll(UnaryOperator<CLASS_TYPE> o) {
Objects.requireNonNull(o); Objects.requireNonNull(o);
LIST_ITERATOR KEY_GENERIC_TYPE iter = listIterator(); LIST_ITERATOR KEY_GENERIC_TYPE iter = listIterator();
while (iter.hasNext()) iter.set(o.apply(iter.NEXT())); while (iter.hasNext()) iter.set(o.apply(iter.NEXT()));
} }
#endif #endif
/** /**
* A function to fast add elements to the list * A function to fast add elements to the list
* @param a the elements that should be added * @param a the elements that should be added
* @throws IndexOutOfBoundsException if from is outside of the lists range * @throws IndexOutOfBoundsException if from is outside of the lists range
*/ */
public default void addElements(KEY_TYPE... a) { addElements(0, a, 0, a.length); } public default void addElements(KEY_TYPE... a) { addElements(size(), a, 0, a.length); }
/** /**
* A function to fast add elements to the list * A function to fast add elements to the list
@@ -169,7 +193,6 @@ public interface LIST KEY_GENERIC_TYPE extends COLLECTION KEY_GENERIC_TYPE, List
* @param offset the start index of the array should be read from * @param offset the start index of the array should be read from
* @param length how many elements should be read from * @param length how many elements should be read from
* @throws IndexOutOfBoundsException if from is outside of the lists range * @throws IndexOutOfBoundsException if from is outside of the lists range
* @throws IllegalStateException if offset or length are smaller then 0 or exceed the array length
*/ */
public void addElements(int from, KEY_TYPE[] a, int offset, int length); public void addElements(int from, KEY_TYPE[] a, int offset, int length);
@@ -204,6 +227,22 @@ public interface LIST KEY_GENERIC_TYPE extends COLLECTION KEY_GENERIC_TYPE, List
*/ */
public void removeElements(int from, int to); public void removeElements(int from, int to);
/**
* A Highly Optimized remove function that removes the desired element.
* But instead of shifting the elements to the left it moves the last element to the removed space.
* @param index the index of the element to be removed
* @return the element previously at the specified position
*/
public KEY_TYPE swapRemove(int index);
/**
* A Highly Optimized remove function that removes the desired element.
* But instead of shifting the elements to the left it moves the last element to the removed space.
* @param e the element that should be removed
* @return true if the element was removed
*/
public boolean REMOVE_SWAP(KEY_TYPE e);
#if TYPE_OBJECT #if TYPE_OBJECT
/** /**
* A function to fast extract elements out of the list, this removes the elements that were fetched. * A function to fast extract elements out of the list, this removes the elements that were fetched.
@@ -223,12 +262,12 @@ public interface LIST KEY_GENERIC_TYPE extends COLLECTION KEY_GENERIC_TYPE, List
public default void sort(Comparator<? super CLASS_TYPE> c) { public default void sort(Comparator<? super CLASS_TYPE> c) {
KEY_TYPE[] array = (KEY_TYPE[])TO_ARRAY(); KEY_TYPE[] array = (KEY_TYPE[])TO_ARRAY();
if(c != null) ARRAYS.stableSort(array, c); if(c != null) ARRAYS.stableSort(array, c);
else ARRAYS.stableSort((Comparable[])array); else ARRAYS.stableSort(array);
LIST_ITERATOR KEY_GENERIC_TYPE iter = listIterator(); LIST_ITERATOR KEY_GENERIC_TYPE iter = listIterator();
for (int i = 0,m=size();i<m && iter.hasNext();i++) { for (int i = 0,m=size();i<m && iter.hasNext();i++) {
iter.NEXT(); iter.NEXT();
iter.set(array[i]); iter.set(array[i]);
} }
} }
/** /**
@@ -239,12 +278,12 @@ public interface LIST KEY_GENERIC_TYPE extends COLLECTION KEY_GENERIC_TYPE, List
public default void unstableSort(Comparator<? super CLASS_TYPE> c) { public default void unstableSort(Comparator<? super CLASS_TYPE> c) {
KEY_TYPE[] array = (KEY_TYPE[])TO_ARRAY(); KEY_TYPE[] array = (KEY_TYPE[])TO_ARRAY();
if(c != null) ARRAYS.unstableSort(array, c); if(c != null) ARRAYS.unstableSort(array, c);
else ARRAYS.unstableSort((Comparable[])array); else ARRAYS.unstableSort(array);
LIST_ITERATOR KEY_GENERIC_TYPE iter = listIterator(); LIST_ITERATOR KEY_GENERIC_TYPE iter = listIterator();
for (int i = 0,m=size();i<m && iter.hasNext();i++) { for (int i = 0,m=size();i<m && iter.hasNext();i++) {
iter.NEXT(); iter.NEXT();
iter.set(array[i]); iter.set(array[i]);
} }
} }
#else #else
@@ -256,6 +295,14 @@ public interface LIST KEY_GENERIC_TYPE extends COLLECTION KEY_GENERIC_TYPE, List
*/ */
public KEY_TYPE[] extractElements(int from, int to); public KEY_TYPE[] extractElements(int from, int to);
#if PRIMITIVES
/**
* Helper function that allows to fastFill a buffer reducing the duplication requirement
* @param buffer where the data should be stored in.
*/
public default void fillBuffer(JAVA_BUFFER buffer) { buffer.put(TO_ARRAY()); }
#endif
/** {@inheritDoc} /** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function. * <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead. * @deprecated Please use the corresponding type-specific function instead.
@@ -303,11 +350,11 @@ public interface LIST KEY_GENERIC_TYPE extends COLLECTION KEY_GENERIC_TYPE, List
KEY_TYPE[] array = TO_ARRAY(); KEY_TYPE[] array = TO_ARRAY();
if(c != null) ARRAYS.unstableSort(array, c); if(c != null) ARRAYS.unstableSort(array, c);
else ARRAYS.unstableSort(array); else ARRAYS.unstableSort(array);
LIST_ITERATOR KEY_GENERIC_TYPE iter = listIterator(); LIST_ITERATOR KEY_GENERIC_TYPE iter = listIterator();
for (int i = 0,m=size();i<m && iter.hasNext();i++) { for (int i = 0,m=size();i<m && iter.hasNext();i++) {
iter.NEXT(); iter.NEXT();
iter.set(array[i]); iter.set(array[i]);
} }
} }
#endif #endif
@@ -332,6 +379,28 @@ public interface LIST KEY_GENERIC_TYPE extends COLLECTION KEY_GENERIC_TYPE, List
@Override @Override
public LIST KEY_GENERIC_TYPE subList(int from, int to); public LIST KEY_GENERIC_TYPE subList(int from, int to);
/**
* Creates a Wrapped List that is Synchronized
* @return a new List that is synchronized
* @see LISTS#synchronize
*/
public default LIST KEY_GENERIC_TYPE synchronize() { return LISTS.synchronize(this); }
/**
* Creates a Wrapped List that is Synchronized
* @param mutex is the controller of the synchronization block
* @return a new List Wrapper that is synchronized
* @see LISTS#synchronize
*/
public default LIST KEY_GENERIC_TYPE synchronize(Object mutex) { return LISTS.synchronize(this, mutex); }
/**
* Creates a Wrapped List that is unmodifiable
* @return a new List Wrapper that is unmodifiable
* @see LISTS#unmodifiable
*/
public default LIST KEY_GENERIC_TYPE unmodifiable() { return LISTS.unmodifiable(this); }
/** /**
* A function to ensure the elements are within the requested size. * A function to ensure the elements are within the requested size.
* If smaller then the stored elements they get removed as needed. * If smaller then the stored elements they get removed as needed.
@@ -340,6 +409,8 @@ public interface LIST KEY_GENERIC_TYPE extends COLLECTION KEY_GENERIC_TYPE, List
*/ */
public void size(int size); public void size(int size);
@Override
public LIST KEY_GENERIC_TYPE copy();
#if !TYPE_OBJECT #if !TYPE_OBJECT
/** {@inheritDoc} /** {@inheritDoc}
@@ -26,9 +26,9 @@ public interface LIST_ITERATOR KEY_GENERIC_TYPE extends ListIterator<CLASS_TYPE>
public void add(KEY_TYPE e); public void add(KEY_TYPE e);
/** {@inheritDoc} /** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function. * <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead. * @deprecated Please use the corresponding type-specific function instead.
*/ */
@Override @Override
@Deprecated @Deprecated
public default CLASS_TYPE previous() { public default CLASS_TYPE previous() {
@@ -36,9 +36,9 @@ public interface LIST_ITERATOR KEY_GENERIC_TYPE extends ListIterator<CLASS_TYPE>
} }
/** {@inheritDoc} /** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function. * <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead. * @deprecated Please use the corresponding type-specific function instead.
*/ */
@Override @Override
@Deprecated @Deprecated
public default CLASS_TYPE next() { public default CLASS_TYPE next() {
@@ -46,9 +46,9 @@ public interface LIST_ITERATOR KEY_GENERIC_TYPE extends ListIterator<CLASS_TYPE>
} }
/** {@inheritDoc} /** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function. * <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead. * @deprecated Please use the corresponding type-specific function instead.
*/ */
@Override @Override
@Deprecated @Deprecated
public default void set(CLASS_TYPE e) { public default void set(CLASS_TYPE e) {
@@ -56,9 +56,9 @@ public interface LIST_ITERATOR KEY_GENERIC_TYPE extends ListIterator<CLASS_TYPE>
} }
/** {@inheritDoc} /** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function. * <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead. * @deprecated Please use the corresponding type-specific function instead.
*/ */
@Override @Override
@Deprecated @Deprecated
public default void add(CLASS_TYPE e) { public default void add(CLASS_TYPE e) {
@@ -18,12 +18,14 @@ import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_COLLECTION;
import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ITERATOR; import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ITERATOR;
import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_UNARY_OPERATOR; import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_UNARY_OPERATOR;
#endif #endif
import speiger.src.collections.VALUE_PACKAGE.functions.VALUE_SUPPLIER;
#if !TYPE_OBJECT && !VALUE_OBJECT #if !TYPE_OBJECT && !VALUE_OBJECT
import speiger.src.collections.objects.collections.ObjectIterator; import speiger.src.collections.objects.collections.ObjectIterator;
#endif #endif
#if !TYPE_OBJECT #if !TYPE_OBJECT
import speiger.src.collections.objects.sets.ObjectSet; import speiger.src.collections.objects.sets.ObjectSet;
#endif #endif
import speiger.src.collections.utils.SanityChecks;
/** /**
* A Base Implementation of a Type Specific Map to reduce boxing/unboxing * A Base Implementation of a Type Specific Map to reduce boxing/unboxing
@@ -45,6 +47,27 @@ public abstract class ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE extends AbstractMap<CL
return this; return this;
} }
@Override
public MAP KEY_VALUE_GENERIC_TYPE copy() {
throw new UnsupportedOperationException();
}
#if !TYPE_OBJECT || !VALUE_OBJECT
@Override
@Deprecated
public CLASS_VALUE_TYPE put(CLASS_TYPE key, CLASS_VALUE_TYPE value) {
return VALUE_TO_OBJ(put(OBJ_TO_KEY(key), OBJ_TO_VALUE(value)));
}
#endif
#if VALUE_PRIMITIVES
@Override
public void addToAll(MAP KEY_VALUE_GENERIC_TYPE m) {
for(MAP.Entry KEY_VALUE_GENERIC_TYPE entry : MAPS.fastIterable(m))
addTo(entry.ENTRY_KEY(), entry.ENTRY_VALUE());
}
#endif
@Override @Override
public void putAll(MAP KEY_VALUE_GENERIC_TYPE m) { public void putAll(MAP KEY_VALUE_GENERIC_TYPE m) {
for(ObjectIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> iter = MAPS.fastIterator(m);iter.hasNext();) { for(ObjectIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> iter = MAPS.fastIterator(m);iter.hasNext();) {
@@ -60,6 +83,28 @@ public abstract class ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE extends AbstractMap<CL
else super.putAll(m); else super.putAll(m);
} }
@Override
public void putAll(KEY_TYPE[] keys, VALUE_TYPE[] values, int offset, int size) {
SanityChecks.checkArrayCapacity(keys.length, offset, size);
SanityChecks.checkArrayCapacity(values.length, offset, size);
for(int i = 0;i<size;i++) put(keys[i], values[i]);
}
#if !TYPE_OBJECT || !VALUE_OBJECT
@Override
public void putAll(CLASS_TYPE[] keys, CLASS_VALUE_TYPE[] values, int offset, int size) {
SanityChecks.checkArrayCapacity(keys.length, offset, size);
SanityChecks.checkArrayCapacity(values.length, offset, size);
for(int i = 0;i<size;i++) put(keys[i], values[i]);
}
#endif
@Override
public void putAllIfAbsent(MAP KEY_VALUE_GENERIC_TYPE m) {
for(MAP.Entry KEY_VALUE_GENERIC_TYPE entry : MAPS.fastIterable(m))
putIfAbsent(entry.ENTRY_KEY(), entry.ENTRY_VALUE());
}
#if TYPE_OBJECT #if TYPE_OBJECT
@Override @Override
@@ -98,20 +143,26 @@ public abstract class ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE extends AbstractMap<CL
@Override @Override
public boolean replace(KEY_TYPE key, VALUE_TYPE oldValue, VALUE_TYPE newValue) { public boolean replace(KEY_TYPE key, VALUE_TYPE oldValue, VALUE_TYPE newValue) {
VALUE_TYPE curValue = GET_VALUE(key); VALUE_TYPE curValue = GET_VALUE(key);
if (VALUE_EQUALS_NOT(curValue, oldValue) || (VALUE_EQUALS(curValue, getDefaultReturnValue()) && !containsKey(key))) { if (VALUE_EQUALS_NOT(curValue, oldValue) || (VALUE_EQUALS(curValue, getDefaultReturnValue()) && !containsKey(key))) {
return false; return false;
} }
put(key, newValue); put(key, newValue);
return true; return true;
} }
@Override @Override
public VALUE_TYPE replace(KEY_TYPE key, VALUE_TYPE value) { public VALUE_TYPE replace(KEY_TYPE key, VALUE_TYPE value) {
VALUE_TYPE curValue; VALUE_TYPE curValue;
if (VALUE_EQUALS_NOT((curValue = GET_VALUE(key)), getDefaultReturnValue()) || containsKey(key)) { if (VALUE_EQUALS_NOT((curValue = GET_VALUE(key)), getDefaultReturnValue()) || containsKey(key)) {
curValue = put(key, value); curValue = put(key, value);
} }
return curValue; return curValue;
}
@Override
public void REPLACE_VALUES(MAP KEY_VALUE_GENERIC_TYPE m) {
for(MAP.Entry KEY_VALUE_GENERIC_TYPE entry : MAPS.fastIterable(m))
replace(entry.ENTRY_KEY(), entry.ENTRY_VALUE());
} }
@Override @Override
@@ -125,59 +176,85 @@ public abstract class ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE extends AbstractMap<CL
@Override @Override
public VALUE_TYPE COMPUTE(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { public VALUE_TYPE COMPUTE(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) {
Objects.requireNonNull(mappingFunction); Objects.requireNonNull(mappingFunction);
VALUE_TYPE value = GET_VALUE(key); VALUE_TYPE value = GET_VALUE(key);
VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, value); VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, value);
if(VALUE_EQUALS(newValue, getDefaultReturnValue())) { if(VALUE_EQUALS(newValue, getDefaultReturnValue())) {
if(VALUE_EQUALS_NOT(value, getDefaultReturnValue()) || containsKey(key)) { if(VALUE_EQUALS_NOT(value, getDefaultReturnValue()) || containsKey(key)) {
remove(key); remove(key);
return getDefaultReturnValue(); return getDefaultReturnValue();
} }
return getDefaultReturnValue(); return getDefaultReturnValue();
} }
put(key, newValue); put(key, newValue);
return newValue; return newValue;
} }
@Override @Override
public VALUE_TYPE COMPUTE_IF_ABSENT(KEY_TYPE key, FUNCTION KEY_VALUE_GENERIC_TYPE mappingFunction) { public VALUE_TYPE COMPUTE_IF_ABSENT(KEY_TYPE key, FUNCTION KEY_VALUE_GENERIC_TYPE mappingFunction) {
Objects.requireNonNull(mappingFunction); Objects.requireNonNull(mappingFunction);
VALUE_TYPE value; VALUE_TYPE value;
if((value = GET_VALUE(key)) == getDefaultReturnValue() || !containsKey(key)) { if((value = GET_VALUE(key)) == getDefaultReturnValue() || !containsKey(key)) {
VALUE_TYPE newValue = mappingFunction.GET_VALUE(key); VALUE_TYPE newValue = mappingFunction.GET_VALUE(key);
if(VALUE_EQUALS_NOT(newValue, getDefaultReturnValue())) { if(VALUE_EQUALS_NOT(newValue, getDefaultReturnValue())) {
put(key, newValue); put(key, newValue);
return newValue; return newValue;
} }
} }
return value;
}
@Override
public VALUE_TYPE SUPPLY_IF_ABSENT(KEY_TYPE key, VALUE_SUPPLIER VALUE_GENERIC_TYPE valueProvider) {
Objects.requireNonNull(valueProvider);
VALUE_TYPE value;
if((value = GET_VALUE(key)) == getDefaultReturnValue() || !containsKey(key)) {
VALUE_TYPE newValue = valueProvider.VALUE_GET_KEY();
if(VALUE_EQUALS_NOT(newValue, getDefaultReturnValue())) {
put(key, newValue);
return newValue;
}
}
return value; return value;
} }
@Override @Override
public VALUE_TYPE COMPUTE_IF_PRESENT(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { public VALUE_TYPE COMPUTE_IF_PRESENT(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) {
Objects.requireNonNull(mappingFunction); Objects.requireNonNull(mappingFunction);
VALUE_TYPE value; VALUE_TYPE value;
if(VALUE_EQUALS_NOT((value = GET_VALUE(key)), getDefaultReturnValue()) || containsKey(key)) { if(VALUE_EQUALS_NOT((value = GET_VALUE(key)), getDefaultReturnValue()) || containsKey(key)) {
VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, value); VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, value);
if(VALUE_EQUALS_NOT(newValue, getDefaultReturnValue())) { if(VALUE_EQUALS_NOT(newValue, getDefaultReturnValue())) {
put(key, newValue); put(key, newValue);
return newValue; return newValue;
} }
remove(key); remove(key);
} }
return getDefaultReturnValue(); return getDefaultReturnValue();
} }
@Override @Override
public VALUE_TYPE MERGE(KEY_TYPE key, VALUE_TYPE value, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) { public VALUE_TYPE MERGE(KEY_TYPE key, VALUE_TYPE value, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) {
Objects.requireNonNull(mappingFunction); Objects.requireNonNull(mappingFunction);
VALUE_TYPE oldValue = GET_VALUE(key); VALUE_TYPE oldValue = GET_VALUE(key);
VALUE_TYPE newValue = VALUE_EQUALS(oldValue, getDefaultReturnValue()) ? value : mappingFunction.APPLY_VALUE(oldValue, value); VALUE_TYPE newValue = VALUE_EQUALS(oldValue, getDefaultReturnValue()) ? value : mappingFunction.APPLY_VALUE(oldValue, value);
if(VALUE_EQUALS(newValue, getDefaultReturnValue())) remove(key); if(VALUE_EQUALS(newValue, getDefaultReturnValue())) remove(key);
else put(key, newValue); else put(key, newValue);
return newValue; return newValue;
} }
@Override
public void BULK_MERGE(MAP KEY_VALUE_GENERIC_TYPE m, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) {
Objects.requireNonNull(mappingFunction);
for(MAP.Entry KEY_VALUE_GENERIC_TYPE entry : MAPS.fastIterable(m)) {
KEY_TYPE key = entry.ENTRY_KEY();
VALUE_TYPE oldValue = GET_VALUE(key);
VALUE_TYPE newValue = VALUE_EQUALS(oldValue, getDefaultReturnValue()) ? entry.ENTRY_VALUE() : mappingFunction.APPLY_VALUE(oldValue, entry.ENTRY_VALUE());
if(VALUE_EQUALS(newValue, getDefaultReturnValue())) remove(key);
else put(key, newValue);
}
}
#if TYPE_OBJECT #if TYPE_OBJECT
@Override @Override
public CLASS_VALUE_TYPE get(Object key) { public CLASS_VALUE_TYPE get(Object key) {
@@ -427,7 +504,7 @@ public abstract class ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE extends AbstractMap<CL
@Override @Override
public String toString() { public String toString() {
return KEY_TO_STRING(key) + "->" + VALUE_TO_STRING(value); return KEY_TO_STRING(key) + "=" + VALUE_TO_STRING(value);
} }
} }
} }
@@ -1,16 +1,24 @@
package speiger.src.collections.PACKAGE.maps.impl.customHash; package speiger.src.collections.PACKAGE.maps.impl.customHash;
import java.util.Arrays;
import java.util.Comparator; import java.util.Comparator;
import java.util.Map; import java.util.Map;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.function.BiFunction;
import java.util.Objects;
import speiger.src.collections.PACKAGE.collections.BI_ITERATOR; import speiger.src.collections.PACKAGE.collections.BI_ITERATOR;
#if !TYPE_OBJECT #if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.functions.COMPARATOR; import speiger.src.collections.PACKAGE.functions.COMPARATOR;
import speiger.src.collections.PACKAGE.functions.CONSUMER; import speiger.src.collections.PACKAGE.functions.CONSUMER;
import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER;
#endif
#if !TYPE_OBJECT || VALUE_BOOLEAN
import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
#endif #endif
import speiger.src.collections.PACKAGE.functions.consumer.BI_CONSUMER; import speiger.src.collections.PACKAGE.functions.consumer.BI_CONSUMER;
import speiger.src.collections.PACKAGE.functions.function.SINGLE_UNARY_OPERATOR;
import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR; import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR;
import speiger.src.collections.PACKAGE.maps.interfaces.MAP; import speiger.src.collections.PACKAGE.maps.interfaces.MAP;
import speiger.src.collections.PACKAGE.maps.interfaces.SORTED_MAP; import speiger.src.collections.PACKAGE.maps.interfaces.SORTED_MAP;
@@ -21,11 +29,33 @@ import speiger.src.collections.PACKAGE.utils.STRATEGY;
import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ABSTRACT_COLLECTION; import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ABSTRACT_COLLECTION;
import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_COLLECTION; import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_COLLECTION;
import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ITERATOR; import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ITERATOR;
#if !SAME_TYPE
import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_UNARY_OPERATOR;
#endif
#if !VALUE_OBJECT && !SAME_TYPE #if !VALUE_OBJECT && !SAME_TYPE
import speiger.src.collections.VALUE_PACKAGE.functions.VALUE_CONSUMER; import speiger.src.collections.VALUE_PACKAGE.functions.VALUE_CONSUMER;
import speiger.src.collections.VALUE_PACKAGE.lists.VALUE_LIST_ITERATOR; import speiger.src.collections.VALUE_PACKAGE.lists.VALUE_LIST_ITERATOR;
#endif #endif
#if !TYPE_OBJECT && !VALUE_OBJECT || !VALUE_OBJECT
import speiger.src.collections.objects.functions.consumer.ObjectObjectConsumer;
#endif
#if !TYPE_OBJECT || !VALUE_BOOLEAN
#if !VALUE_OBJECT || SAME_TYPE
import speiger.src.collections.objects.functions.function.Object2BooleanFunction;
#endif
#endif
#if !SAME_TYPE
#if !TYPE_OBJECT #if !TYPE_OBJECT
import speiger.src.collections.objects.functions.consumer.VALUE_BI_FROM_OBJECT_CONSUMER;
#endif
import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_PREDICATE;
#endif
#if !TYPE_OBJECT
#if !VALUE_OBJECT
import speiger.src.collections.objects.functions.function.ObjectObjectUnaryOperator;
#endif
import speiger.src.collections.objects.collections.ObjectBidirectionalIterator; import speiger.src.collections.objects.collections.ObjectBidirectionalIterator;
import speiger.src.collections.objects.lists.ObjectListIterator; import speiger.src.collections.objects.lists.ObjectListIterator;
import speiger.src.collections.objects.sets.AbstractObjectSet; import speiger.src.collections.objects.sets.AbstractObjectSet;
@@ -316,6 +346,23 @@ public class LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends CUSTOM_HASH_M
return values[index]; return values[index];
} }
@Override
public LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE copy() {
LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE map = new LINKED_CUSTOM_HASH_MAPKV_BRACES(0, loadFactor, strategy);
map.minCapacity = minCapacity;
map.mask = mask;
map.maxFill = maxFill;
map.nullIndex = nullIndex;
map.containsNull = containsNull;
map.size = size;
map.keys = Arrays.copyOf(keys, keys.length);
map.values = Arrays.copyOf(values, values.length);
map.links = Arrays.copyOf(links, links.length);
map.firstIndex = firstIndex;
map.lastIndex = lastIndex;
return map;
}
@Override @Override
public COMPARATOR KEY_GENERIC_TYPE comparator() { public COMPARATOR KEY_GENERIC_TYPE comparator() {
return null; return null;
@@ -423,6 +470,24 @@ public class LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends CUSTOM_HASH_M
firstIndex = lastIndex = -1; firstIndex = lastIndex = -1;
} }
@Override
public void clearAndTrim(int size) {
int request = Math.max(minCapacity, HashUtil.nextPowerOfTwo((int)Math.ceil(size / loadFactor)));
if(request >= size) {
clear();
return;
}
nullIndex = request;
mask = request-1;
maxFill = Math.min((int)Math.ceil(nullIndex * loadFactor), nullIndex - 1);
keys = NEW_KEY_ARRAY(request + 1);
values = NEW_VALUE_ARRAY(request + 1);
links = new long[request + 1];
firstIndex = lastIndex = -1;
this.size = 0;
containsNull = false;
}
protected void moveToFirstIndex(int startPos) { protected void moveToFirstIndex(int startPos) {
if(size == 1 || firstIndex == startPos) return; if(size == 1 || firstIndex == startPos) return;
if(lastIndex == startPos) { if(lastIndex == startPos) {
@@ -481,7 +546,7 @@ public class LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends CUSTOM_HASH_M
} }
else if(lastIndex == pos) { else if(lastIndex == pos) {
lastIndex = (int)(links[pos] >>> 32); lastIndex = (int)(links[pos] >>> 32);
if(0 <= lastIndex) links[pos] |= 0xFFFFFFFFL; if(0 <= lastIndex) links[lastIndex] |= 0xFFFFFFFFL;
} }
else { else {
long link = links[pos]; long link = links[pos];
@@ -615,10 +680,13 @@ public class LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends CUSTOM_HASH_M
return new FastEntryIterator(fromElement); return new FastEntryIterator(fromElement);
} }
@Override
public MapEntrySet copy() { throw new UnsupportedOperationException(); }
@Override @Override
public void forEach(Consumer<? super MAP.Entry KEY_VALUE_GENERIC_TYPE> action) { public void forEach(Consumer<? super MAP.Entry KEY_VALUE_GENERIC_TYPE> action) {
int index = firstIndex; int index = firstIndex;
while(index != -1){ while(index != -1) {
action.accept(new BasicEntryKV_BRACES(keys[index], values[index])); action.accept(new BasicEntryKV_BRACES(keys[index], values[index]));
index = (int)links[index]; index = (int)links[index];
} }
@@ -628,19 +696,143 @@ public class LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends CUSTOM_HASH_M
public void fastForEach(Consumer<? super MAP.Entry KEY_VALUE_GENERIC_TYPE> action) { public void fastForEach(Consumer<? super MAP.Entry KEY_VALUE_GENERIC_TYPE> action) {
BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES();
int index = firstIndex; int index = firstIndex;
while(index != -1){ while(index != -1) {
entry.set(keys[index], values[index]); entry.set(keys[index], values[index]);
action.accept(entry); action.accept(entry);
index = (int)links[index]; index = (int)links[index];
} }
} }
@Override
public <E> void forEach(E input, ObjectObjectConsumer<E, MAP.Entry KEY_VALUE_GENERIC_TYPE> action) {
Objects.requireNonNull(action);
if(size() <= 0) return;
int index = firstIndex;
while(index != -1) {
action.accept(input, new BasicEntryKV_BRACES(keys[index], values[index]));
index = (int)links[index];
}
}
@Override
public boolean matchesAny(Object2BooleanFunction<MAP.Entry KEY_VALUE_GENERIC_TYPE> filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return false;
BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES();
int index = firstIndex;
while(index != -1) {
entry.set(keys[index], values[index]);
if(filter.getBoolean(entry)) return true;
index = (int)links[index];
}
return false;
}
@Override
public boolean matchesNone(Object2BooleanFunction<MAP.Entry KEY_VALUE_GENERIC_TYPE> filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return true;
BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES();
int index = firstIndex;
while(index != -1) {
entry.set(keys[index], values[index]);
if(filter.getBoolean(entry)) return false;
index = (int)links[index];
}
return true;
}
@Override
public boolean matchesAll(Object2BooleanFunction<MAP.Entry KEY_VALUE_GENERIC_TYPE> filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return true;
BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES();
int index = firstIndex;
while(index != -1) {
entry.set(keys[index], values[index]);
if(!filter.getBoolean(entry)) return false;
index = (int)links[index];
}
return true;
}
@Override
public <E> E reduce(E identity, BiFunction<E, MAP.Entry KEY_VALUE_GENERIC_TYPE, E> operator) {
Objects.requireNonNull(operator);
E state = identity;
int index = firstIndex;
while(index != -1) {
state = operator.apply(state, new BasicEntryKV_BRACES(keys[index], values[index]));
index = (int)links[index];
}
return state;
}
@Override
public MAP.Entry KEY_VALUE_GENERIC_TYPE reduce(ObjectObjectUnaryOperator<MAP.Entry KEY_VALUE_GENERIC_TYPE, MAP.Entry KEY_VALUE_GENERIC_TYPE> operator) {
Objects.requireNonNull(operator);
MAP.Entry KEY_VALUE_GENERIC_TYPE state = null;
boolean empty = true;
int index = firstIndex;
while(index != -1) {
if(empty) {
empty = false;
state = new BasicEntryKV_BRACES(keys[index], values[index]);
index = (int)links[index];
continue;
}
state = operator.apply(state, new BasicEntryKV_BRACES(keys[index], values[index]));
index = (int)links[index];
}
return state;
}
@Override
public MAP.Entry KEY_VALUE_GENERIC_TYPE findFirst(Object2BooleanFunction<MAP.Entry KEY_VALUE_GENERIC_TYPE> filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return null;
BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES();
int index = firstIndex;
while(index != -1) {
entry.set(keys[index], values[index]);
if(filter.getBoolean(entry)) return entry;
index = (int)links[index];
}
return null;
}
@Override
public int count(Object2BooleanFunction<MAP.Entry KEY_VALUE_GENERIC_TYPE> filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return 0;
BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES();
int result = 0;
int index = firstIndex;
while(index != -1) {
entry.set(keys[index], values[index]);
if(filter.getBoolean(entry)) result++;
index = (int)links[index];
}
return result;
}
@Override @Override
@Deprecated @Deprecated
public boolean contains(Object o) { public boolean contains(Object o) {
if(o instanceof Map.Entry) { if(o instanceof Map.Entry) {
if(o instanceof MAP.Entry) return LINKED_CUSTOM_HASH_MAP.this.containsKey(((MAP.Entry KEY_VALUE_GENERIC_TYPE)o).ENTRY_KEY()); if(o instanceof MAP.Entry) {
return LINKED_CUSTOM_HASH_MAP.this.containsKey(((Map.Entry<?, ?>)o).getKey()); MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)o;
int index = LINKED_CUSTOM_HASH_MAP.this.findIndex(entry.ENTRY_KEY());
if(index >= 0) return VALUE_EQUALS(entry.ENTRY_VALUE(), LINKED_CUSTOM_HASH_MAP.this.values[index]);
}
else {
Map.Entry<?, ?> entry = (Map.Entry<?, ?>)o;
#if !TYPE_OBJECT
if(!(entry.getKey() instanceof CLASS_TYPE)) return false;
#endif
int index = LINKED_CUSTOM_HASH_MAP.this.findIndex((CLASS_TYPE)entry.getKey());
if(index >= 0) return Objects.equals(entry.getValue(), VALUE_TO_OBJ(LINKED_CUSTOM_HASH_MAP.this.values[index]));
}
} }
return false; return false;
} }
@@ -692,7 +884,7 @@ public class LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends CUSTOM_HASH_M
@Override @Override
public boolean remove(Object o) { public boolean remove(Object o) {
int oldSize = size; int oldSize = size;
remove(o); LINKED_CUSTOM_HASH_MAP.this.remove(o);
return size != oldSize; return size != oldSize;
} }
@@ -705,7 +897,7 @@ public class LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends CUSTOM_HASH_M
@Override @Override
public boolean remove(KEY_TYPE o) { public boolean remove(KEY_TYPE o) {
int oldSize = size; int oldSize = size;
remove(o); LINKED_CUSTOM_HASH_MAP.this.remove(o);
return size != oldSize; return size != oldSize;
} }
@@ -741,6 +933,9 @@ public class LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends CUSTOM_HASH_M
return new KeyIterator(fromElement); return new KeyIterator(fromElement);
} }
@Override
public KeySet copy() { throw new UnsupportedOperationException(); }
@Override @Override
public int size() { public int size() {
return LINKED_CUSTOM_HASH_MAP.this.size(); return LINKED_CUSTOM_HASH_MAP.this.size();
@@ -771,17 +966,6 @@ public class LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends CUSTOM_HASH_M
return POLL_LAST_ENTRY_KEY(); return POLL_LAST_ENTRY_KEY();
} }
#if TYPE_OBJECT
@Override
public void forEach(Consumer KEY_SUPER_GENERIC_TYPE action) {
int index = firstIndex;
while(index != -1){
action.accept(keys[index]);
index = (int)links[index];
}
}
#else
@Override @Override
public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) { public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) {
int index = firstIndex; int index = firstIndex;
@@ -791,7 +975,124 @@ public class LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends CUSTOM_HASH_M
} }
} }
@Override
public <E> void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
if(size() <= 0) return;
int index = firstIndex;
while(index != -1){
action.accept(input, keys[index]);
index = (int)links[index];
}
}
@Override
public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return false;
int index = firstIndex;
while(index != -1){
if(filter.TEST_VALUE(keys[index])) return true;
index = (int)links[index];
}
return false;
}
@Override
public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return true;
int index = firstIndex;
while(index != -1){
if(filter.TEST_VALUE(keys[index])) return false;
index = (int)links[index];
}
return true;
}
@Override
public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return true;
int index = firstIndex;
while(index != -1){
if(!filter.TEST_VALUE(keys[index])) return false;
index = (int)links[index];
}
return true;
}
#if !TYPE_OBJECT
@Override
public KEY_TYPE reduce(KEY_TYPE identity, SINGLE_UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
KEY_TYPE state = identity;
int index = firstIndex;
while(index != -1) {
state = operator.APPLY_KEY_VALUE(state, keys[index]);
index = (int)links[index];
}
return state;
}
#else
@Override
public <KEY_SPECIAL_TYPE> KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction<KEY_SPECIAL_TYPE, KEY_TYPE, KEY_SPECIAL_TYPE> operator) {
Objects.requireNonNull(operator);
KEY_SPECIAL_TYPE state = identity;
int index = firstIndex;
while(index != -1) {
state = operator.apply(state, keys[index]);
index = (int)links[index];
}
return state;
}
#endif #endif
@Override
public KEY_TYPE reduce(SINGLE_UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
KEY_TYPE state = EMPTY_KEY_VALUE;
boolean empty = true;
int index = firstIndex;
while(index != -1) {
if(empty) {
empty = false;
state = keys[index];
index = (int)links[index];
continue;
}
state = operator.APPLY_KEY_VALUE(state, keys[index]);
index = (int)links[index];
}
return state;
}
@Override
public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return EMPTY_KEY_VALUE;
int index = firstIndex;
while(index != -1){
if(filter.TEST_VALUE(keys[index])) return keys[index];
index = (int)links[index];
}
return EMPTY_KEY_VALUE;
}
@Override
public int count(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return 0;
int result = 0;
int index = firstIndex;
while(index != -1){
if(filter.TEST_VALUE(keys[index])) result++;
index = (int)links[index];
}
return result;
}
@Override @Override
public COMPARATOR KEY_GENERIC_TYPE comparator() { return null; } public COMPARATOR KEY_GENERIC_TYPE comparator() { return null; }
@@ -840,16 +1141,6 @@ public class LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends CUSTOM_HASH_M
LINKED_CUSTOM_HASH_MAP.this.clear(); LINKED_CUSTOM_HASH_MAP.this.clear();
} }
#if VALUE_OBJECT
@Override
public void forEach(Consumer VALUE_SUPER_GENERIC_TYPE action) {
int index = firstIndex;
while(index != -1){
action.accept(values[index]);
index = (int)links[index];
}
}
#else
@Override @Override
public void forEach(VALUE_CONSUMER VALUE_SUPER_GENERIC_TYPE action) { public void forEach(VALUE_CONSUMER VALUE_SUPER_GENERIC_TYPE action) {
int index = firstIndex; int index = firstIndex;
@@ -858,7 +1149,124 @@ public class LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends CUSTOM_HASH_M
index = (int)links[index]; index = (int)links[index];
} }
} }
@Override
public <E> void forEach(E input, VALUE_BI_FROM_OBJECT_CONSUMER VSV_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
if(size() <= 0) return;
int index = firstIndex;
while(index != -1){
action.accept(input, values[index]);
index = (int)links[index];
}
}
@Override
public boolean matchesAny(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return false;
int index = firstIndex;
while(index != -1){
if(filter.VALUE_TEST_VALUE(values[index])) return true;
index = (int)links[index];
}
return false;
}
@Override
public boolean matchesNone(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return true;
int index = firstIndex;
while(index != -1){
if(filter.VALUE_TEST_VALUE(values[index])) return false;
index = (int)links[index];
}
return true;
}
@Override
public boolean matchesAll(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return true;
int index = firstIndex;
while(index != -1){
if(!filter.VALUE_TEST_VALUE(values[index])) return false;
index = (int)links[index];
}
return true;
}
#if !VALUE_OBJECT
@Override
public VALUE_TYPE reduce(VALUE_TYPE identity, VALUE_SINGLE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
VALUE_TYPE state = identity;
int index = firstIndex;
while(index != -1) {
state = operator.APPLY_VALUE(state, values[index]);
index = (int)links[index];
}
return state;
}
#else
@Override
public <VALUE_SPECIAL_TYPE> VALUE_SPECIAL_TYPE reduce(VALUE_SPECIAL_TYPE identity, BiFunction<VALUE_SPECIAL_TYPE, VALUE_TYPE, VALUE_SPECIAL_TYPE> operator) {
Objects.requireNonNull(operator);
VALUE_SPECIAL_TYPE state = identity;
int index = firstIndex;
while(index != -1) {
state = operator.apply(state, values[index]);
index = (int)links[index];
}
return state;
}
#endif #endif
@Override
public VALUE_TYPE reduce(VALUE_SINGLE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
VALUE_TYPE state = EMPTY_VALUE;
boolean empty = true;
int index = firstIndex;
while(index != -1) {
if(empty) {
empty = false;
state = values[index];
index = (int)links[index];
continue;
}
state = operator.APPLY_VALUE(state, values[index]);
index = (int)links[index];
}
return state;
}
@Override
public VALUE_TYPE findFirst(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return EMPTY_VALUE;
int index = firstIndex;
while(index != -1){
if(filter.VALUE_TEST_VALUE(values[index])) return values[index];
index = (int)links[index];
}
return EMPTY_VALUE;
}
@Override
public int count(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return 0;
int result = 0;
int index = firstIndex;
while(index != -1){
if(filter.VALUE_TEST_VALUE(values[index])) result++;
index = (int)links[index];
}
return result;
}
} }
private class FastEntryIterator extends MapIterator implements ObjectListIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> { private class FastEntryIterator extends MapIterator implements ObjectListIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> {
@@ -976,8 +1384,8 @@ public class LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends CUSTOM_HASH_M
MapIterator(KEY_TYPE from) { MapIterator(KEY_TYPE from) {
if(strategy.equals(from, EMPTY_KEY_VALUE)) { if(strategy.equals(from, EMPTY_KEY_VALUE)) {
if(containsNull) { if(containsNull) {
next = (int) links[nullIndex]; next = (int) links[nullIndex];
previous = nullIndex; previous = nullIndex;
} }
else throw new NoSuchElementException("The null element is not in the set"); else throw new NoSuchElementException("The null element is not in the set");
} }
@@ -1,20 +1,32 @@
package speiger.src.collections.PACKAGE.maps.impl.customHash; package speiger.src.collections.PACKAGE.maps.impl.customHash;
import java.util.Arrays; import java.util.Arrays;
import java.util.ConcurrentModificationException;
import java.util.Map; import java.util.Map;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import java.util.Objects; import java.util.Objects;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.function.BiFunction;
#if !TYPE_OBJECT #if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.collections.ITERATOR; import speiger.src.collections.PACKAGE.collections.ITERATOR;
import speiger.src.collections.PACKAGE.functions.CONSUMER; import speiger.src.collections.PACKAGE.functions.CONSUMER;
import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER;
#endif #endif
import speiger.src.collections.PACKAGE.functions.consumer.BI_CONSUMER; import speiger.src.collections.PACKAGE.functions.consumer.BI_CONSUMER;
import speiger.src.collections.PACKAGE.functions.function.FUNCTION;
import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR;
#if !SAME_TYPE
import speiger.src.collections.PACKAGE.functions.function.SINGLE_UNARY_OPERATOR;
#endif
#if !TYPE_OBJECT && !VALUE_BOOLEAN
import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
#endif
import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; import speiger.src.collections.PACKAGE.lists.ARRAY_LIST;
import speiger.src.collections.PACKAGE.lists.LIST; import speiger.src.collections.PACKAGE.lists.LIST;
import speiger.src.collections.PACKAGE.maps.abstracts.ABSTRACT_MAP; import speiger.src.collections.PACKAGE.maps.abstracts.ABSTRACT_MAP;
import speiger.src.collections.PACKAGE.maps.interfaces.MAP; import speiger.src.collections.PACKAGE.maps.interfaces.MAP;
import speiger.src.collections.PACKAGE.utils.maps.MAPS;
#if !TYPE_OBJECT #if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.sets.ABSTRACT_SET; import speiger.src.collections.PACKAGE.sets.ABSTRACT_SET;
import speiger.src.collections.PACKAGE.sets.SET; import speiger.src.collections.PACKAGE.sets.SET;
@@ -22,14 +34,41 @@ import speiger.src.collections.PACKAGE.sets.SET;
import speiger.src.collections.PACKAGE.utils.STRATEGY; import speiger.src.collections.PACKAGE.utils.STRATEGY;
import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ABSTRACT_COLLECTION; import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ABSTRACT_COLLECTION;
import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_COLLECTION; import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_COLLECTION;
#if !SAME_TYPE && !VALUE_OBJECT import speiger.src.collections.VALUE_PACKAGE.functions.VALUE_SUPPLIER;
#if !SAME_TYPE
import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_UNARY_OPERATOR;
#if !VALUE_OBJECT
#if !TYPE_OBJECT
import speiger.src.collections.objects.functions.function.ObjectObjectUnaryOperator;
#endif
import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ITERATOR; import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ITERATOR;
import speiger.src.collections.VALUE_PACKAGE.functions.VALUE_CONSUMER; import speiger.src.collections.VALUE_PACKAGE.functions.VALUE_CONSUMER;
#endif #endif
#else if !VALUE_OBJECT
import speiger.src.collections.objects.functions.function.ObjectObjectUnaryOperator;
#endif
#if !TYPE_OBJECT && !VALUE_OBJECT || !VALUE_OBJECT
import speiger.src.collections.objects.functions.consumer.ObjectObjectConsumer;
#endif
#if !TYPE_OBJECT || !VALUE_BOOLEAN
#if !VALUE_OBJECT || SAME_TYPE
import speiger.src.collections.objects.functions.function.Object2BooleanFunction;
#endif
#endif
#if !SAME_TYPE
#if !TYPE_OBJECT
import speiger.src.collections.objects.functions.consumer.VALUE_BI_FROM_OBJECT_CONSUMER;
#endif
import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_PREDICATE;
#endif
import speiger.src.collections.objects.collections.ObjectIterator; import speiger.src.collections.objects.collections.ObjectIterator;
import speiger.src.collections.objects.sets.AbstractObjectSet; import speiger.src.collections.objects.sets.AbstractObjectSet;
import speiger.src.collections.objects.sets.ObjectSet; import speiger.src.collections.objects.sets.ObjectSet;
import speiger.src.collections.utils.HashUtil; import speiger.src.collections.utils.HashUtil;
import speiger.src.collections.utils.ITrimmable;
/** /**
* A Type Specific HashMap that allows for custom HashControl. * A Type Specific HashMap that allows for custom HashControl.
@@ -37,7 +76,7 @@ import speiger.src.collections.utils.HashUtil;
* @Type(T) * @Type(T)
* @ValueType(V) * @ValueType(V)
*/ */
public class CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE public class CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE implements ITrimmable
{ {
/** The Backing keys array */ /** The Backing keys array */
protected transient KEY_TYPE[] keys; protected transient KEY_TYPE[] keys;
@@ -256,7 +295,7 @@ public class CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VAL
#endif #endif
@Override @Override
@Deprecated @Primitive
public boolean containsKey(Object key) { public boolean containsKey(Object key) {
#if !TYPE_OBJECT #if !TYPE_OBJECT
return key instanceof CLASS_TYPE && findIndex(CLASS_TO_KEY(key)) >= 0; return key instanceof CLASS_TYPE && findIndex(CLASS_TO_KEY(key)) >= 0;
@@ -268,31 +307,39 @@ public class CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VAL
#if !VALUE_OBJECT #if !VALUE_OBJECT
@Override @Override
public boolean containsValue(VALUE_TYPE value) { public boolean containsValue(VALUE_TYPE value) {
if(VALUE_EQUALS(value, values[nullIndex])) return true; for(int i = nullIndex;i >= 0;i--)
for(int i = nullIndex-1;i >= 0;i--)
if(!strategy.equals(keys[i], EMPTY_KEY_VALUE) && VALUE_EQUALS(values[i], value)) return true; if(!strategy.equals(keys[i], EMPTY_KEY_VALUE) && VALUE_EQUALS(values[i], value)) return true;
return false; return false;
} }
#endif #endif
@Override @Override
@Deprecated @ValuePrimitive
public boolean containsValue(Object value) { public boolean containsValue(Object value) {
if((value == null && VALUE_EQUALS(values[nullIndex], getDefaultReturnValue())) || EQUALS_VALUE_TYPE(values[nullIndex], value)) return true; for(int i = nullIndex;i >= 0;i--)
for(int i = nullIndex-1;i >= 0;i--) #if VALUE_OBJECT
if(!strategy.equals(keys[i], EMPTY_KEY_VALUE) && EQUALS_VALUE_TYPE(values[i], value)) return true;
#else
if(!strategy.equals(keys[i], EMPTY_KEY_VALUE) && ((value == null && values[i] == getDefaultReturnValue()) || EQUALS_VALUE_TYPE(values[i], value))) return true; if(!strategy.equals(keys[i], EMPTY_KEY_VALUE) && ((value == null && values[i] == getDefaultReturnValue()) || EQUALS_VALUE_TYPE(values[i], value))) return true;
#endif
return false; return false;
} }
@Override @Override
public VALUE_TYPE REMOVE_KEY(KEY_TYPE key) { public VALUE_TYPE REMOVE_VALUE(KEY_TYPE key) {
int slot = findIndex(key); int slot = findIndex(key);
if(slot < 0) return getDefaultReturnValue(); if(slot < 0) return getDefaultReturnValue();
return removeIndex(slot); return removeIndex(slot);
} }
@Override @Override
@Deprecated public VALUE_TYPE REMOVE_VALUEOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) {
int slot = findIndex(key);
if(slot < 0) return defaultValue;
return removeIndex(slot);
}
@Override
public CLASS_VALUE_TYPE remove(Object key) { public CLASS_VALUE_TYPE remove(Object key) {
#if !TYPE_OBJECT #if !TYPE_OBJECT
if(!(key instanceof CLASS_TYPE)) return getDefaultReturnValue(); if(!(key instanceof CLASS_TYPE)) return getDefaultReturnValue();
@@ -389,6 +436,20 @@ public class CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VAL
} }
#endif #endif
@Override
public CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE copy() {
CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE map = new CUSTOM_HASH_MAPKV_BRACES(0, loadFactor, strategy);
map.minCapacity = minCapacity;
map.mask = mask;
map.maxFill = maxFill;
map.nullIndex = nullIndex;
map.containsNull = containsNull;
map.size = size;
map.keys = Arrays.copyOf(keys, keys.length);
map.values = Arrays.copyOf(values, values.length);
return map;
}
@Override @Override
public ObjectSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> ENTRY_SET() { public ObjectSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> ENTRY_SET() {
if(entrySet == null) entrySet = new MapEntrySet(); if(entrySet == null) entrySet = new MapEntrySet();
@@ -416,6 +477,127 @@ public class CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VAL
} }
} }
@Override
public boolean replace(KEY_TYPE key, VALUE_TYPE oldValue, VALUE_TYPE newValue) {
int index = findIndex(key);
if(index < 0 || values[index] != oldValue) return false;
values[index] = newValue;
return true;
}
@Override
public VALUE_TYPE replace(KEY_TYPE key, VALUE_TYPE value) {
int index = findIndex(key);
if(index < 0) return getDefaultReturnValue();
VALUE_TYPE oldValue = values[index];
values[index] = value;
return oldValue;
}
@Override
public VALUE_TYPE COMPUTE(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) {
Objects.requireNonNull(mappingFunction);
int index = findIndex(key);
if(index < 0) {
VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, getDefaultReturnValue());
if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue;
insert(-index-1, key, newValue);
return newValue;
}
VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, values[index]);
if(VALUE_EQUALS(newValue, getDefaultReturnValue())) {
removeIndex(index);
return newValue;
}
values[index] = newValue;
return newValue;
}
@Override
public VALUE_TYPE COMPUTE_IF_ABSENT(KEY_TYPE key, FUNCTION KEY_VALUE_GENERIC_TYPE mappingFunction) {
Objects.requireNonNull(mappingFunction);
int index = findIndex(key);
if(index < 0) {
VALUE_TYPE newValue = mappingFunction.GET_VALUE(key);
if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue;
insert(-index-1, key, newValue);
return newValue;
}
VALUE_TYPE newValue = values[index];
if(VALUE_EQUALS(newValue, getDefaultReturnValue())) {
newValue = mappingFunction.GET_VALUE(key);
if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue;
values[index] = newValue;
}
return newValue;
}
@Override
public VALUE_TYPE SUPPLY_IF_ABSENT(KEY_TYPE key, VALUE_SUPPLIER VALUE_GENERIC_TYPE valueProvider) {
Objects.requireNonNull(valueProvider);
int index = findIndex(key);
if(index < 0) {
VALUE_TYPE newValue = valueProvider.VALUE_GET_KEY();
if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue;
insert(-index-1, key, newValue);
return newValue;
}
VALUE_TYPE newValue = values[index];
if(VALUE_EQUALS(newValue, getDefaultReturnValue())) {
newValue = valueProvider.VALUE_GET_KEY();
if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue;
values[index] = newValue;
}
return newValue;
}
@Override
public VALUE_TYPE COMPUTE_IF_PRESENT(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) {
Objects.requireNonNull(mappingFunction);
int index = findIndex(key);
if(index < 0 || VALUE_EQUALS(values[index], getDefaultReturnValue())) return getDefaultReturnValue();
VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, values[index]);
if(VALUE_EQUALS(newValue, getDefaultReturnValue())) {
removeIndex(index);
return newValue;
}
values[index] = newValue;
return newValue;
}
@Override
public VALUE_TYPE MERGE(KEY_TYPE key, VALUE_TYPE value, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) {
Objects.requireNonNull(mappingFunction);
#if VALUE_OBJECT
Objects.requireNonNull(value);
#endif
int index = findIndex(key);
VALUE_TYPE newValue = index < 0 || VALUE_EQUALS(values[index], getDefaultReturnValue()) ? value : mappingFunction.APPLY_VALUE(values[index], value);
if(VALUE_EQUALS(newValue, getDefaultReturnValue())) {
if(index >= 0)
removeIndex(index);
}
else if(index < 0) insert(-index-1, key, newValue);
else values[index] = newValue;
return newValue;
}
@Override
public void BULK_MERGE(MAP KEY_VALUE_GENERIC_TYPE m, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) {
Objects.requireNonNull(mappingFunction);
for(MAP.Entry KEY_VALUE_GENERIC_TYPE entry : MAPS.fastIterable(m)) {
KEY_TYPE key = entry.ENTRY_KEY();
int index = findIndex(key);
VALUE_TYPE newValue = index < 0 || VALUE_EQUALS(values[index], getDefaultReturnValue()) ? entry.ENTRY_VALUE() : mappingFunction.APPLY_VALUE(values[index], entry.ENTRY_VALUE());
if(VALUE_EQUALS(newValue, getDefaultReturnValue())) {
if(index >= 0)
removeIndex(index);
}
else if(index < 0) insert(-index-1, key, newValue);
else values[index] = newValue;
}
}
@Override @Override
public int size() { return size; } public int size() { return size; }
@@ -428,6 +610,33 @@ public class CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VAL
Arrays.fill(values, EMPTY_VALUE); Arrays.fill(values, EMPTY_VALUE);
} }
@Override
public boolean trim(int size) {
int request = Math.max(minCapacity, HashUtil.nextPowerOfTwo((int)Math.ceil(size / loadFactor)));
if(request >= size || this.size > Math.min((int)Math.ceil(request * loadFactor), request - 1)) return false;
try {
rehash(request);
}
catch(OutOfMemoryError noMemory) { return false; }
return true;
}
@Override
public void clearAndTrim(int size) {
int request = Math.max(minCapacity, HashUtil.nextPowerOfTwo((int)Math.ceil(size / loadFactor)));
if(request >= size) {
clear();
return;
}
nullIndex = request;
mask = request-1;
maxFill = Math.min((int)Math.ceil(nullIndex * loadFactor), nullIndex - 1);
keys = NEW_KEY_ARRAY(request + 1);
values = NEW_VALUE_ARRAY(request + 1);
this.size = 0;
containsNull = false;
}
#if !TYPE_OBJECT #if !TYPE_OBJECT
protected int findIndex(KEY_TYPE key) { protected int findIndex(KEY_TYPE key) {
if(strategy.equals(key, EMPTY_KEY_VALUE)) return containsNull ? nullIndex : -(nullIndex + 1); if(strategy.equals(key, EMPTY_KEY_VALUE)) return containsNull ? nullIndex : -(nullIndex + 1);
@@ -456,7 +665,10 @@ public class CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VAL
} }
protected VALUE_TYPE removeIndex(int pos) { protected VALUE_TYPE removeIndex(int pos) {
if(pos == nullIndex) return containsNull ? removeNullIndex() : getDefaultReturnValue();
VALUE_TYPE value = values[pos]; VALUE_TYPE value = values[pos];
keys[pos] = EMPTY_KEY_VALUE;
values[pos] = EMPTY_VALUE;
size--; size--;
onNodeRemoved(pos); onNodeRemoved(pos);
shiftKeys(pos); shiftKeys(pos);
@@ -488,7 +700,10 @@ public class CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VAL
KEY_TYPE[] newKeys = NEW_KEY_ARRAY(newSize + 1); KEY_TYPE[] newKeys = NEW_KEY_ARRAY(newSize + 1);
VALUE_TYPE[] newValues = NEW_VALUE_ARRAY(newSize + 1); VALUE_TYPE[] newValues = NEW_VALUE_ARRAY(newSize + 1);
for(int i = nullIndex, pos = 0, j = (size - (containsNull ? 1 : 0));j-- != 0;) { for(int i = nullIndex, pos = 0, j = (size - (containsNull ? 1 : 0));j-- != 0;) {
while(strategy.equals(keys[--i], EMPTY_KEY_VALUE)); while(true) {
if(--i < 0) throw new ConcurrentModificationException("Map was modified during rehash");
if(!strategy.equals(keys[i], EMPTY_KEY_VALUE)) break;
}
if(!strategy.equals(newKeys[pos = HashUtil.mix(strategy.hashCode(keys[i])) & newMask], EMPTY_KEY_VALUE)) if(!strategy.equals(newKeys[pos = HashUtil.mix(strategy.hashCode(keys[i])) & newMask], EMPTY_KEY_VALUE))
while(!strategy.equals(newKeys[pos = (++pos & newMask)], EMPTY_KEY_VALUE)); while(!strategy.equals(newKeys[pos = (++pos & newMask)], EMPTY_KEY_VALUE));
newKeys[pos] = keys[i]; newKeys[pos] = keys[i];
@@ -590,7 +805,7 @@ public class CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VAL
@Override @Override
public String toString() { public String toString() {
return KEY_TO_STRING(keys[index]) + "->" + VALUE_TO_STRING(values[index]); return KEY_TO_STRING(keys[index]) + "=" + VALUE_TO_STRING(values[index]);
} }
} }
@@ -620,13 +835,147 @@ public class CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VAL
action.accept(entry); action.accept(entry);
} }
for(int i = nullIndex-1;i>=0;i--) { for(int i = nullIndex-1;i>=0;i--) {
if(strategy.equals(keys[i], EMPTY_KEY_VALUE)) { if(!strategy.equals(keys[i], EMPTY_KEY_VALUE)) {
entry.set(keys[i], values[i]); entry.set(keys[i], values[i]);
action.accept(entry); action.accept(entry);
} }
} }
} }
@Override
public <E> void forEach(E input, ObjectObjectConsumer<E, MAP.Entry KEY_VALUE_GENERIC_TYPE> action) {
Objects.requireNonNull(action);
if(size() <= 0) return;
if(containsNull) action.accept(input, new BasicEntryKV_BRACES(keys[nullIndex], values[nullIndex]));
for(int i = nullIndex-1;i>=0;i--) {
if(!strategy.equals(keys[i], EMPTY_KEY_VALUE)) action.accept(input, new BasicEntryKV_BRACES(keys[i], values[i]));
}
}
@Override
public boolean matchesAny(Object2BooleanFunction<MAP.Entry KEY_VALUE_GENERIC_TYPE> filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return false;
BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES();
if(containsNull) {
entry.set(keys[nullIndex], values[nullIndex]);
if(filter.getBoolean(entry)) return true;
}
for(int i = nullIndex-1;i>=0;i--) {
if(!strategy.equals(keys[i], EMPTY_KEY_VALUE)) {
entry.set(keys[i], values[i]);
if(filter.getBoolean(entry)) return true;
}
}
return false;
}
@Override
public boolean matchesNone(Object2BooleanFunction<MAP.Entry KEY_VALUE_GENERIC_TYPE> filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return true;
BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES();
if(containsNull) {
entry.set(keys[nullIndex], values[nullIndex]);
if(filter.getBoolean(entry)) return false;
}
for(int i = nullIndex-1;i>=0;i--) {
if(!strategy.equals(keys[i], EMPTY_KEY_VALUE)) {
entry.set(keys[i], values[i]);
if(filter.getBoolean(entry)) return false;
}
}
return true;
}
@Override
public boolean matchesAll(Object2BooleanFunction<MAP.Entry KEY_VALUE_GENERIC_TYPE> filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return true;
BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES();
if(containsNull) {
entry.set(keys[nullIndex], values[nullIndex]);
if(!filter.getBoolean(entry)) return false;
}
for(int i = nullIndex-1;i>=0;i--) {
if(!strategy.equals(keys[i], EMPTY_KEY_VALUE)) {
entry.set(keys[i], values[i]);
if(!filter.getBoolean(entry)) return false;
}
}
return true;
}
@Override
public <E> E reduce(E identity, BiFunction<E, MAP.Entry KEY_VALUE_GENERIC_TYPE, E> operator) {
Objects.requireNonNull(operator);
E state = identity;
if(containsNull) state = operator.apply(state, new BasicEntryKV_BRACES(keys[nullIndex], values[nullIndex]));
for(int i = nullIndex-1;i>=0;i--) {
if(strategy.equals(keys[i], EMPTY_KEY_VALUE)) continue;
state = operator.apply(state, new BasicEntryKV_BRACES(keys[i], values[i]));
}
return state;
}
@Override
public MAP.Entry KEY_VALUE_GENERIC_TYPE reduce(ObjectObjectUnaryOperator<MAP.Entry KEY_VALUE_GENERIC_TYPE, MAP.Entry KEY_VALUE_GENERIC_TYPE> operator) {
Objects.requireNonNull(operator);
MAP.Entry KEY_VALUE_GENERIC_TYPE state = null;
boolean empty = true;
if(containsNull) {
state = new BasicEntryKV_BRACES(keys[nullIndex], values[nullIndex]);
empty = false;
}
for(int i = 0;i<size;i++) {
if(strategy.equals(keys[i], EMPTY_KEY_VALUE)) continue;
if(empty) {
empty = false;
state = new BasicEntryKV_BRACES(keys[i], values[i]);
continue;
}
state = operator.apply(state, new BasicEntryKV_BRACES(keys[i], values[i]));
}
return state;
}
@Override
public MAP.Entry KEY_VALUE_GENERIC_TYPE findFirst(Object2BooleanFunction<MAP.Entry KEY_VALUE_GENERIC_TYPE> filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return null;
BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES();
if(containsNull) {
entry.set(keys[nullIndex], values[nullIndex]);
if(filter.getBoolean(entry)) return entry;
}
for(int i = nullIndex-1;i>=0;i--) {
if(!strategy.equals(keys[i], EMPTY_KEY_VALUE)) {
entry.set(keys[i], values[i]);
if(filter.getBoolean(entry)) return entry;
}
}
return null;
}
@Override
public int count(Object2BooleanFunction<MAP.Entry KEY_VALUE_GENERIC_TYPE> filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return 0;
BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES();
int result = 0;
if(containsNull) {
entry.set(keys[nullIndex], values[nullIndex]);
if(filter.getBoolean(entry)) result++;
}
for(int i = nullIndex-1;i>=0;i--) {
if(!strategy.equals(keys[i], EMPTY_KEY_VALUE)) {
entry.set(keys[i], values[i]);
if(filter.getBoolean(entry)) result++;
}
}
return result;
}
@Override @Override
public int size() { public int size() {
return CUSTOM_HASH_MAP.this.size(); return CUSTOM_HASH_MAP.this.size();
@@ -640,8 +989,19 @@ public class CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VAL
@Override @Override
public boolean contains(Object o) { public boolean contains(Object o) {
if(o instanceof Map.Entry) { if(o instanceof Map.Entry) {
if(o instanceof MAP.Entry) return CUSTOM_HASH_MAP.this.containsKey(((MAP.Entry KEY_VALUE_GENERIC_TYPE)o).ENTRY_KEY()); if(o instanceof MAP.Entry) {
return CUSTOM_HASH_MAP.this.containsKey(((Map.Entry<?, ?>)o).getKey()); MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)o;
int index = CUSTOM_HASH_MAP.this.findIndex(entry.ENTRY_KEY());
if(index >= 0) return VALUE_EQUALS(entry.ENTRY_VALUE(), CUSTOM_HASH_MAP.this.values[index]);
}
else {
Map.Entry<?, ?> entry = (Map.Entry<?, ?>)o;
#if !TYPE_OBJECT
if(!(entry.getKey() instanceof CLASS_TYPE)) return false;
#endif
int index = CUSTOM_HASH_MAP.this.findIndex((CLASS_TYPE)entry.getKey());
if(index >= 0) return Objects.equals(entry.getValue(), VALUE_TO_OBJ(CUSTOM_HASH_MAP.this.values[index]));
}
} }
return false; return false;
} }
@@ -670,7 +1030,7 @@ public class CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VAL
@Override @Override
public boolean remove(Object o) { public boolean remove(Object o) {
int oldSize = size; int oldSize = size;
remove(o); CUSTOM_HASH_MAP.this.remove(o);
return size != oldSize; return size != oldSize;
} }
@@ -683,7 +1043,7 @@ public class CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VAL
@Override @Override
public boolean remove(KEY_TYPE o) { public boolean remove(KEY_TYPE o) {
int oldSize = size; int oldSize = size;
remove(o); CUSTOM_HASH_MAP.this.remove(o);
return size != oldSize; return size != oldSize;
} }
@@ -698,6 +1058,9 @@ public class CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VAL
return new KeyIterator(); return new KeyIterator();
} }
@Override
public KeySet copy() { throw new UnsupportedOperationException(); }
@Override @Override
public int size() { public int size() {
return CUSTOM_HASH_MAP.this.size(); return CUSTOM_HASH_MAP.this.size();
@@ -708,22 +1071,127 @@ public class CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VAL
CUSTOM_HASH_MAP.this.clear(); CUSTOM_HASH_MAP.this.clear();
} }
#if TYPE_OBJECT
@Override @Override
public void forEach(Consumer KEY_SUPER_GENERIC_TYPE action) { public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) {
Objects.requireNonNull(action);
if(containsNull) action.accept(keys[nullIndex]); if(containsNull) action.accept(keys[nullIndex]);
for(int i = nullIndex-1;i>=0;i--) for(int i = nullIndex-1;i>=0;i--)
if(strategy.equals(keys[i], EMPTY_KEY_VALUE)) action.accept(keys[i]); if(!strategy.equals(keys[i], EMPTY_KEY_VALUE)) action.accept(keys[i]);
}
@Override
public <E> void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
if(size() <= 0) return;
if(containsNull) action.accept(input, keys[nullIndex]);
for(int i = nullIndex-1;i>=0;i--) {
if(!strategy.equals(keys[i], EMPTY_KEY_VALUE)) action.accept(input, keys[i]);
}
}
@Override
public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return false;
if(containsNull && filter.TEST_VALUE(keys[nullIndex])) return true;
for(int i = nullIndex-1;i>=0;i--) {
if(!strategy.equals(keys[i], EMPTY_KEY_VALUE) && filter.TEST_VALUE(keys[i])) return true;
}
return false;
}
@Override
public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return true;
if(containsNull && filter.TEST_VALUE(keys[nullIndex])) return false;
for(int i = nullIndex-1;i>=0;i--) {
if(!strategy.equals(keys[i], EMPTY_KEY_VALUE) && filter.TEST_VALUE(keys[i])) return false;
}
return true;
}
@Override
public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return true;
if(containsNull && !filter.TEST_VALUE(keys[nullIndex])) return false;
for(int i = nullIndex-1;i>=0;i--) {
if(!strategy.equals(keys[i], EMPTY_KEY_VALUE) && !filter.TEST_VALUE(keys[i])) return false;
}
return true;
}
#if !TYPE_OBJECT
@Override
public KEY_TYPE reduce(KEY_TYPE identity, SINGLE_UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
KEY_TYPE state = identity;
if(containsNull) state = operator.APPLY_KEY_VALUE(state, keys[nullIndex]);
for(int i = nullIndex-1;i>=0;i--) {
if(strategy.equals(keys[i], EMPTY_KEY_VALUE)) continue;
state = operator.APPLY_KEY_VALUE(state, keys[i]);
}
return state;
} }
#else #else
@Override @Override
public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) { public <KEY_SPECIAL_TYPE> KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction<KEY_SPECIAL_TYPE, KEY_TYPE, KEY_SPECIAL_TYPE> operator) {
if(containsNull) action.accept(keys[nullIndex]); Objects.requireNonNull(operator);
for(int i = nullIndex-1;i>=0;i--) KEY_SPECIAL_TYPE state = identity;
if(strategy.equals(keys[i], EMPTY_KEY_VALUE)) action.accept(keys[i]); if(containsNull) state = operator.apply(state, keys[nullIndex]);
for(int i = nullIndex-1;i>=0;i--) {
if(strategy.equals(keys[i], EMPTY_KEY_VALUE)) continue;
state = operator.apply(state, keys[i]);
}
return state;
} }
#endif #endif
@Override
public KEY_TYPE reduce(SINGLE_UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
KEY_TYPE state = EMPTY_KEY_VALUE;
boolean empty = true;
if(containsNull) {
state = keys[nullIndex];
empty = false;
}
for(int i = 0;i<size;i++) {
if(strategy.equals(keys[i], EMPTY_KEY_VALUE)) continue;
if(empty) {
empty = false;
state = keys[i];
continue;
}
state = operator.APPLY_KEY_VALUE(state, keys[i]);
}
return state;
}
@Override
public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return EMPTY_KEY_VALUE;
if(containsNull && filter.TEST_VALUE(keys[nullIndex])) return keys[nullIndex];
for(int i = nullIndex-1;i>=0;i--) {
if(!strategy.equals(keys[i], EMPTY_KEY_VALUE) && filter.TEST_VALUE(keys[i])) return keys[i];
}
return EMPTY_KEY_VALUE;
}
@Override
public int count(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return 0;
int result = 0;
if(containsNull && filter.TEST_VALUE(keys[nullIndex])) result++;
for(int i = nullIndex-1;i>=0;i--) {
if(!strategy.equals(keys[i], EMPTY_KEY_VALUE) && filter.TEST_VALUE(keys[i])) result++;
}
return result;
}
} }
private class Values extends VALUE_ABSTRACT_COLLECTION VALUE_GENERIC_TYPE { private class Values extends VALUE_ABSTRACT_COLLECTION VALUE_GENERIC_TYPE {
@@ -760,21 +1228,126 @@ public class CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VAL
CUSTOM_HASH_MAP.this.clear(); CUSTOM_HASH_MAP.this.clear();
} }
#if VALUE_OBJECT
@Override
public void forEach(Consumer VALUE_SUPER_GENERIC_TYPE action) {
if(containsNull) action.accept(values[nullIndex]);
for(int i = nullIndex-1;i>=0;i--)
if(!strategy.equals(keys[i], EMPTY_KEY_VALUE)) action.accept(values[i]);
}
#else
@Override @Override
public void forEach(VALUE_CONSUMER VALUE_SUPER_GENERIC_TYPE action) { public void forEach(VALUE_CONSUMER VALUE_SUPER_GENERIC_TYPE action) {
if(containsNull) action.accept(values[nullIndex]); if(containsNull) action.accept(values[nullIndex]);
for(int i = nullIndex-1;i>=0;i--) for(int i = nullIndex-1;i>=0;i--)
if(!strategy.equals(keys[i], EMPTY_KEY_VALUE)) action.accept(values[i]); if(!strategy.equals(keys[i], EMPTY_KEY_VALUE)) action.accept(values[i]);
} }
@Override
public <E> void forEach(E input, VALUE_BI_FROM_OBJECT_CONSUMER VSV_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
if(size() <= 0) return;
if(containsNull) action.accept(input, values[nullIndex]);
for(int i = nullIndex-1;i>=0;i--) {
if(!strategy.equals(keys[i], EMPTY_KEY_VALUE)) action.accept(input, values[i]);
}
}
@Override
public boolean matchesAny(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return false;
if(containsNull && filter.VALUE_TEST_VALUE(values[nullIndex])) return true;
for(int i = nullIndex-1;i>=0;i--) {
if(!strategy.equals(keys[i], EMPTY_KEY_VALUE) && filter.VALUE_TEST_VALUE(values[i])) return true;
}
return false;
}
@Override
public boolean matchesNone(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return true;
if(containsNull && filter.VALUE_TEST_VALUE(values[nullIndex])) return false;
for(int i = nullIndex-1;i>=0;i--) {
if(!strategy.equals(keys[i], EMPTY_KEY_VALUE) && filter.VALUE_TEST_VALUE(values[i])) return false;
}
return true;
}
@Override
public boolean matchesAll(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return true;
if(containsNull && !filter.VALUE_TEST_VALUE(values[nullIndex])) return false;
for(int i = nullIndex-1;i>=0;i--) {
if(!strategy.equals(keys[i], EMPTY_KEY_VALUE) && !filter.VALUE_TEST_VALUE(values[i])) return false;
}
return true;
}
#if !VALUE_OBJECT
@Override
public VALUE_TYPE reduce(VALUE_TYPE identity, VALUE_SINGLE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
VALUE_TYPE state = identity;
if(containsNull) state = operator.APPLY_VALUE(state, values[nullIndex]);
for(int i = nullIndex-1;i>=0;i--) {
if(strategy.equals(keys[i], EMPTY_KEY_VALUE)) continue;
state = operator.APPLY_VALUE(state, values[i]);
}
return state;
}
#else
@Override
public <VALUE_SPECIAL_TYPE> VALUE_SPECIAL_TYPE reduce(VALUE_SPECIAL_TYPE identity, BiFunction<VALUE_SPECIAL_TYPE, VALUE_TYPE, VALUE_SPECIAL_TYPE> operator) {
Objects.requireNonNull(operator);
VALUE_SPECIAL_TYPE state = identity;
if(containsNull) state = operator.APPLY_VALUE(state, values[nullIndex]);
for(int i = nullIndex-1;i>=0;i--) {
if(strategy.equals(keys[i], EMPTY_KEY_VALUE)) continue;
state = operator.APPLY_VALUE(state, values[i]);
}
return state;
}
#endif #endif
@Override
public VALUE_TYPE reduce(VALUE_SINGLE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
VALUE_TYPE state = EMPTY_VALUE;
boolean empty = true;
if(containsNull) {
state = values[nullIndex];
empty = false;
}
for(int i = 0;i<size;i++) {
if(strategy.equals(keys[i], EMPTY_KEY_VALUE)) continue;
if(empty) {
empty = false;
state = values[i];
continue;
}
state = operator.APPLY_VALUE(state, values[i]);
}
return state;
}
@Override
public VALUE_TYPE findFirst(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return EMPTY_VALUE;
if(containsNull && filter.VALUE_TEST_VALUE(values[nullIndex])) return values[nullIndex];
for(int i = nullIndex-1;i>=0;i--) {
if(!strategy.equals(keys[i], EMPTY_KEY_VALUE) && filter.VALUE_TEST_VALUE(values[i])) return values[i];
}
return EMPTY_VALUE;
}
@Override
public int count(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return 0;
int result = 0;
if(containsNull && filter.VALUE_TEST_VALUE(values[nullIndex])) result++;
for(int i = nullIndex-1;i>=0;i--) {
if(!strategy.equals(keys[i], EMPTY_KEY_VALUE) && filter.VALUE_TEST_VALUE(values[i])) result++;
}
return result;
}
} }
private class FastEntryIterator extends MapIterator implements ObjectIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> { private class FastEntryIterator extends MapIterator implements ObjectIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> {
@@ -816,6 +1389,7 @@ public class CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VAL
private class MapIterator { private class MapIterator {
int pos = nullIndex; int pos = nullIndex;
int returnedPos = -1;
int lastReturned = -1; int lastReturned = -1;
int nextIndex = Integer.MIN_VALUE; int nextIndex = Integer.MIN_VALUE;
boolean returnNull = containsNull; boolean returnNull = containsNull;
@@ -847,6 +1421,7 @@ public class CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VAL
public int nextEntry() { public int nextEntry() {
if(!hasNext()) throw new NoSuchElementException(); if(!hasNext()) throw new NoSuchElementException();
returnedPos = pos;
if(nextIndex < 0){ if(nextIndex < 0){
lastReturned = Integer.MAX_VALUE; lastReturned = Integer.MAX_VALUE;
int value = findIndex(wrapped.GET_KEY(nextIndex)); int value = findIndex(wrapped.GET_KEY(nextIndex));
@@ -866,9 +1441,10 @@ public class CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VAL
keys[nullIndex] = EMPTY_KEY_VALUE; keys[nullIndex] = EMPTY_KEY_VALUE;
values[nullIndex] = EMPTY_VALUE; values[nullIndex] = EMPTY_VALUE;
} }
else if(pos >= 0) shiftKeys(pos); else if(returnedPos >= 0) shiftKeys(returnedPos);
else { else {
CUSTOM_HASH_MAP.this.remove(wrapped.GET_KEY(-pos - 1)); CUSTOM_HASH_MAP.this.remove(wrapped.GET_KEY(-returnedPos - 1));
lastReturned = -1;
return; return;
} }
size--; size--;
@@ -1,19 +1,24 @@
package speiger.src.collections.PACKAGE.maps.impl.hash; package speiger.src.collections.PACKAGE.maps.impl.hash;
import java.util.Arrays;
import java.util.Comparator; import java.util.Comparator;
import java.util.Map; import java.util.Map;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import java.util.function.Consumer; import java.util.function.Consumer;
#if TYPE_OBJECT import java.util.function.BiFunction;
import java.util.Objects; import java.util.Objects;
#endif
import speiger.src.collections.PACKAGE.collections.BI_ITERATOR; import speiger.src.collections.PACKAGE.collections.BI_ITERATOR;
#if !TYPE_OBJECT #if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.functions.COMPARATOR; import speiger.src.collections.PACKAGE.functions.COMPARATOR;
import speiger.src.collections.PACKAGE.functions.CONSUMER; import speiger.src.collections.PACKAGE.functions.CONSUMER;
import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER;
#endif
#if !TYPE_OBJECT || VALUE_BOOLEAN
import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
#endif #endif
import speiger.src.collections.PACKAGE.functions.consumer.BI_CONSUMER; import speiger.src.collections.PACKAGE.functions.consumer.BI_CONSUMER;
import speiger.src.collections.PACKAGE.functions.function.SINGLE_UNARY_OPERATOR;
import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR; import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR;
import speiger.src.collections.PACKAGE.maps.interfaces.MAP; import speiger.src.collections.PACKAGE.maps.interfaces.MAP;
import speiger.src.collections.PACKAGE.maps.interfaces.SORTED_MAP; import speiger.src.collections.PACKAGE.maps.interfaces.SORTED_MAP;
@@ -23,11 +28,33 @@ import speiger.src.collections.PACKAGE.sets.SET;
import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ABSTRACT_COLLECTION; import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ABSTRACT_COLLECTION;
import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_COLLECTION; import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_COLLECTION;
import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ITERATOR; import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ITERATOR;
#if !SAME_TYPE
import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_UNARY_OPERATOR;
#endif
#if !VALUE_OBJECT && !SAME_TYPE #if !VALUE_OBJECT && !SAME_TYPE
import speiger.src.collections.VALUE_PACKAGE.functions.VALUE_CONSUMER; import speiger.src.collections.VALUE_PACKAGE.functions.VALUE_CONSUMER;
import speiger.src.collections.VALUE_PACKAGE.lists.VALUE_LIST_ITERATOR; import speiger.src.collections.VALUE_PACKAGE.lists.VALUE_LIST_ITERATOR;
#endif #endif
#if !TYPE_OBJECT && !VALUE_OBJECT || !VALUE_OBJECT
import speiger.src.collections.objects.functions.consumer.ObjectObjectConsumer;
#endif
#if !TYPE_OBJECT || !VALUE_BOOLEAN
#if !VALUE_OBJECT || SAME_TYPE
import speiger.src.collections.objects.functions.function.Object2BooleanFunction;
#endif
#endif
#if !SAME_TYPE
#if !TYPE_OBJECT #if !TYPE_OBJECT
import speiger.src.collections.objects.functions.consumer.VALUE_BI_FROM_OBJECT_CONSUMER;
#endif
import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_PREDICATE;
#endif
#if !TYPE_OBJECT
#if !VALUE_OBJECT
import speiger.src.collections.objects.functions.function.ObjectObjectUnaryOperator;
#endif
import speiger.src.collections.objects.collections.ObjectBidirectionalIterator; import speiger.src.collections.objects.collections.ObjectBidirectionalIterator;
import speiger.src.collections.objects.lists.ObjectListIterator; import speiger.src.collections.objects.lists.ObjectListIterator;
import speiger.src.collections.objects.sets.AbstractObjectSet; import speiger.src.collections.objects.sets.AbstractObjectSet;
@@ -46,7 +73,7 @@ import speiger.src.collections.utils.HashUtil;
public class LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE extends HASH_MAP KEY_VALUE_GENERIC_TYPE implements SORTED_MAP KEY_VALUE_GENERIC_TYPE public class LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE extends HASH_MAP KEY_VALUE_GENERIC_TYPE implements SORTED_MAP KEY_VALUE_GENERIC_TYPE
{ {
/** The Backing array for links between nodes. Left 32 Bits => Previous Entry, Right 32 Bits => Next Entry */ /** The Backing array for links between nodes. Left 32 Bits => Previous Entry, Right 32 Bits => Next Entry */
protected long[] links; protected transient long[] links;
/** The First Index in the Map */ /** The First Index in the Map */
protected int firstIndex = -1; protected int firstIndex = -1;
/** The Last Index in the Map */ /** The Last Index in the Map */
@@ -296,6 +323,50 @@ public class LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE extends HASH_MAP KEY_VALUE_G
return values[index]; return values[index];
} }
#if !VALUE_OBJECT
@Override
public boolean containsValue(VALUE_TYPE value) {
int index = firstIndex;
while(index != -1) {
if(VALUE_EQUALS(values[index], value)) return true;
index = (int)links[index];
}
return false;
}
#endif
@Override
@ValuePrimitive
public boolean containsValue(Object value) {
int index = firstIndex;
while(index != -1) {
#if VALUE_OBJECT
if(VALUE_EQUALS(values[index], value)) return true;
#else
if((value == null && values[index] == getDefaultReturnValue()) || EQUALS_VALUE_TYPE(values[index], value)) return true;
#endif
index = (int)links[index];
}
return false;
}
@Override
public LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE copy() {
LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE map = new LINKED_HASH_MAPKV_BRACES(0, loadFactor);
map.minCapacity = minCapacity;
map.mask = mask;
map.maxFill = maxFill;
map.nullIndex = nullIndex;
map.containsNull = containsNull;
map.size = size;
map.keys = Arrays.copyOf(keys, keys.length);
map.values = Arrays.copyOf(values, values.length);
map.links = Arrays.copyOf(links, links.length);
map.firstIndex = firstIndex;
map.lastIndex = lastIndex;
return map;
}
@Override @Override
public COMPARATOR KEY_GENERIC_TYPE comparator() { public COMPARATOR KEY_GENERIC_TYPE comparator() {
return null; return null;
@@ -403,6 +474,24 @@ public class LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE extends HASH_MAP KEY_VALUE_G
firstIndex = lastIndex = -1; firstIndex = lastIndex = -1;
} }
@Override
public void clearAndTrim(int size) {
int request = Math.max(minCapacity, HashUtil.nextPowerOfTwo((int)Math.ceil(size / loadFactor)));
if(request >= size) {
clear();
return;
}
nullIndex = request;
mask = request-1;
maxFill = Math.min((int)Math.ceil(nullIndex * loadFactor), nullIndex - 1);
keys = NEW_KEY_ARRAY(request + 1);
values = NEW_VALUE_ARRAY(request + 1);
links = new long[request + 1];
firstIndex = lastIndex = -1;
this.size = 0;
containsNull = false;
}
protected void moveToFirstIndex(int startPos) { protected void moveToFirstIndex(int startPos) {
if(size == 1 || firstIndex == startPos) return; if(size == 1 || firstIndex == startPos) return;
if(lastIndex == startPos) { if(lastIndex == startPos) {
@@ -461,7 +550,7 @@ public class LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE extends HASH_MAP KEY_VALUE_G
} }
else if(lastIndex == pos) { else if(lastIndex == pos) {
lastIndex = (int)(links[pos] >>> 32); lastIndex = (int)(links[pos] >>> 32);
if(0 <= lastIndex) links[pos] |= 0xFFFFFFFFL; if(0 <= lastIndex) links[lastIndex] |= 0xFFFFFFFFL;
} }
else { else {
long link = links[pos]; long link = links[pos];
@@ -595,6 +684,9 @@ public class LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE extends HASH_MAP KEY_VALUE_G
return new FastEntryIterator(fromElement); return new FastEntryIterator(fromElement);
} }
@Override
public MapEntrySet copy() { throw new UnsupportedOperationException(); }
@Override @Override
public void forEach(Consumer<? super MAP.Entry KEY_VALUE_GENERIC_TYPE> action) { public void forEach(Consumer<? super MAP.Entry KEY_VALUE_GENERIC_TYPE> action) {
int index = firstIndex; int index = firstIndex;
@@ -615,12 +707,133 @@ public class LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE extends HASH_MAP KEY_VALUE_G
} }
} }
@Override
public <E> void forEach(E input, ObjectObjectConsumer<E, MAP.Entry KEY_VALUE_GENERIC_TYPE> action) {
Objects.requireNonNull(action);
if(size() <= 0) return;
int index = firstIndex;
while(index != -1) {
action.accept(input, new BasicEntryKV_BRACES(keys[index], values[index]));
index = (int)links[index];
}
}
@Override
public boolean matchesAny(Object2BooleanFunction<MAP.Entry KEY_VALUE_GENERIC_TYPE> filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return false;
BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES();
int index = firstIndex;
while(index != -1) {
entry.set(keys[index], values[index]);
if(filter.getBoolean(entry)) return true;
index = (int)links[index];
}
return false;
}
@Override
public boolean matchesNone(Object2BooleanFunction<MAP.Entry KEY_VALUE_GENERIC_TYPE> filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return true;
BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES();
int index = firstIndex;
while(index != -1) {
entry.set(keys[index], values[index]);
if(filter.getBoolean(entry)) return false;
index = (int)links[index];
}
return true;
}
@Override
public boolean matchesAll(Object2BooleanFunction<MAP.Entry KEY_VALUE_GENERIC_TYPE> filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return true;
BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES();
int index = firstIndex;
while(index != -1) {
entry.set(keys[index], values[index]);
if(!filter.getBoolean(entry)) return false;
index = (int)links[index];
}
return true;
}
@Override
public <E> E reduce(E identity, BiFunction<E, MAP.Entry KEY_VALUE_GENERIC_TYPE, E> operator) {
Objects.requireNonNull(operator);
E state = identity;
int index = firstIndex;
while(index != -1) {
state = operator.apply(state, new BasicEntryKV_BRACES(keys[index], values[index]));
index = (int)links[index];
}
return state;
}
@Override
public MAP.Entry KEY_VALUE_GENERIC_TYPE reduce(ObjectObjectUnaryOperator<MAP.Entry KEY_VALUE_GENERIC_TYPE, MAP.Entry KEY_VALUE_GENERIC_TYPE> operator) {
Objects.requireNonNull(operator);
MAP.Entry KEY_VALUE_GENERIC_TYPE state = null;
boolean empty = true;
int index = firstIndex;
while(index != -1) {
if(empty) {
empty = false;
state = new BasicEntryKV_BRACES(keys[index], values[index]);
index = (int)links[index];
continue;
}
state = operator.apply(state, new BasicEntryKV_BRACES(keys[index], values[index]));
index = (int)links[index];
}
return state;
}
@Override
public MAP.Entry KEY_VALUE_GENERIC_TYPE findFirst(Object2BooleanFunction<MAP.Entry KEY_VALUE_GENERIC_TYPE> filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return null;
BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES();
int index = firstIndex;
while(index != -1) {
entry.set(keys[index], values[index]);
if(filter.getBoolean(entry)) return entry;
index = (int)links[index];
}
return null;
}
@Override
public int count(Object2BooleanFunction<MAP.Entry KEY_VALUE_GENERIC_TYPE> filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return 0;
int result = 0;
BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES();
int index = firstIndex;
while(index != -1) {
entry.set(keys[index], values[index]);
if(filter.getBoolean(entry)) result++;
index = (int)links[index];
}
return result;
}
@Override @Override
@Deprecated @Deprecated
public boolean contains(Object o) { public boolean contains(Object o) {
if(o instanceof Map.Entry) { if(o instanceof Map.Entry) {
if(o instanceof MAP.Entry) return LINKED_HASH_MAP.this.containsKey(((MAP.Entry KEY_VALUE_GENERIC_TYPE)o).ENTRY_KEY()); if(o instanceof MAP.Entry) {
return LINKED_HASH_MAP.this.containsKey(((Map.Entry<?, ?>)o).getKey()); MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)o;
int index = LINKED_HASH_MAP.this.findIndex(entry.ENTRY_KEY());
if(index >= 0) return VALUE_EQUALS(entry.ENTRY_VALUE(), LINKED_HASH_MAP.this.values[index]);
}
else {
Map.Entry<?, ?> entry = (Map.Entry<?, ?>)o;
int index = LINKED_HASH_MAP.this.findIndex(entry.getKey());
if(index >= 0) return Objects.equals(entry.getValue(), VALUE_TO_OBJ(LINKED_HASH_MAP.this.values[index]));
}
} }
return false; return false;
} }
@@ -672,7 +885,7 @@ public class LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE extends HASH_MAP KEY_VALUE_G
@Override @Override
public boolean remove(Object o) { public boolean remove(Object o) {
int oldSize = size; int oldSize = size;
remove(o); LINKED_HASH_MAP.this.remove(o);
return size != oldSize; return size != oldSize;
} }
@@ -685,7 +898,7 @@ public class LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE extends HASH_MAP KEY_VALUE_G
@Override @Override
public boolean remove(KEY_TYPE o) { public boolean remove(KEY_TYPE o) {
int oldSize = size; int oldSize = size;
remove(o); LINKED_HASH_MAP.this.remove(o);
return size != oldSize; return size != oldSize;
} }
@@ -721,6 +934,9 @@ public class LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE extends HASH_MAP KEY_VALUE_G
return new KeyIterator(fromElement); return new KeyIterator(fromElement);
} }
@Override
public KeySet copy() { throw new UnsupportedOperationException(); }
@Override @Override
public int size() { public int size() {
return LINKED_HASH_MAP.this.size(); return LINKED_HASH_MAP.this.size();
@@ -751,17 +967,6 @@ public class LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE extends HASH_MAP KEY_VALUE_G
return POLL_LAST_ENTRY_KEY(); return POLL_LAST_ENTRY_KEY();
} }
#if TYPE_OBJECT
@Override
public void forEach(Consumer KEY_SUPER_GENERIC_TYPE action) {
int index = firstIndex;
while(index != -1){
action.accept(keys[index]);
index = (int)links[index];
}
}
#else
@Override @Override
public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) { public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) {
int index = firstIndex; int index = firstIndex;
@@ -771,7 +976,124 @@ public class LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE extends HASH_MAP KEY_VALUE_G
} }
} }
@Override
public <E> void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
if(size() <= 0) return;
int index = firstIndex;
while(index != -1){
action.accept(input, keys[index]);
index = (int)links[index];
}
}
@Override
public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return false;
int index = firstIndex;
while(index != -1){
if(filter.TEST_VALUE(keys[index])) return true;
index = (int)links[index];
}
return false;
}
@Override
public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return true;
int index = firstIndex;
while(index != -1){
if(filter.TEST_VALUE(keys[index])) return false;
index = (int)links[index];
}
return true;
}
@Override
public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return true;
int index = firstIndex;
while(index != -1) {
if(!filter.TEST_VALUE(keys[index])) return false;
index = (int)links[index];
}
return true;
}
#if !TYPE_OBJECT
@Override
public KEY_TYPE reduce(KEY_TYPE identity, SINGLE_UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
KEY_TYPE state = identity;
int index = firstIndex;
while(index != -1) {
state = operator.APPLY_KEY_VALUE(state, keys[index]);
index = (int)links[index];
}
return state;
}
#else
@Override
public <KEY_SPECIAL_TYPE> KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction<KEY_SPECIAL_TYPE, KEY_TYPE, KEY_SPECIAL_TYPE> operator) {
Objects.requireNonNull(operator);
KEY_SPECIAL_TYPE state = identity;
int index = firstIndex;
while(index != -1) {
state = operator.apply(state, keys[index]);
index = (int)links[index];
}
return state;
}
#endif #endif
@Override
public KEY_TYPE reduce(SINGLE_UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
KEY_TYPE state = EMPTY_KEY_VALUE;
boolean empty = true;
int index = firstIndex;
while(index != -1) {
if(empty) {
empty = false;
state = keys[index];
index = (int)links[index];
continue;
}
state = operator.APPLY_KEY_VALUE(state, keys[index]);
index = (int)links[index];
}
return state;
}
@Override
public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return EMPTY_KEY_VALUE;
int index = firstIndex;
while(index != -1){
if(filter.TEST_VALUE(keys[index])) return keys[index];
index = (int)links[index];
}
return EMPTY_KEY_VALUE;
}
@Override
public int count(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return 0;
int result = 0;
int index = firstIndex;
while(index != -1){
if(filter.TEST_VALUE(keys[index])) return result++;
index = (int)links[index];
}
return result;
}
@Override @Override
public COMPARATOR KEY_GENERIC_TYPE comparator() { return null; } public COMPARATOR KEY_GENERIC_TYPE comparator() { return null; }
@@ -820,25 +1142,133 @@ public class LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE extends HASH_MAP KEY_VALUE_G
LINKED_HASH_MAP.this.clear(); LINKED_HASH_MAP.this.clear();
} }
#if VALUE_OBJECT
@Override
public void forEach(Consumer VALUE_SUPER_GENERIC_TYPE action) {
int index = firstIndex;
while(index != -1){
action.accept(values[index]);
index = (int)links[index];
}
}
#else
@Override @Override
public void forEach(VALUE_CONSUMER VALUE_SUPER_GENERIC_TYPE action) { public void forEach(VALUE_CONSUMER VALUE_SUPER_GENERIC_TYPE action) {
Objects.requireNonNull(action);
int index = firstIndex; int index = firstIndex;
while(index != -1){ while(index != -1){
action.accept(values[index]); action.accept(values[index]);
index = (int)links[index]; index = (int)links[index];
} }
} }
@Override
public <E> void forEach(E input, VALUE_BI_FROM_OBJECT_CONSUMER VSV_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
if(size() <= 0) return;
int index = firstIndex;
while(index != -1){
action.accept(input, values[index]);
index = (int)links[index];
}
}
@Override
public boolean matchesAny(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return false;
int index = firstIndex;
while(index != -1){
if(filter.VALUE_TEST_VALUE(values[index])) return true;
index = (int)links[index];
}
return false;
}
@Override
public boolean matchesNone(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return true;
int index = firstIndex;
while(index != -1) {
if(filter.VALUE_TEST_VALUE(values[index])) return false;
index = (int)links[index];
}
return true;
}
@Override
public boolean matchesAll(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return true;
int index = firstIndex;
while(index != -1) {
if(!filter.VALUE_TEST_VALUE(values[index])) return false;
index = (int)links[index];
}
return true;
}
#if !VALUE_OBJECT
@Override
public VALUE_TYPE reduce(VALUE_TYPE identity, VALUE_SINGLE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
VALUE_TYPE state = identity;
int index = firstIndex;
while(index != -1) {
state = operator.APPLY_VALUE(state, values[index]);
index = (int)links[index];
}
return state;
}
#else
@Override
public <VALUE_SPECIAL_TYPE> VALUE_SPECIAL_TYPE reduce(VALUE_SPECIAL_TYPE identity, BiFunction<VALUE_SPECIAL_TYPE, VALUE_TYPE, VALUE_SPECIAL_TYPE> operator) {
Objects.requireNonNull(operator);
VALUE_SPECIAL_TYPE state = identity;
int index = firstIndex;
while(index != -1) {
state = operator.apply(state, values[index]);
index = (int)links[index];
}
return state;
}
#endif #endif
@Override
public VALUE_TYPE reduce(VALUE_SINGLE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
VALUE_TYPE state = EMPTY_VALUE;
boolean empty = true;
int index = firstIndex;
while(index != -1) {
if(empty) {
empty = false;
state = values[index];
index = (int)links[index];
continue;
}
state = operator.APPLY_VALUE(state, values[index]);
index = (int)links[index];
}
return state;
}
@Override
public VALUE_TYPE findFirst(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return EMPTY_VALUE;
int index = firstIndex;
while(index != -1){
if(filter.VALUE_TEST_VALUE(values[index])) return values[index];
index = (int)links[index];
}
return EMPTY_VALUE;
}
@Override
public int count(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return 0;
int result = 0;
int index = firstIndex;
while(index != -1){
if(filter.VALUE_TEST_VALUE(values[index])) result++;
index = (int)links[index];
}
return result;
}
} }
private class FastEntryIterator extends MapIterator implements ObjectListIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> { private class FastEntryIterator extends MapIterator implements ObjectListIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> {
@@ -956,8 +1386,8 @@ public class LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE extends HASH_MAP KEY_VALUE_G
MapIterator(KEY_TYPE from) { MapIterator(KEY_TYPE from) {
if(KEY_EQUALS_NULL(from)) { if(KEY_EQUALS_NULL(from)) {
if(containsNull) { if(containsNull) {
next = (int) links[nullIndex]; next = (int) links[nullIndex];
previous = nullIndex; previous = nullIndex;
} }
else throw new NoSuchElementException("The null element is not in the set"); else throw new NoSuchElementException("The null element is not in the set");
} }
@@ -1,34 +1,73 @@
package speiger.src.collections.PACKAGE.maps.impl.hash; package speiger.src.collections.PACKAGE.maps.impl.hash;
import java.util.Arrays; import java.util.Arrays;
import java.util.ConcurrentModificationException;
import java.util.Map; import java.util.Map;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import java.util.Objects; import java.util.Objects;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.function.BiFunction;
#if !TYPE_OBJECT #if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.collections.ITERATOR; import speiger.src.collections.PACKAGE.collections.ITERATOR;
import speiger.src.collections.PACKAGE.functions.CONSUMER; import speiger.src.collections.PACKAGE.functions.CONSUMER;
import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER;
#endif #endif
import speiger.src.collections.PACKAGE.functions.consumer.BI_CONSUMER; import speiger.src.collections.PACKAGE.functions.consumer.BI_CONSUMER;
import speiger.src.collections.PACKAGE.functions.function.FUNCTION;
import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR;
#if !SAME_TYPE
import speiger.src.collections.PACKAGE.functions.function.SINGLE_UNARY_OPERATOR;
#endif
#if !TYPE_OBJECT && !VALUE_BOOLEAN
import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
#endif
import speiger.src.collections.PACKAGE.lists.ARRAY_LIST; import speiger.src.collections.PACKAGE.lists.ARRAY_LIST;
import speiger.src.collections.PACKAGE.lists.LIST; import speiger.src.collections.PACKAGE.lists.LIST;
import speiger.src.collections.PACKAGE.maps.abstracts.ABSTRACT_MAP; import speiger.src.collections.PACKAGE.maps.abstracts.ABSTRACT_MAP;
import speiger.src.collections.PACKAGE.maps.interfaces.MAP; import speiger.src.collections.PACKAGE.maps.interfaces.MAP;
import speiger.src.collections.PACKAGE.utils.maps.MAPS;
#if !TYPE_OBJECT #if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.sets.ABSTRACT_SET; import speiger.src.collections.PACKAGE.sets.ABSTRACT_SET;
import speiger.src.collections.PACKAGE.sets.SET; import speiger.src.collections.PACKAGE.sets.SET;
#endif #endif
import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ABSTRACT_COLLECTION; import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ABSTRACT_COLLECTION;
import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_COLLECTION; import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_COLLECTION;
#if !SAME_TYPE && !VALUE_OBJECT import speiger.src.collections.VALUE_PACKAGE.functions.VALUE_SUPPLIER;
#if !SAME_TYPE
import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_UNARY_OPERATOR;
#if !VALUE_OBJECT
#if !TYPE_OBJECT
import speiger.src.collections.objects.functions.function.ObjectObjectUnaryOperator;
#endif
import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ITERATOR; import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ITERATOR;
import speiger.src.collections.VALUE_PACKAGE.functions.VALUE_CONSUMER; import speiger.src.collections.VALUE_PACKAGE.functions.VALUE_CONSUMER;
#endif #endif
#else if !VALUE_OBJECT
import speiger.src.collections.objects.functions.function.ObjectObjectUnaryOperator;
#endif
#if !TYPE_OBJECT && !VALUE_OBJECT || !VALUE_OBJECT
import speiger.src.collections.objects.functions.consumer.ObjectObjectConsumer;
#endif
#if !TYPE_OBJECT || !VALUE_BOOLEAN
#if !VALUE_OBJECT || SAME_TYPE
import speiger.src.collections.objects.functions.function.Object2BooleanFunction;
#endif
#endif
#if !SAME_TYPE
#if !TYPE_OBJECT
import speiger.src.collections.objects.functions.consumer.VALUE_BI_FROM_OBJECT_CONSUMER;
#endif
import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_PREDICATE;
#endif
import speiger.src.collections.objects.collections.ObjectIterator; import speiger.src.collections.objects.collections.ObjectIterator;
import speiger.src.collections.objects.sets.AbstractObjectSet; import speiger.src.collections.objects.sets.AbstractObjectSet;
import speiger.src.collections.objects.sets.ObjectSet; import speiger.src.collections.objects.sets.ObjectSet;
import speiger.src.collections.utils.HashUtil; import speiger.src.collections.utils.HashUtil;
import speiger.src.collections.utils.ITrimmable;
/** /**
* A Type Specific Custom implementation of the HashMap * A Type Specific Custom implementation of the HashMap
@@ -37,7 +76,7 @@ import speiger.src.collections.utils.HashUtil;
* @Type(T) * @Type(T)
* @ValueType(V) * @ValueType(V)
*/ */
public class HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE public class HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE implements ITrimmable
{ {
/** The Backing keys array */ /** The Backing keys array */
protected transient KEY_TYPE[] keys; protected transient KEY_TYPE[] keys;
@@ -231,7 +270,7 @@ public class HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENE
#endif #endif
@Override @Override
@Deprecated @Primitive
public boolean containsKey(Object key) { public boolean containsKey(Object key) {
return findIndex(key) >= 0; return findIndex(key) >= 0;
} }
@@ -239,31 +278,39 @@ public class HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENE
#if !VALUE_OBJECT #if !VALUE_OBJECT
@Override @Override
public boolean containsValue(VALUE_TYPE value) { public boolean containsValue(VALUE_TYPE value) {
if(VALUE_EQUALS(value, values[nullIndex])) return true; for(int i = nullIndex;i >= 0;i--)
for(int i = nullIndex-1;i >= 0;i--)
if(KEY_EQUALS_NOT_NULL(keys[i]) && VALUE_EQUALS(values[i], value)) return true; if(KEY_EQUALS_NOT_NULL(keys[i]) && VALUE_EQUALS(values[i], value)) return true;
return false; return false;
} }
#endif #endif
@Override @Override
@Deprecated @ValuePrimitive
public boolean containsValue(Object value) { public boolean containsValue(Object value) {
if((value == null && VALUE_EQUALS(values[nullIndex], getDefaultReturnValue())) || EQUALS_VALUE_TYPE(values[nullIndex], value)) return true; for(int i = nullIndex;i >= 0;i--)
for(int i = nullIndex-1;i >= 0;i--) #if VALUE_OBJECT
if(KEY_EQUALS_NOT_NULL(keys[i]) && EQUALS_VALUE_TYPE(values[i], value)) return true;
#else
if(KEY_EQUALS_NOT_NULL(keys[i]) && ((value == null && values[i] == getDefaultReturnValue()) || EQUALS_VALUE_TYPE(values[i], value))) return true; if(KEY_EQUALS_NOT_NULL(keys[i]) && ((value == null && values[i] == getDefaultReturnValue()) || EQUALS_VALUE_TYPE(values[i], value))) return true;
#endif
return false; return false;
} }
@Override @Override
public VALUE_TYPE REMOVE_KEY(KEY_TYPE key) { public VALUE_TYPE REMOVE_VALUE(KEY_TYPE key) {
int slot = findIndex(key); int slot = findIndex(key);
if(slot < 0) return getDefaultReturnValue(); if(slot < 0) return getDefaultReturnValue();
return removeIndex(slot); return removeIndex(slot);
} }
@Override @Override
@Deprecated public VALUE_TYPE REMOVE_VALUEOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) {
int slot = findIndex(key);
if(slot < 0) return defaultValue;
return removeIndex(slot);
}
@Override
public CLASS_VALUE_TYPE remove(Object key) { public CLASS_VALUE_TYPE remove(Object key) {
int slot = findIndex(key); int slot = findIndex(key);
if(slot < 0) return VALUE_TO_OBJ(getDefaultReturnValue()); if(slot < 0) return VALUE_TO_OBJ(getDefaultReturnValue());
@@ -350,6 +397,20 @@ public class HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENE
} }
#endif #endif
@Override
public HASH_MAP KEY_VALUE_GENERIC_TYPE copy() {
HASH_MAP KEY_VALUE_GENERIC_TYPE map = new HASH_MAPKV_BRACES(0, loadFactor);
map.minCapacity = minCapacity;
map.mask = mask;
map.maxFill = maxFill;
map.nullIndex = nullIndex;
map.containsNull = containsNull;
map.size = size;
map.keys = Arrays.copyOf(keys, keys.length);
map.values = Arrays.copyOf(values, values.length);
return map;
}
@Override @Override
public ObjectSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> ENTRY_SET() { public ObjectSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> ENTRY_SET() {
if(entrySet == null) entrySet = new MapEntrySet(); if(entrySet == null) entrySet = new MapEntrySet();
@@ -377,6 +438,127 @@ public class HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENE
} }
} }
@Override
public boolean replace(KEY_TYPE key, VALUE_TYPE oldValue, VALUE_TYPE newValue) {
int index = findIndex(key);
if(index < 0 || values[index] != oldValue) return false;
values[index] = newValue;
return true;
}
@Override
public VALUE_TYPE replace(KEY_TYPE key, VALUE_TYPE value) {
int index = findIndex(key);
if(index < 0) return getDefaultReturnValue();
VALUE_TYPE oldValue = values[index];
values[index] = value;
return oldValue;
}
@Override
public VALUE_TYPE COMPUTE(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) {
Objects.requireNonNull(mappingFunction);
int index = findIndex(key);
if(index < 0) {
VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, getDefaultReturnValue());
if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue;
insert(-index-1, key, newValue);
return newValue;
}
VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, values[index]);
if(VALUE_EQUALS(newValue, getDefaultReturnValue())) {
removeIndex(index);
return newValue;
}
values[index] = newValue;
return newValue;
}
@Override
public VALUE_TYPE COMPUTE_IF_ABSENT(KEY_TYPE key, FUNCTION KEY_VALUE_GENERIC_TYPE mappingFunction) {
Objects.requireNonNull(mappingFunction);
int index = findIndex(key);
if(index < 0) {
VALUE_TYPE newValue = mappingFunction.GET_VALUE(key);
if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue;
insert(-index-1, key, newValue);
return newValue;
}
VALUE_TYPE newValue = values[index];
if(VALUE_EQUALS(newValue, getDefaultReturnValue())) {
newValue = mappingFunction.GET_VALUE(key);
if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue;
values[index] = newValue;
}
return newValue;
}
@Override
public VALUE_TYPE SUPPLY_IF_ABSENT(KEY_TYPE key, VALUE_SUPPLIER VALUE_GENERIC_TYPE valueProvider) {
Objects.requireNonNull(valueProvider);
int index = findIndex(key);
if(index < 0) {
VALUE_TYPE newValue = valueProvider.VALUE_GET_KEY();
if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue;
insert(-index-1, key, newValue);
return newValue;
}
VALUE_TYPE newValue = values[index];
if(VALUE_EQUALS(newValue, getDefaultReturnValue())) {
newValue = valueProvider.VALUE_GET_KEY();
if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue;
values[index] = newValue;
}
return newValue;
}
@Override
public VALUE_TYPE COMPUTE_IF_PRESENT(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) {
Objects.requireNonNull(mappingFunction);
int index = findIndex(key);
if(index < 0 || VALUE_EQUALS(values[index], getDefaultReturnValue())) return getDefaultReturnValue();
VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, values[index]);
if(VALUE_EQUALS(newValue, getDefaultReturnValue())) {
removeIndex(index);
return newValue;
}
values[index] = newValue;
return newValue;
}
@Override
public VALUE_TYPE MERGE(KEY_TYPE key, VALUE_TYPE value, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) {
Objects.requireNonNull(mappingFunction);
#if VALUE_OBJECT
Objects.requireNonNull(value);
#endif
int index = findIndex(key);
VALUE_TYPE newValue = index < 0 || VALUE_EQUALS(values[index], getDefaultReturnValue()) ? value : mappingFunction.APPLY_VALUE(values[index], value);
if(VALUE_EQUALS(newValue, getDefaultReturnValue())) {
if(index >= 0)
removeIndex(index);
}
else if(index < 0) insert(-index-1, key, newValue);
else values[index] = newValue;
return newValue;
}
@Override
public void BULK_MERGE(MAP KEY_VALUE_GENERIC_TYPE m, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) {
Objects.requireNonNull(mappingFunction);
for(MAP.Entry KEY_VALUE_GENERIC_TYPE entry : MAPS.fastIterable(m)) {
KEY_TYPE key = entry.ENTRY_KEY();
int index = findIndex(key);
VALUE_TYPE newValue = index < 0 || VALUE_EQUALS(values[index], getDefaultReturnValue()) ? entry.ENTRY_VALUE() : mappingFunction.APPLY_VALUE(values[index], entry.ENTRY_VALUE());
if(VALUE_EQUALS(newValue, getDefaultReturnValue())) {
if(index >= 0)
removeIndex(index);
}
else if(index < 0) insert(-index-1, key, newValue);
else values[index] = newValue;
}
}
@Override @Override
public int size() { return size; } public int size() { return size; }
@@ -389,6 +571,33 @@ public class HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENE
Arrays.fill(values, EMPTY_VALUE); Arrays.fill(values, EMPTY_VALUE);
} }
@Override
public boolean trim(int size) {
int request = Math.max(minCapacity, HashUtil.nextPowerOfTwo((int)Math.ceil(size / loadFactor)));
if(request >= size || this.size > Math.min((int)Math.ceil(request * loadFactor), request - 1)) return false;
try {
rehash(request);
}
catch(OutOfMemoryError noMemory) { return false; }
return true;
}
@Override
public void clearAndTrim(int size) {
int request = Math.max(minCapacity, HashUtil.nextPowerOfTwo((int)Math.ceil(size / loadFactor)));
if(request >= size) {
clear();
return;
}
nullIndex = request;
mask = request-1;
maxFill = Math.min((int)Math.ceil(nullIndex * loadFactor), nullIndex - 1);
keys = NEW_KEY_ARRAY(request + 1);
values = NEW_VALUE_ARRAY(request + 1);
this.size = 0;
containsNull = false;
}
#if !TYPE_OBJECT #if !TYPE_OBJECT
protected int findIndex(KEY_TYPE key) { protected int findIndex(KEY_TYPE key) {
if(KEY_EQUALS_NULL(key)) return containsNull ? nullIndex : -(nullIndex + 1); if(KEY_EQUALS_NULL(key)) return containsNull ? nullIndex : -(nullIndex + 1);
@@ -416,7 +625,10 @@ public class HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENE
} }
protected VALUE_TYPE removeIndex(int pos) { protected VALUE_TYPE removeIndex(int pos) {
if(pos == nullIndex) return containsNull ? removeNullIndex() : getDefaultReturnValue();
VALUE_TYPE value = values[pos]; VALUE_TYPE value = values[pos];
keys[pos] = EMPTY_KEY_VALUE;
values[pos] = EMPTY_VALUE;
size--; size--;
onNodeRemoved(pos); onNodeRemoved(pos);
shiftKeys(pos); shiftKeys(pos);
@@ -448,7 +660,10 @@ public class HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENE
KEY_TYPE[] newKeys = NEW_KEY_ARRAY(newSize + 1); KEY_TYPE[] newKeys = NEW_KEY_ARRAY(newSize + 1);
VALUE_TYPE[] newValues = NEW_VALUE_ARRAY(newSize + 1); VALUE_TYPE[] newValues = NEW_VALUE_ARRAY(newSize + 1);
for(int i = nullIndex, pos = 0, j = (size - (containsNull ? 1 : 0));j-- != 0;) { for(int i = nullIndex, pos = 0, j = (size - (containsNull ? 1 : 0));j-- != 0;) {
while(KEY_EQUALS_NULL(keys[--i])); while(true) {
if(--i < 0) throw new ConcurrentModificationException("Map was modified during rehash");
if(KEY_EQUALS_NOT_NULL(keys[i])) break;
}
if(KEY_EQUALS_NOT_NULL(newKeys[pos = HashUtil.mix(KEY_TO_HASH(keys[i])) & newMask])) if(KEY_EQUALS_NOT_NULL(newKeys[pos = HashUtil.mix(KEY_TO_HASH(keys[i])) & newMask]))
while(KEY_EQUALS_NOT_NULL(newKeys[pos = (++pos & newMask)])); while(KEY_EQUALS_NOT_NULL(newKeys[pos = (++pos & newMask)]));
newKeys[pos] = keys[i]; newKeys[pos] = keys[i];
@@ -550,7 +765,7 @@ public class HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENE
@Override @Override
public String toString() { public String toString() {
return KEY_TO_STRING(keys[index]) + "->" + VALUE_TO_STRING(values[index]); return KEY_TO_STRING(keys[index]) + "=" + VALUE_TO_STRING(values[index]);
} }
} }
@@ -587,6 +802,140 @@ public class HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENE
} }
} }
@Override
public <E> void forEach(E input, ObjectObjectConsumer<E, MAP.Entry KEY_VALUE_GENERIC_TYPE> action) {
Objects.requireNonNull(action);
if(size() <= 0) return;
if(containsNull) action.accept(input, new BasicEntryKV_BRACES(keys[nullIndex], values[nullIndex]));
for(int i = nullIndex-1;i>=0;i--) {
if(KEY_EQUALS_NOT_NULL(keys[i])) action.accept(input, new BasicEntryKV_BRACES(keys[i], values[i]));
}
}
@Override
public boolean matchesAny(Object2BooleanFunction<MAP.Entry KEY_VALUE_GENERIC_TYPE> filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return false;
BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES();
if(containsNull) {
entry.set(keys[nullIndex], values[nullIndex]);
if(filter.getBoolean(entry)) return true;
}
for(int i = nullIndex-1;i>=0;i--) {
if(KEY_EQUALS_NOT_NULL(keys[i])) {
entry.set(keys[i], values[i]);
if(filter.getBoolean(entry)) return true;
}
}
return false;
}
@Override
public boolean matchesNone(Object2BooleanFunction<MAP.Entry KEY_VALUE_GENERIC_TYPE> filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return true;
BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES();
if(containsNull) {
entry.set(keys[nullIndex], values[nullIndex]);
if(filter.getBoolean(entry)) return false;
}
for(int i = nullIndex-1;i>=0;i--) {
if(KEY_EQUALS_NOT_NULL(keys[i])) {
entry.set(keys[i], values[i]);
if(filter.getBoolean(entry)) return false;
}
}
return true;
}
@Override
public boolean matchesAll(Object2BooleanFunction<MAP.Entry KEY_VALUE_GENERIC_TYPE> filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return true;
BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES();
if(containsNull) {
entry.set(keys[nullIndex], values[nullIndex]);
if(!filter.getBoolean(entry)) return false;
}
for(int i = nullIndex-1;i>=0;i--) {
if(KEY_EQUALS_NOT_NULL(keys[i])) {
entry.set(keys[i], values[i]);
if(!filter.getBoolean(entry)) return false;
}
}
return true;
}
@Override
public <E> E reduce(E identity, BiFunction<E, MAP.Entry KEY_VALUE_GENERIC_TYPE, E> operator) {
Objects.requireNonNull(operator);
E state = identity;
if(containsNull) state = operator.apply(state, new BasicEntryKV_BRACES(keys[nullIndex], values[nullIndex]));
for(int i = nullIndex-1;i>=0;i--) {
if(KEY_EQUALS_NULL(keys[i])) continue;
state = operator.apply(state, new BasicEntryKV_BRACES(keys[i], values[i]));
}
return state;
}
@Override
public MAP.Entry KEY_VALUE_GENERIC_TYPE reduce(ObjectObjectUnaryOperator<MAP.Entry KEY_VALUE_GENERIC_TYPE, MAP.Entry KEY_VALUE_GENERIC_TYPE> operator) {
Objects.requireNonNull(operator);
MAP.Entry KEY_VALUE_GENERIC_TYPE state = null;
boolean empty = true;
if(containsNull) {
state = new BasicEntryKV_BRACES(keys[nullIndex], values[nullIndex]);
empty = false;
}
for(int i = 0;i<size;i++) {
if(KEY_EQUALS_NULL(keys[i])) continue;
if(empty) {
empty = false;
state = new BasicEntryKV_BRACES(keys[i], values[i]);
continue;
}
state = operator.apply(state, new BasicEntryKV_BRACES(keys[i], values[i]));
}
return state;
}
@Override
public MAP.Entry KEY_VALUE_GENERIC_TYPE findFirst(Object2BooleanFunction<MAP.Entry KEY_VALUE_GENERIC_TYPE> filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return null;
BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES();
if(containsNull) {
entry.set(keys[nullIndex], values[nullIndex]);
if(filter.getBoolean(entry)) return entry;
}
for(int i = nullIndex-1;i>=0;i--) {
if(KEY_EQUALS_NOT_NULL(keys[i])) {
entry.set(keys[i], values[i]);
if(filter.getBoolean(entry)) return entry;
}
}
return null;
}
@Override
public int count(Object2BooleanFunction<MAP.Entry KEY_VALUE_GENERIC_TYPE> filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return 0;
BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES();
int result = 0;
if(containsNull) {
entry.set(keys[nullIndex], values[nullIndex]);
if(filter.getBoolean(entry)) result++;
}
for(int i = nullIndex-1;i>=0;i--) {
if(KEY_EQUALS_NOT_NULL(keys[i])) {
entry.set(keys[i], values[i]);
if(filter.getBoolean(entry)) result++;
}
}
return result;
}
@Override @Override
public int size() { public int size() {
return HASH_MAP.this.size(); return HASH_MAP.this.size();
@@ -600,8 +949,16 @@ public class HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENE
@Override @Override
public boolean contains(Object o) { public boolean contains(Object o) {
if(o instanceof Map.Entry) { if(o instanceof Map.Entry) {
if(o instanceof MAP.Entry) return HASH_MAP.this.containsKey(((MAP.Entry KEY_VALUE_GENERIC_TYPE)o).ENTRY_KEY()); if(o instanceof MAP.Entry) {
return HASH_MAP.this.containsKey(((Map.Entry<?, ?>)o).getKey()); MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)o;
int index = HASH_MAP.this.findIndex(entry.ENTRY_KEY());
if(index >= 0) return VALUE_EQUALS(entry.ENTRY_VALUE(), HASH_MAP.this.values[index]);
}
else {
Map.Entry<?, ?> entry = (Map.Entry<?, ?>)o;
int index = HASH_MAP.this.findIndex(entry.getKey());
if(index >= 0) return Objects.equals(entry.getValue(), VALUE_TO_OBJ(HASH_MAP.this.values[index]));
}
} }
return false; return false;
} }
@@ -630,7 +987,7 @@ public class HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENE
@Override @Override
public boolean remove(Object o) { public boolean remove(Object o) {
int oldSize = size; int oldSize = size;
remove(o); HASH_MAP.this.remove(o);
return size != oldSize; return size != oldSize;
} }
@@ -643,7 +1000,7 @@ public class HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENE
@Override @Override
public boolean remove(KEY_TYPE o) { public boolean remove(KEY_TYPE o) {
int oldSize = size; int oldSize = size;
remove(o); HASH_MAP.this.remove(o);
return size != oldSize; return size != oldSize;
} }
@@ -668,22 +1025,129 @@ public class HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENE
HASH_MAP.this.clear(); HASH_MAP.this.clear();
} }
#if TYPE_OBJECT
@Override @Override
public void forEach(Consumer KEY_SUPER_GENERIC_TYPE action) { public KeySet copy() { throw new UnsupportedOperationException(); }
if(containsNull) action.accept(keys[nullIndex]);
for(int i = nullIndex-1;i>=0;i--)
if(KEY_EQUALS_NOT_NULL(keys[i])) action.accept(keys[i]);
}
#else
@Override @Override
public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) { public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) {
if(containsNull) action.accept(keys[nullIndex]); if(containsNull) action.accept(keys[nullIndex]);
for(int i = nullIndex-1;i>=0;i--) for(int i = nullIndex-1;i>=0;i--)
if(KEY_EQUALS_NOT_NULL(keys[i])) action.accept(keys[i]); if(KEY_EQUALS_NOT_NULL(keys[i])) action.accept(keys[i]);
} }
@Override
public <E> void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
if(size() <= 0) return;
if(containsNull) action.accept(input, keys[nullIndex]);
for(int i = nullIndex-1;i>=0;i--) {
if(KEY_EQUALS_NOT_NULL(keys[i])) action.accept(input, keys[i]);
}
}
@Override
public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return false;
if(containsNull && filter.TEST_VALUE(keys[nullIndex])) return true;
for(int i = nullIndex-1;i>=0;i--) {
if(KEY_EQUALS_NOT_NULL(keys[i]) && filter.TEST_VALUE(keys[i])) return true;
}
return false;
}
@Override
public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return true;
if(containsNull && filter.TEST_VALUE(keys[nullIndex])) return false;
for(int i = nullIndex-1;i>=0;i--) {
if(KEY_EQUALS_NOT_NULL(keys[i]) && filter.TEST_VALUE(keys[i])) return false;
}
return true;
}
@Override
public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return true;
if(containsNull && !filter.TEST_VALUE(keys[nullIndex])) return false;
for(int i = nullIndex-1;i>=0;i--) {
if(KEY_EQUALS_NOT_NULL(keys[i]) && !filter.TEST_VALUE(keys[i])) return false;
}
return true;
}
#if !TYPE_OBJECT
@Override
public KEY_TYPE reduce(KEY_TYPE identity, SINGLE_UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
KEY_TYPE state = identity;
if(containsNull) state = operator.APPLY_KEY_VALUE(state, keys[nullIndex]);
for(int i = nullIndex-1;i>=0;i--) {
if(KEY_EQUALS_NULL(keys[i])) continue;
state = operator.APPLY_KEY_VALUE(state, keys[i]);
}
return state;
}
#else
@Override
public <KEY_SPECIAL_TYPE> KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction<KEY_SPECIAL_TYPE, KEY_TYPE, KEY_SPECIAL_TYPE> operator) {
Objects.requireNonNull(operator);
KEY_SPECIAL_TYPE state = identity;
if(containsNull) state = operator.apply(state, keys[nullIndex]);
for(int i = nullIndex-1;i>=0;i--) {
if(KEY_EQUALS_NULL(keys[i])) continue;
state = operator.apply(state, keys[i]);
}
return state;
}
#endif #endif
@Override
public KEY_TYPE reduce(SINGLE_UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
KEY_TYPE state = EMPTY_KEY_VALUE;
boolean empty = true;
if(containsNull) {
state = keys[nullIndex];
empty = false;
}
for(int i = 0;i<size;i++) {
if(KEY_EQUALS_NULL(keys[i])) continue;
if(empty) {
empty = false;
state = keys[i];
continue;
}
state = operator.APPLY_KEY_VALUE(state, keys[i]);
}
return state;
}
@Override
public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return EMPTY_KEY_VALUE;
if(containsNull && filter.TEST_VALUE(keys[nullIndex])) return keys[nullIndex];
for(int i = nullIndex-1;i>=0;i--) {
if(KEY_EQUALS_NOT_NULL(keys[i]) && filter.TEST_VALUE(keys[i])) return keys[i];
}
return EMPTY_KEY_VALUE;
}
@Override
public int count(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return 0;
int result = 0;
if(containsNull && filter.TEST_VALUE(keys[nullIndex])) result++;
for(int i = nullIndex-1;i>=0;i--) {
if(KEY_EQUALS_NOT_NULL(keys[i]) && filter.TEST_VALUE(keys[i])) result++;
}
return result;
}
} }
private class Values extends VALUE_ABSTRACT_COLLECTION VALUE_GENERIC_TYPE { private class Values extends VALUE_ABSTRACT_COLLECTION VALUE_GENERIC_TYPE {
@@ -720,21 +1184,126 @@ public class HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENE
HASH_MAP.this.clear(); HASH_MAP.this.clear();
} }
#if VALUE_OBJECT
@Override
public void forEach(Consumer VALUE_SUPER_GENERIC_TYPE action) {
if(containsNull) action.accept(values[nullIndex]);
for(int i = nullIndex-1;i>=0;i--)
if(KEY_EQUALS_NOT_NULL(keys[i])) action.accept(values[i]);
}
#else
@Override @Override
public void forEach(VALUE_CONSUMER VALUE_SUPER_GENERIC_TYPE action) { public void forEach(VALUE_CONSUMER VALUE_SUPER_GENERIC_TYPE action) {
if(containsNull) action.accept(values[nullIndex]); if(containsNull) action.accept(values[nullIndex]);
for(int i = nullIndex-1;i>=0;i--) for(int i = nullIndex-1;i>=0;i--)
if(KEY_EQUALS_NOT_NULL(keys[i])) action.accept(values[i]); if(KEY_EQUALS_NOT_NULL(keys[i])) action.accept(values[i]);
} }
@Override
public <E> void forEach(E input, VALUE_BI_FROM_OBJECT_CONSUMER VSV_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
if(size() <= 0) return;
if(containsNull) action.accept(input, values[nullIndex]);
for(int i = nullIndex-1;i>=0;i--) {
if(KEY_EQUALS_NOT_NULL(keys[i])) action.accept(input, values[i]);
}
}
@Override
public boolean matchesAny(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return false;
if(containsNull && filter.VALUE_TEST_VALUE(values[nullIndex])) return true;
for(int i = nullIndex-1;i>=0;i--) {
if(KEY_EQUALS_NOT_NULL(keys[i]) && filter.VALUE_TEST_VALUE(values[i])) return true;
}
return false;
}
@Override
public boolean matchesNone(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return true;
if(containsNull && filter.VALUE_TEST_VALUE(values[nullIndex])) return false;
for(int i = nullIndex-1;i>=0;i--) {
if(KEY_EQUALS_NOT_NULL(keys[i]) && filter.VALUE_TEST_VALUE(values[i])) return false;
}
return true;
}
@Override
public boolean matchesAll(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return true;
if(containsNull && !filter.VALUE_TEST_VALUE(values[nullIndex])) return false;
for(int i = nullIndex-1;i>=0;i--) {
if(KEY_EQUALS_NOT_NULL(keys[i]) && !filter.VALUE_TEST_VALUE(values[i])) return false;
}
return true;
}
#if !VALUE_OBJECT
@Override
public VALUE_TYPE reduce(VALUE_TYPE identity, VALUE_SINGLE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
VALUE_TYPE state = identity;
if(containsNull) state = operator.APPLY_VALUE(state, values[nullIndex]);
for(int i = nullIndex-1;i>=0;i--) {
if(KEY_EQUALS_NULL(keys[i])) continue;
state = operator.APPLY_VALUE(state, values[i]);
}
return state;
}
#else
@Override
public <VALUE_SPECIAL_TYPE> VALUE_SPECIAL_TYPE reduce(VALUE_SPECIAL_TYPE identity, BiFunction<VALUE_SPECIAL_TYPE, VALUE_TYPE, VALUE_SPECIAL_TYPE> operator) {
Objects.requireNonNull(operator);
VALUE_SPECIAL_TYPE state = identity;
if(containsNull) state = operator.APPLY_VALUE(state, values[nullIndex]);
for(int i = nullIndex-1;i>=0;i--) {
if(KEY_EQUALS_NULL(keys[i])) continue;
state = operator.APPLY_VALUE(state, values[i]);
}
return state;
}
#endif #endif
@Override
public VALUE_TYPE reduce(VALUE_SINGLE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
VALUE_TYPE state = EMPTY_VALUE;
boolean empty = true;
if(containsNull) {
state = values[nullIndex];
empty = false;
}
for(int i = 0;i<size;i++) {
if(KEY_EQUALS_NULL(keys[i])) continue;
if(empty) {
empty = false;
state = values[i];
continue;
}
state = operator.APPLY_VALUE(state, values[i]);
}
return state;
}
@Override
public VALUE_TYPE findFirst(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return EMPTY_VALUE;
if(containsNull && filter.VALUE_TEST_VALUE(values[nullIndex])) return values[nullIndex];
for(int i = nullIndex-1;i>=0;i--) {
if(KEY_EQUALS_NOT_NULL(keys[i]) && filter.VALUE_TEST_VALUE(values[i])) return values[i];
}
return EMPTY_VALUE;
}
@Override
public int count(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return 0;
int result = 0;
if(containsNull && filter.VALUE_TEST_VALUE(values[nullIndex])) result++;
for(int i = nullIndex-1;i>=0;i--) {
if(KEY_EQUALS_NOT_NULL(keys[i]) && filter.VALUE_TEST_VALUE(values[i])) result++;
}
return result;
}
} }
private class FastEntryIterator extends MapIterator implements ObjectIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> { private class FastEntryIterator extends MapIterator implements ObjectIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> {
@@ -776,6 +1345,7 @@ public class HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENE
private class MapIterator { private class MapIterator {
int pos = nullIndex; int pos = nullIndex;
int returnedPos = -1;
int lastReturned = -1; int lastReturned = -1;
int nextIndex = Integer.MIN_VALUE; int nextIndex = Integer.MIN_VALUE;
boolean returnNull = containsNull; boolean returnNull = containsNull;
@@ -807,6 +1377,7 @@ public class HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENE
public int nextEntry() { public int nextEntry() {
if(!hasNext()) throw new NoSuchElementException(); if(!hasNext()) throw new NoSuchElementException();
returnedPos = pos;
if(nextIndex < 0){ if(nextIndex < 0){
lastReturned = Integer.MAX_VALUE; lastReturned = Integer.MAX_VALUE;
int value = findIndex(wrapped.GET_KEY(nextIndex)); int value = findIndex(wrapped.GET_KEY(nextIndex));
@@ -826,9 +1397,10 @@ public class HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENE
keys[nullIndex] = EMPTY_KEY_VALUE; keys[nullIndex] = EMPTY_KEY_VALUE;
values[nullIndex] = EMPTY_VALUE; values[nullIndex] = EMPTY_VALUE;
} }
else if(pos >= 0) shiftKeys(pos); else if(returnedPos >= 0) shiftKeys(returnedPos);
else { else {
HASH_MAP.this.remove(wrapped.GET_KEY(-pos - 1)); HASH_MAP.this.remove(wrapped.GET_KEY(-returnedPos - 1));
lastReturned = -1;
return; return;
} }
size--; size--;
@@ -1,10 +1,9 @@
package speiger.src.collections.PACKAGE.maps.impl.misc; package speiger.src.collections.PACKAGE.maps.impl.misc;
import java.util.Arrays;
import java.util.Map; import java.util.Map;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
#if VALUE_OBJECT
import java.util.Objects; import java.util.Objects;
#endif
import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ABSTRACT_COLLECTION; import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ABSTRACT_COLLECTION;
import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_COLLECTION; import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_COLLECTION;
@@ -12,11 +11,18 @@ import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ITERATOR;
#if !VALUE_OBJECT #if !VALUE_OBJECT
import speiger.src.collections.objects.collections.ObjectIterator; import speiger.src.collections.objects.collections.ObjectIterator;
#endif #endif
import speiger.src.collections.VALUE_PACKAGE.functions.VALUE_SUPPLIER;
import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_UNARY_OPERATOR;
import speiger.src.collections.PACKAGE.functions.consumer.BI_CONSUMER;
#if !VALUE_OBJECT
import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR;
#endif
import speiger.src.collections.PACKAGE.functions.function.FUNCTION;
import speiger.src.collections.PACKAGE.utils.maps.MAPS;
import speiger.src.collections.objects.maps.abstracts.ABSTRACT_MAP; import speiger.src.collections.objects.maps.abstracts.ABSTRACT_MAP;
import speiger.src.collections.objects.maps.interfaces.MAP; import speiger.src.collections.objects.maps.interfaces.MAP;
import speiger.src.collections.objects.sets.AbstractObjectSet; import speiger.src.collections.objects.sets.AbstractObjectSet;
import speiger.src.collections.objects.sets.ObjectSet; import speiger.src.collections.objects.sets.ObjectSet;
import sun.misc.SharedSecrets;
/** /**
* A Type Specific EnumMap implementation that allows for Primitive Values. * A Type Specific EnumMap implementation that allows for Primitive Values.
@@ -28,26 +34,29 @@ import sun.misc.SharedSecrets;
public class ENUM_MAP KEY_ENUM_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE public class ENUM_MAP KEY_ENUM_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE
{ {
/** Enum Type that is being used */ /** Enum Type that is being used */
protected final Class<T> keyType; protected Class<T> keyType;
/** The Backing keys array. */ /** The Backing keys array. */
protected transient final T[] keys; protected transient T[] keys;
/** The Backing values array */ /** The Backing values array */
protected transient final VALUE_TYPE[] values; protected transient VALUE_TYPE[] values;
/** The Backing array that indicates which index is present or not */ /** The Backing array that indicates which index is present or not */
protected transient final long[] present; protected transient long[] present;
/** Amount of Elements stored in the ArrayMap */ /** Amount of Elements stored in the ArrayMap */
protected int size = 0; protected int size = 0;
/** EntrySet cache */ /** EntrySet cache */
protected transient ObjectSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> entrySet; protected transient ObjectSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> entrySet;
/** KeySet cache */ /** KeySet cache */
protected transient ObjectSet<T> keySet; protected transient ObjectSet<T> keySet;
/** Values cache */ /** Values cache */
protected transient VALUE_COLLECTION VALUE_GENERIC_TYPE valuesC; protected transient VALUE_COLLECTION VALUE_GENERIC_TYPE valuesC;
/** protected ENUM_MAP() {
* Default Constructor
* @param keyType the type of Enum that should be used }
*/ /**
* Default Constructor
* @param keyType the type of Enum that should be used
*/
public ENUM_MAP(Class<T> keyType) { public ENUM_MAP(Class<T> keyType) {
this.keyType = keyType; this.keyType = keyType;
keys = getKeyUniverse(keyType); keys = getKeyUniverse(keyType);
@@ -55,6 +64,86 @@ public class ENUM_MAP KEY_ENUM_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE
present = new long[((keys.length - 1) >> 6) + 1]; present = new long[((keys.length - 1) >> 6) + 1];
} }
#if !VALUE_OBJECT
/**
* Helper constructor that allow to create a EnumMap from boxed values (it will unbox them)
* @param keys the keys that should be put into the EnumMap
* @param values the values that should be put into the EnumMap.
* @throws IllegalStateException if the keys and values do not match in lenght
*/
public ENUM_MAP(T[] keys, CLASS_VALUE_TYPE[] values) {
if(keys.length <= 0) throw new IllegalArgumentException("Empty Array are not allowed");
if(keys.length != values.length) throw new IllegalArgumentException("Keys and Values have to be the same size");
keyType = keys[0].getDeclaringClass();
this.keys = getKeyUniverse(keyType);
this.values = NEW_VALUE_ARRAY(keys.length);
present = new long[((keys.length - 1) >> 6) + 1];
putAll(keys, values);
}
#endif
/**
* Helper constructor that allow to create a EnumMap from unboxed values
* @param keys the keys that should be put into the map
* @param values the values that should be put into the map.
* @throws IllegalStateException if the keys and values do not match in lenght
*/
public ENUM_MAP(T[] keys, VALUE_TYPE[] values) {
if(keys.length <= 0) throw new IllegalArgumentException("Empty Array are not allowed");
if(keys.length != values.length) throw new IllegalArgumentException("Keys and Values have to be the same size");
keyType = keys[0].getDeclaringClass();
this.keys = getKeyUniverse(keyType);
this.values = NEW_VALUE_ARRAY(keys.length);
present = new long[((keys.length - 1) >> 6) + 1];
putAll(keys, values);
}
/**
* A Helper constructor that allows to create a EnumMap with exactly the same values as the provided map.
* @param map the values that should be present in the map
*/
public ENUM_MAP(Map<? extends CLASS_TYPE, ? extends CLASS_VALUE_TYPE> map) {
if(map instanceof ENUM_MAP) {
ENUM_MAP KEY_VALUE_GENERIC_TYPE enumMap = (ENUM_MAP KEY_VALUE_GENERIC_TYPE)map;
keyType = enumMap.keyType;
keys = enumMap.keys;
values = enumMap.values.clone();
present = enumMap.present.clone();
size = enumMap.size;
}
else if(map.isEmpty()) throw new IllegalArgumentException("Empty Maps are not allowed");
else {
keyType = map.keySet().iterator().next().getDeclaringClass();
this.keys = getKeyUniverse(keyType);
this.values = NEW_VALUE_ARRAY(keys.length);
present = new long[((keys.length - 1) >> 6) + 1];
putAll(map);
}
}
/**
* A Type Specific Helper function that allows to create a new EnumMap with exactly the same values as the provided map.
* @param map the values that should be present in the map
*/
public ENUM_MAP(MAP KEY_VALUE_GENERIC_TYPE map) {
if(map instanceof ENUM_MAP) {
ENUM_MAP KEY_VALUE_GENERIC_TYPE enumMap = (ENUM_MAP KEY_VALUE_GENERIC_TYPE)map;
keyType = enumMap.keyType;
keys = enumMap.keys;
values = enumMap.values.clone();
present = enumMap.present.clone();
size = enumMap.size;
}
else if(map.isEmpty()) throw new IllegalArgumentException("Empty Maps are not allowed");
else {
keyType = map.keySet().iterator().next().getDeclaringClass();
this.keys = getKeyUniverse(keyType);
this.values = NEW_VALUE_ARRAY(keys.length);
present = new long[((keys.length - 1) >> 6) + 1];
putAll(map);
}
}
@Override @Override
public VALUE_TYPE put(T key, VALUE_TYPE value) { public VALUE_TYPE put(T key, VALUE_TYPE value) {
int index = key.ordinal(); int index = key.ordinal();
@@ -94,6 +183,7 @@ public class ENUM_MAP KEY_ENUM_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE
#endif #endif
@Override @Override
public boolean containsKey(Object key) { public boolean containsKey(Object key) {
if(!keyType.isInstance(key)) return false;
return isSet(((T)key).ordinal()); return isSet(((T)key).ordinal());
} }
@@ -101,7 +191,7 @@ public class ENUM_MAP KEY_ENUM_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE
@Override @Override
public boolean containsValue(Object value) { public boolean containsValue(Object value) {
for(int i = 0;i<values.length;i++) for(int i = 0;i<values.length;i++)
if(VALUE_EQUALS(value, values[i])) return true; if(isSet(i) && VALUE_EQUALS(value, values[i])) return true;
return false; return false;
} }
@@ -109,13 +199,25 @@ public class ENUM_MAP KEY_ENUM_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE
@Override @Override
public boolean containsValue(VALUE_TYPE value) { public boolean containsValue(VALUE_TYPE value) {
for(int i = 0;i<values.length;i++) for(int i = 0;i<values.length;i++)
if(VALUE_EQUALS(value, values[i])) return true; if(isSet(i) && VALUE_EQUALS(value, values[i])) return true;
return false; return false;
} }
#endif #endif
@Override
public CLASS_VALUE_TYPE remove(Object key) {
if(!keyType.isInstance(key)) return getDefaultReturnValue();
int index = ((T)key).ordinal();
if(!isSet(index)) return getDefaultReturnValue();
clear(index);
VALUE_TYPE result = values[index];
values[index] = EMPTY_VALUE;
return result;
}
@Override @Override
public VALUE_TYPE rem(T key) { public VALUE_TYPE rem(T key) {
if(!keyType.isInstance(key)) return getDefaultReturnValue();
int index = key.ordinal(); int index = key.ordinal();
if(!isSet(index)) return getDefaultReturnValue(); if(!isSet(index)) return getDefaultReturnValue();
clear(index); clear(index);
@@ -124,6 +226,16 @@ public class ENUM_MAP KEY_ENUM_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE
return result; return result;
} }
@Override
public VALUE_TYPE remOrDefault(T key, VALUE_TYPE defaultValue) {
int index = key.ordinal();
if(!isSet(index)) return defaultValue;
clear(index);
VALUE_TYPE result = values[index];
values[index] = EMPTY_VALUE;
return result;
}
#if VALUE_OBJECT #if VALUE_OBJECT
@Override @Override
public boolean remove(Object key, Object value) { public boolean remove(Object key, Object value) {
@@ -147,6 +259,7 @@ public class ENUM_MAP KEY_ENUM_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE
#endif #endif
@Override @Override
public VALUE_TYPE GET_VALUE(T key) { public VALUE_TYPE GET_VALUE(T key) {
if(!keyType.isInstance(key)) return getDefaultReturnValue();
int index = key.ordinal(); int index = key.ordinal();
return isSet(index) ? values[index] : getDefaultReturnValue(); return isSet(index) ? values[index] : getDefaultReturnValue();
} }
@@ -154,6 +267,7 @@ public class ENUM_MAP KEY_ENUM_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE
#if VALUE_OBJECT #if VALUE_OBJECT
@Override @Override
public VALUE_TYPE getOrDefault(Object key, VALUE_TYPE defaultValue) { public VALUE_TYPE getOrDefault(Object key, VALUE_TYPE defaultValue) {
if(!keyType.isInstance(key)) return defaultValue;
int index = ((T)key).ordinal(); int index = ((T)key).ordinal();
return isSet(index) ? values[index] : defaultValue; return isSet(index) ? values[index] : defaultValue;
} }
@@ -161,11 +275,21 @@ public class ENUM_MAP KEY_ENUM_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE
#else #else
@Override @Override
public VALUE_TYPE getOrDefault(T key, VALUE_TYPE defaultValue) { public VALUE_TYPE getOrDefault(T key, VALUE_TYPE defaultValue) {
if(!keyType.isInstance(key)) return defaultValue;
int index = key.ordinal(); int index = key.ordinal();
return isSet(index) ? values[index] : defaultValue; return isSet(index) ? values[index] : defaultValue;
} }
#endif #endif
@Override
public ENUM_MAP KEY_VALUE_GENERIC_TYPE copy() {
ENUM_MAP KEY_VALUE_GENERIC_TYPE map = new ENUM_MAPKV_BRACES(keyType);
map.size = size;
System.arraycopy(present, 0, map.present, 0, Math.min(present.length, map.present.length));
System.arraycopy(values, 0, map.values, 0, Math.min(values.length, map.values.length));
return map;
}
@Override @Override
public ObjectSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> ENTRY_SET() { public ObjectSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> ENTRY_SET() {
if(entrySet == null) entrySet = new EntrySet(); if(entrySet == null) entrySet = new EntrySet();
@@ -184,6 +308,158 @@ public class ENUM_MAP KEY_ENUM_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE
return valuesC; return valuesC;
} }
@Override
public void forEach(BI_CONSUMER KEY_VALUE_GENERIC_TYPE action) {
if(size() <= 0) return;
for(int i = 0,m=keys.length;i<m;i++) {
if(isSet(i)) action.accept(keys[i], values[i]);
}
}
@Override
public boolean replace(T key, VALUE_TYPE oldValue, VALUE_TYPE newValue) {
int index = key.ordinal();
if(!isSet(index) || values[index] != oldValue) return false;
values[index] = newValue;
return true;
}
@Override
public VALUE_TYPE replace(T key, VALUE_TYPE value) {
int index = key.ordinal();
if(!isSet(index)) return getDefaultReturnValue();
VALUE_TYPE oldValue = values[index];
values[index] = value;
return oldValue;
}
@Override
public VALUE_TYPE COMPUTE(T key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) {
int index = key.ordinal();
if(!isSet(index)) {
VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, getDefaultReturnValue());
if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue;
set(index);
values[index] = newValue;
return newValue;
}
VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, values[index]);
if(VALUE_EQUALS(newValue, getDefaultReturnValue())) {
clear(index);
values[index] = EMPTY_VALUE;
return newValue;
}
values[index] = newValue;
return newValue;
}
@Override
public VALUE_TYPE COMPUTE_IF_ABSENT(T key, FUNCTION KEY_VALUE_GENERIC_TYPE mappingFunction) {
int index = key.ordinal();
if(!isSet(index)) {
VALUE_TYPE newValue = mappingFunction.GET_VALUE(key);
if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue;
set(index);
values[index] = newValue;
return newValue;
}
VALUE_TYPE newValue = values[index];
if(VALUE_EQUALS(newValue, getDefaultReturnValue())) {
newValue = mappingFunction.GET_VALUE(key);
if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue;
values[index] = newValue;
}
return newValue;
}
@Override
public VALUE_TYPE SUPPLY_IF_ABSENT(T key, VALUE_SUPPLIER VALUE_GENERIC_TYPE valueProvider) {
int index = key.ordinal();
if(!isSet(index)) {
VALUE_TYPE newValue = valueProvider.VALUE_GET_KEY();
if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue;
set(index);
values[index] = newValue;
return newValue;
}
VALUE_TYPE newValue = values[index];
if(VALUE_EQUALS(newValue, getDefaultReturnValue())) {
newValue = valueProvider.VALUE_GET_KEY();
if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue;
values[index] = newValue;
}
return newValue;
}
@Override
public VALUE_TYPE COMPUTE_IF_PRESENT(T key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) {
int index = key.ordinal();
if(!isSet(index) || VALUE_EQUALS(values[index], getDefaultReturnValue())) return getDefaultReturnValue();
VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, values[index]);
if(VALUE_EQUALS(newValue, getDefaultReturnValue())) {
clear(index);
values[index] = EMPTY_VALUE;
return newValue;
}
values[index] = newValue;
return newValue;
}
@Override
public VALUE_TYPE MERGE(T key, VALUE_TYPE value, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) {
int index = key.ordinal();
#if VALUE_OBJECT
Objects.requireNonNull(value);
#endif
VALUE_TYPE newValue = !isSet(index) || VALUE_EQUALS(values[index], getDefaultReturnValue()) ? value : mappingFunction.APPLY_VALUE(values[index], value);
if(VALUE_EQUALS(newValue, getDefaultReturnValue())) {
if(isSet(index)) {
clear(index);
values[index] = EMPTY_VALUE;
}
}
else if(!isSet(index)) {
set(index);
values[index] = newValue;
}
else values[index] = newValue;
return newValue;
}
@Override
public void BULK_MERGE(MAP KEY_VALUE_GENERIC_TYPE m, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) {
Objects.requireNonNull(mappingFunction);
for(MAP.Entry KEY_VALUE_GENERIC_TYPE entry : MAPS.fastIterable(m)) {
T key = entry.ENTRY_KEY();
int index = key.ordinal();
VALUE_TYPE newValue = !isSet(index) || VALUE_EQUALS(values[index], getDefaultReturnValue()) ? entry.ENTRY_VALUE() : mappingFunction.APPLY_VALUE(values[index], entry.ENTRY_VALUE());
if(VALUE_EQUALS(newValue, getDefaultReturnValue())) {
if(isSet(index)) {
clear(index);
values[index] = EMPTY_VALUE;
}
}
else if(!isSet(index)) {
set(index);
values[index] = newValue;
}
else values[index] = newValue;
}
}
@Override
public void clear() {
if(size == 0) return;
size = 0;
Arrays.fill(present, 0L);
Arrays.fill(values, EMPTY_VALUE);
}
@Override
public int size() {
return size;
}
protected void onNodeAdded(int index) { protected void onNodeAdded(int index) {
} }
@@ -193,39 +469,54 @@ public class ENUM_MAP KEY_ENUM_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE
} }
protected void set(int index) { protected void set(int index) {
present[index >> 6] |= (1L << index);
onNodeAdded(index); onNodeAdded(index);
present[index >> 6] |= (1L << index);
size++;
} }
protected void clear(int index) { protected void clear(int index) {
size--;
present[index >> 6] &= ~(1L << index); present[index >> 6] &= ~(1L << index);
onNodeRemoved(index); onNodeRemoved(index);
} }
protected boolean isSet(int index) { return (present[index >> 6] & (1L << index)) != 0; } protected boolean isSet(int index) { return (present[index >> 6] & (1L << index)) != 0; }
private static <K extends Enum<K>> K[] getKeyUniverse(Class<K> keyType) {
// return keyType.getEnumConstants();
return SharedSecrets.getJavaLangAccess().getEnumConstantsShared(keyType);
}
class EntrySet extends AbstractObjectSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> { protected static <K extends Enum<K>> K[] getKeyUniverse(Class<K> keyType) {
return keyType.getEnumConstants();
}
@Override class EntrySet extends AbstractObjectSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> {
public boolean contains(Object o) {
if(o instanceof Map.Entry) return containsKey(((Map.Entry<?, ?>)o).getKey());
return false;
}
@Override @Override
public boolean remove(Object o) { public boolean contains(Object o) {
if(o instanceof Map.Entry) { if(o instanceof Map.Entry) {
if(o instanceof MAP.Entry) { if(o instanceof MAP.Entry) {
MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)o; MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)o;
return ENUM_MAP.this.remove(entry.getKey(), entry.ENTRY_VALUE()); if(!keyType.isInstance(entry.ENTRY_KEY())) return false;
} int index = ((T)entry.ENTRY_KEY()).ordinal();
Map.Entry<?, ?> entry = (java.util.Map.Entry<?, ?>)o; if(index >= 0 && ENUM_MAP.this.isSet(index)) return VALUE_EQUALS(entry.ENTRY_VALUE(), ENUM_MAP.this.values[index]);
return ENUM_MAP.this.remove(entry.getKey(), entry.getValue()); }
} else {
return false; Map.Entry<?, ?> entry = (Map.Entry<?, ?>)o;
} if(!keyType.isInstance(entry.getKey())) return false;
int index = ((T)entry.getKey()).ordinal();
if(index >= 0 && ENUM_MAP.this.isSet(index)) return Objects.equals(entry.getValue(), VALUE_TO_OBJ(ENUM_MAP.this.values[index]));
}
}
return false;
}
@Override
public boolean remove(Object o) {
if(o instanceof Map.Entry) {
if(o instanceof MAP.Entry) {
MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)o;
return ENUM_MAP.this.remove(entry.getKey(), entry.ENTRY_VALUE());
}
Map.Entry<?, ?> entry = (java.util.Map.Entry<?, ?>)o;
return ENUM_MAP.this.remove(entry.getKey(), entry.getValue());
}
return false;
}
@Override @Override
public ObjectIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> iterator() { public ObjectIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> iterator() {
@@ -241,21 +532,21 @@ public class ENUM_MAP KEY_ENUM_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE
public void clear() { public void clear() {
ENUM_MAP.this.clear(); ENUM_MAP.this.clear();
} }
} }
class KeySet extends AbstractObjectSet<T> { class KeySet extends AbstractObjectSet<T> {
@Override @Override
public boolean contains(Object o) { public boolean contains(Object o) {
return containsKey(o); return containsKey(o);
} }
@Override @Override
public boolean remove(Object o) { public boolean remove(Object o) {
int size = size(); int size = size();
ENUM_MAP.this.remove(o); ENUM_MAP.this.remove(o);
return size != size(); return size != size();
} }
@Override @Override
public ObjectIterator<T> iterator() { public ObjectIterator<T> iterator() {
@@ -271,9 +562,9 @@ public class ENUM_MAP KEY_ENUM_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE
public void clear() { public void clear() {
ENUM_MAP.this.clear(); ENUM_MAP.this.clear();
} }
} }
class Values extends VALUE_ABSTRACT_COLLECTION VALUE_GENERIC_TYPE { class Values extends VALUE_ABSTRACT_COLLECTION VALUE_GENERIC_TYPE {
@Override @Override
public boolean add(VALUE_TYPE o) { throw new UnsupportedOperationException(); } public boolean add(VALUE_TYPE o) { throw new UnsupportedOperationException(); }
@@ -301,34 +592,33 @@ public class ENUM_MAP KEY_ENUM_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE
public void clear() { public void clear() {
ENUM_MAP.this.clear(); ENUM_MAP.this.clear();
} }
} }
class EntryIterator extends MapIterator implements ObjectIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> { class EntryIterator extends MapIterator implements ObjectIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> {
@Override @Override
public MAP.Entry KEY_VALUE_GENERIC_TYPE next() { public MAP.Entry KEY_VALUE_GENERIC_TYPE next() {
int index = nextEntry(); return new MapEntry(nextEntry());
return new BasicEntry<>(keys[index], values[index]);
} }
} }
class KeyIterator extends MapIterator implements ObjectIterator<T> { class KeyIterator extends MapIterator implements ObjectIterator<T> {
@Override @Override
public T next() { public T next() {
return keys[nextEntry()]; return keys[nextEntry()];
} }
} }
class ValueIterator extends MapIterator implements VALUE_ITERATOR VALUE_GENERIC_TYPE { class ValueIterator extends MapIterator implements VALUE_ITERATOR VALUE_GENERIC_TYPE {
@Override @Override
public VALUE_TYPE VALUE_NEXT() { public VALUE_TYPE VALUE_NEXT() {
return values[nextEntry()]; return values[nextEntry()];
} }
} }
class MapIterator { class MapIterator {
int index; int index;
int lastReturnValue = -1; int lastReturnValue = -1;
int nextIndex = -1; int nextIndex = -1;
public boolean hasNext() { public boolean hasNext() {
if(nextIndex == -1 && index < values.length) { if(nextIndex == -1 && index < values.length) {
@@ -342,13 +632,74 @@ public class ENUM_MAP KEY_ENUM_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE
public int nextEntry() { public int nextEntry() {
if(!hasNext()) throw new NoSuchElementException(); if(!hasNext()) throw new NoSuchElementException();
lastReturnValue = nextIndex; lastReturnValue = nextIndex;
return nextIndex; nextIndex = -1;
return lastReturnValue;
} }
public void remove() { public void remove() {
if(lastReturnValue == -1) throw new IllegalStateException(); if(lastReturnValue == -1) throw new IllegalStateException();
clear(lastReturnValue); clear(lastReturnValue);
values[lastReturnValue] = EMPTY_VALUE; values[lastReturnValue] = EMPTY_VALUE;
lastReturnValue = -1;
} }
} }
protected class MapEntry implements MAP.Entry KEY_VALUE_GENERIC_TYPE, Map.Entry<CLASS_TYPE, CLASS_VALUE_TYPE> {
public int index = -1;
public MapEntry() {}
public MapEntry(int index) {
this.index = index;
}
@Override
public KEY_TYPE ENTRY_KEY() {
return keys[index];
}
@Override
public VALUE_TYPE ENTRY_VALUE() {
return values[index];
}
@Override
public VALUE_TYPE setValue(VALUE_TYPE value) {
VALUE_TYPE oldValue = values[index];
values[index] = value;
return oldValue;
}
@Override
public boolean equals(Object obj) {
if(obj instanceof Map.Entry) {
if(obj instanceof MAP.Entry) {
MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)obj;
return KEY_EQUALS(keys[index], entry.ENTRY_KEY()) && VALUE_EQUALS(values[index], entry.ENTRY_VALUE());
}
Map.Entry<?, ?> entry = (Map.Entry<?, ?>)obj;
Object key = entry.getKey();
Object value = entry.getValue();
#if TYPE_OBJECT && VALUE_OBJECT
return KEY_EQUALS(keys[index], key) && VALUE_EQUALS(values[index], value);
#else if TYPE_OBJECT
return value instanceof CLASS_VALUE_TYPE && KEY_EQUALS(keys[index], key) && VALUE_EQUALS(values[index], CLASS_TO_VALUE(value));
#else if VALUE_OBJECT
return key instanceof CLASS_TYPE && KEY_EQUALS(keys[index], CLASS_TO_KEY(key)) && VALUE_EQUALS(values[index], value);
#else
return key instanceof CLASS_TYPE && value instanceof CLASS_VALUE_TYPE && KEY_EQUALS(keys[index], CLASS_TO_KEY(key)) && VALUE_EQUALS(values[index], CLASS_TO_VALUE(value));
#endif
}
return false;
}
@Override
public int hashCode() {
return KEY_TO_HASH(keys[index]) ^ VALUE_TO_HASH(values[index]);
}
@Override
public String toString() {
return KEY_TO_STRING(keys[index]) + "=" + VALUE_TO_STRING(values[index]);
}
}
} }
@@ -2,6 +2,7 @@ package speiger.src.collections.PACKAGE.maps.interfaces;
import java.util.NavigableMap; import java.util.NavigableMap;
import speiger.src.collections.PACKAGE.sets.NAVIGABLE_SET; import speiger.src.collections.PACKAGE.sets.NAVIGABLE_SET;
import speiger.src.collections.PACKAGE.utils.maps.MAPS;
/** /**
* A Type Specific Navigable Map interface with a couple helper methods * A Type Specific Navigable Map interface with a couple helper methods
@@ -10,6 +11,8 @@ import speiger.src.collections.PACKAGE.sets.NAVIGABLE_SET;
*/ */
public interface NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE extends SORTED_MAP KEY_VALUE_GENERIC_TYPE, NavigableMap<CLASS_TYPE, CLASS_VALUE_TYPE> public interface NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE extends SORTED_MAP KEY_VALUE_GENERIC_TYPE, NavigableMap<CLASS_TYPE, CLASS_VALUE_TYPE>
{ {
@Override
public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE copy();
/** @return a Type Specific desendingMap */ /** @return a Type Specific desendingMap */
@Override @Override
public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE descendingMap(); public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE descendingMap();
@@ -32,6 +35,28 @@ public interface NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE extends SORTED_MAP KEY_VAL
@Override @Override
public MAP.Entry KEY_VALUE_GENERIC_TYPE pollLastEntry(); public MAP.Entry KEY_VALUE_GENERIC_TYPE pollLastEntry();
/**
* Creates a Wrapped NavigableMap that is Synchronized
* @return a new NavigableMap that is synchronized
* @see MAPS#synchronize
*/
public default NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE synchronize() { return MAPS.synchronize(this); }
/**
* Creates a Wrapped NavigableMap that is Synchronized
* @param mutex is the controller of the synchronization block
* @return a new NavigableMap Wrapper that is synchronized
* @see MAPS#synchronize
*/
public default NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE synchronize(Object mutex) { return MAPS.synchronize(this, mutex); }
/**
* Creates a Wrapped NavigableMap that is unmodifiable
* @return a new NavigableMap Wrapper that is unmodifiable
* @see MAPS#unmodifiable
*/
public default NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE unmodifiable() { return MAPS.unmodifiable(this); }
#if !TYPE_OBJECT #if !TYPE_OBJECT
/** /**
* A Type Specific SubMap method to reduce boxing/unboxing * A Type Specific SubMap method to reduce boxing/unboxing
@@ -10,6 +10,7 @@ import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_COLLECTION;
import speiger.src.collections.PACKAGE.functions.COMPARATOR; import speiger.src.collections.PACKAGE.functions.COMPARATOR;
#endif #endif
import speiger.src.collections.PACKAGE.sets.SET; import speiger.src.collections.PACKAGE.sets.SET;
import speiger.src.collections.PACKAGE.utils.maps.MAPS;
import speiger.src.collections.objects.sets.ObjectSortedSet; import speiger.src.collections.objects.sets.ObjectSortedSet;
import speiger.src.collections.objects.collections.ObjectBidirectionalIterator; import speiger.src.collections.objects.collections.ObjectBidirectionalIterator;
@@ -75,11 +76,36 @@ public interface SORTED_MAP KEY_VALUE_GENERIC_TYPE extends SortedMap<CLASS_TYPE,
@Override @Override
public COMPARATOR KEY_GENERIC_TYPE comparator(); public COMPARATOR KEY_GENERIC_TYPE comparator();
@Override
public SORTED_MAP KEY_VALUE_GENERIC_TYPE copy();
@Override @Override
public SET KEY_GENERIC_TYPE keySet(); public SET KEY_GENERIC_TYPE keySet();
@Override @Override
public VALUE_COLLECTION VALUE_GENERIC_TYPE values(); public VALUE_COLLECTION VALUE_GENERIC_TYPE values();
/**
* Creates a Wrapped SortedMap that is Synchronized
* @return a new SortedMap that is synchronized
* @see MAPS#synchronize
*/
public default SORTED_MAP KEY_VALUE_GENERIC_TYPE synchronize() { return MAPS.synchronize(this); }
/**
* Creates a Wrapped SortedMap that is Synchronized
* @param mutex is the controller of the synchronization block
* @return a new SortedMap Wrapper that is synchronized
* @see MAPS#synchronize
*/
public default SORTED_MAP KEY_VALUE_GENERIC_TYPE synchronize(Object mutex) { return MAPS.synchronize(this, mutex); }
/**
* Creates a Wrapped SortedMap that is unmodifiable
* @return a new SortedMap Wrapper that is unmodifiable
* @see MAPS#unmodifiable
*/
public default SORTED_MAP KEY_VALUE_GENERIC_TYPE unmodifiable() { return MAPS.unmodifiable(this); }
#if !TYPE_OBJECT #if !TYPE_OBJECT
/** /**
* A Type Specific SubMap method to reduce boxing/unboxing * A Type Specific SubMap method to reduce boxing/unboxing
@@ -0,0 +1,157 @@
package speiger.src.collections.PACKAGE.misc.pairs;
import speiger.src.collections.PACKAGE.misc.pairs.impl.IMMUTABLE_PAIR;
import speiger.src.collections.PACKAGE.misc.pairs.impl.MUTABLE_PAIR;
/**
* Key Value Pair Interface that allows to reduce boxing/unboxing.
* @Type(T)
* @ValueType(V)
*/
public interface PAIR KEY_VALUE_GENERIC_TYPE
{
/**
* Empty Reference for Immutable Pairs
*/
public static final PAIR NO_KV_GENERIC_TYPE EMPTY = new IMMUTABLE_PAIRKV_BRACES();
/**
* @Type(T)
* @ValueType(V)
* @return empty Immutable Pair
*/
public static GENERIC_KEY_VALUE_BRACES PAIR KEY_VALUE_GENERIC_TYPE of() {
#if TYPE_OBJECT || VALUE_OBJECT
return (PAIR KEY_VALUE_GENERIC_TYPE)EMPTY;
#else
return EMPTY;
#endif
}
/**
* @param key the key that should be in the pair
* @Type(T)
* @ValueType(V)
* @return Immutable Pair of Key
*/
public static GENERIC_KEY_VALUE_BRACES PAIR KEY_VALUE_GENERIC_TYPE ofKey(KEY_TYPE key) {
return new IMMUTABLE_PAIRKV_BRACES(key, EMPTY_VALUE);
}
/**
* @param value the value that should be in the pair
* @Type(T)
* @ValueType(V)
* @return Immutable Pair of Value
*/
public static GENERIC_KEY_VALUE_BRACES PAIR KEY_VALUE_GENERIC_TYPE ofValue(VALUE_TYPE value) {
return new IMMUTABLE_PAIRKV_BRACES(EMPTY_KEY_VALUE, value);
}
/**
* @param key the key that should be in the pair
* @param value the value that should be in the pair
* @Type(T)
* @ValueType(V)
* @return Immutable Pair of key and value
*/
public static GENERIC_KEY_VALUE_BRACES PAIR KEY_VALUE_GENERIC_TYPE of(KEY_TYPE key, VALUE_TYPE value) {
return new IMMUTABLE_PAIRKV_BRACES(key, value);
}
/**
* @param pair the Pair that should be immutably copied
* @Type(T)
* @ValueType(V)
* @return a Immutable Copy of the Provided Pair
*/
public static GENERIC_KEY_VALUE_BRACES PAIR KEY_VALUE_GENERIC_TYPE of(PAIR KEY_VALUE_GENERIC_TYPE pair) {
return new IMMUTABLE_PAIRKV_BRACES(pair.ENTRY_KEY(), pair.ENTRY_VALUE());
}
/**
* @Type(T)
* @ValueType(V)
* @return empty Mutable Pair
*/
public static GENERIC_KEY_VALUE_BRACES PAIR KEY_VALUE_GENERIC_TYPE mutable() {
return new MUTABLE_PAIRKV_BRACES();
}
/**
* @param key the key that should be in the pair
* @Type(T)
* @ValueType(V)
* @return Mutable Pair of key
*/
public static GENERIC_KEY_VALUE_BRACES PAIR KEY_VALUE_GENERIC_TYPE mutableKey(KEY_TYPE key) {
return new MUTABLE_PAIRKV_BRACES(key, EMPTY_VALUE);
}
/**
* @param value the value that should be in the pair
* @Type(T)
* @ValueType(V)
* @return Mutable Pair of value
*/
public static GENERIC_KEY_VALUE_BRACES PAIR KEY_VALUE_GENERIC_TYPE mutableValue(VALUE_TYPE value) {
return new MUTABLE_PAIRKV_BRACES(EMPTY_KEY_VALUE, value);
}
/**
* @param key the key that should be in the pair
* @param value the value that should be in the pair
* @Type(T)
* @ValueType(V)
* @return Mutable Pair of key and value
*/
public static GENERIC_KEY_VALUE_BRACES PAIR KEY_VALUE_GENERIC_TYPE mutable(KEY_TYPE key, VALUE_TYPE value) {
return new MUTABLE_PAIRKV_BRACES(key, value);
}
/**
* @param pair the Pair that should be copied
* @Type(T)
* @ValueType(V)
* @return a Mutable Copy of the Provided Pair
*/
public static GENERIC_KEY_VALUE_BRACES PAIR KEY_VALUE_GENERIC_TYPE mutable(PAIR KEY_VALUE_GENERIC_TYPE pair) {
return new MUTABLE_PAIRKV_BRACES(pair.ENTRY_KEY(), pair.ENTRY_VALUE());
}
/**
* Sets the Key of the Pair.
* @param key the key that should be set.
* @return self or a new Pair instance with the new key.
*/
public PAIR KEY_VALUE_GENERIC_TYPE KEY_ENTRY(KEY_TYPE key);
/**
* @return the Key of the Pair
*/
public KEY_TYPE ENTRY_KEY();
/**
* Sets the Value of the Pair.
* @param value the value that should be set.
* @return self or a new Pair instance with the new value.
*/
public PAIR KEY_VALUE_GENERIC_TYPE VALUE_ENTRY(VALUE_TYPE value);
/**
* @return the Value of the Pair
*/
public VALUE_TYPE ENTRY_VALUE();
/**
* Sets key and value of the Pair
* @param key the key that should be set.
* @param value the value that should be set.
* @return self or a new Pair instance with the new key and value.
*/
public PAIR KEY_VALUE_GENERIC_TYPE set(KEY_TYPE key, VALUE_TYPE value);
/**
* Clones the Pair if it is mutable.
* @return a New Mutable Instance if it is mutable
*/
public PAIR KEY_VALUE_GENERIC_TYPE shallowCopy();
}
@@ -0,0 +1,84 @@
package speiger.src.collections.PACKAGE.misc.pairs.impl;
#if TYPE_OBJECT || VALUE_OBJECT
import java.util.Objects;
#endif
import speiger.src.collections.PACKAGE.misc.pairs.PAIR;
/**
* Mutable Pair Implementation that
* @Type(T)
* @ValueType(V)
*/
public class IMMUTABLE_PAIR KEY_VALUE_GENERIC_TYPE implements PAIR KEY_VALUE_GENERIC_TYPE
{
protected final KEY_TYPE key;
protected final VALUE_TYPE value;
/**
* Default Constructor
*/
public IMMUTABLE_PAIR() {
this(EMPTY_KEY_VALUE, EMPTY_VALUE);
}
/**
* Key/Value Constructur
* @param key the key of the Pair
* @param value the value of the Pair
*/
public IMMUTABLE_PAIR(KEY_TYPE key, VALUE_TYPE value) {
this.key = key;
this.value = value;
}
@Override
public PAIR KEY_VALUE_GENERIC_TYPE KEY_ENTRY(KEY_TYPE key) {
return new IMMUTABLE_PAIRKV_BRACES(key, value);
}
@Override
public KEY_TYPE ENTRY_KEY() {
return key;
}
@Override
public PAIR KEY_VALUE_GENERIC_TYPE VALUE_ENTRY(VALUE_TYPE value) {
return new IMMUTABLE_PAIRKV_BRACES(key, value);
}
@Override
public VALUE_TYPE ENTRY_VALUE() {
return value;
}
@Override
public PAIR KEY_VALUE_GENERIC_TYPE set(KEY_TYPE key, VALUE_TYPE value) {
return new IMMUTABLE_PAIRKV_BRACES(key, value);
}
@Override
public PAIR KEY_VALUE_GENERIC_TYPE shallowCopy() {
return this;
}
@Override
public boolean equals(Object obj) {
if(obj instanceof PAIR) {
PAIR KEY_VALUE_GENERIC_TYPE entry = (PAIR KEY_VALUE_GENERIC_TYPE)obj;
return KEY_EQUALS(key, entry.ENTRY_KEY()) && VALUE_EQUALS(value, entry.ENTRY_VALUE());
}
return false;
}
@Override
public int hashCode() {
return KEY_TO_HASH(key) ^ VALUE_TO_HASH(value);
}
@Override
public String toString() {
return KEY_TO_STRING(key) + "->" + VALUE_TO_STRING(value);
}
}
@@ -0,0 +1,88 @@
package speiger.src.collections.PACKAGE.misc.pairs.impl;
#if TYPE_OBJECT || VALUE_OBJECT
import java.util.Objects;
#endif
import speiger.src.collections.PACKAGE.misc.pairs.PAIR;
/**
* Mutable Pair Implementation that
* @Type(T)
* @ValueType(V)
*/
public class MUTABLE_PAIR KEY_VALUE_GENERIC_TYPE implements PAIR KEY_VALUE_GENERIC_TYPE
{
protected KEY_TYPE key;
protected VALUE_TYPE value;
/**
* Default Constructor
*/
public MUTABLE_PAIR() {}
/**
* Key/Value Constructur
* @param key the key of the Pair
* @param value the value of the Pair
*/
public MUTABLE_PAIR(KEY_TYPE key, VALUE_TYPE value) {
this.key = key;
this.value = value;
}
@Override
public PAIR KEY_VALUE_GENERIC_TYPE KEY_ENTRY(KEY_TYPE key) {
this.key = key;
return this;
}
@Override
public KEY_TYPE ENTRY_KEY() {
return key;
}
@Override
public PAIR KEY_VALUE_GENERIC_TYPE VALUE_ENTRY(VALUE_TYPE value) {
this.value = value;
return this;
}
@Override
public VALUE_TYPE ENTRY_VALUE() {
return value;
}
@Override
public PAIR KEY_VALUE_GENERIC_TYPE set(KEY_TYPE key, VALUE_TYPE value) {
this.key = key;
this.value = value;
return this;
}
@Override
public PAIR KEY_VALUE_GENERIC_TYPE shallowCopy() {
return PAIR.mutable(key, value);
}
@Override
public boolean equals(Object obj) {
if(obj instanceof PAIR) {
PAIR KEY_VALUE_GENERIC_TYPE entry = (PAIR KEY_VALUE_GENERIC_TYPE)obj;
return KEY_EQUALS(key, entry.ENTRY_KEY()) && VALUE_EQUALS(value, entry.ENTRY_VALUE());
}
return false;
}
@Override
public int hashCode() {
return KEY_TO_HASH(key) ^ VALUE_TO_HASH(value);
}
@Override
public String toString() {
return KEY_TO_STRING(key) + "->" + VALUE_TO_STRING(value);
}
}
@@ -0,0 +1,46 @@
package speiger.src.collections.PACKAGE.queues;
#if TYPE_OBJECT
import java.util.Objects;
#endif
import java.util.StringJoiner;
/**
* Helper class that implements all the essential methods for the PriorityQueues
* @Type(T)
*/
public abstract class ABSTRACT_PRIORITY_QUEUE KEY_GENERIC_TYPE implements PRIORITY_QUEUE KEY_GENERIC_TYPE
{
@Override
public boolean equals(Object obj) {
if(obj instanceof PRIORITY_QUEUE) {
PRIORITY_QUEUE KEY_GENERIC_TYPE queue = (PRIORITY_QUEUE KEY_GENERIC_TYPE)obj;
if(queue.size() != size()) return false;
for(int i = 0,m=size();i<m;i++) {
if(KEY_EQUALS_NOT(queue.peek(i), peek(i))) return false;
}
return true;
}
return false;
}
@Override
public int hashCode() {
int result = 1;
for (int i = 0,m=size();i<m;i++) {
result = 31 * result + KEY_TO_HASH(peek(i));
}
return result;
}
@Override
public String toString()
{
if(isEmpty()) return "[]";
StringJoiner joiner = new StringJoiner(", ", "[", "]");
for (int i = 0,m=size();i<m;i++) {
joiner.add(KEY_TO_STRING(peek(i)));
}
return joiner.toString();
}
}
@@ -1,15 +1,22 @@
package speiger.src.collections.PACKAGE.queues; package speiger.src.collections.PACKAGE.queues;
#if TYPE_OBJECT
import java.util.Arrays; import java.util.Arrays;
#if TYPE_OBJECT
import java.util.Comparator; import java.util.Comparator;
import java.util.function.Consumer;
import java.util.function.BiFunction;
#endif #endif
import java.util.Objects;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import speiger.src.collections.PACKAGE.collections.ITERATOR; import speiger.src.collections.PACKAGE.collections.ITERATOR;
#if !TYPE_OBJECT #if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.functions.COMPARATOR; import speiger.src.collections.PACKAGE.functions.COMPARATOR;
import speiger.src.collections.PACKAGE.functions.CONSUMER;
#endif #endif
import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER;
import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR;
import speiger.src.collections.utils.ITrimmable; import speiger.src.collections.utils.ITrimmable;
/** /**
@@ -17,11 +24,11 @@ import speiger.src.collections.utils.ITrimmable;
* Its specific implementation uses a backing array that grows and shrinks as it is needed. * Its specific implementation uses a backing array that grows and shrinks as it is needed.
* @Type(T) * @Type(T)
*/ */
public class ARRAY_FIFO_QUEUE KEY_GENERIC_TYPE implements PRIORITY_DEQUEUE KEY_GENERIC_TYPE, ITrimmable public class ARRAY_FIFO_QUEUE KEY_GENERIC_TYPE extends ABSTRACT_PRIORITY_QUEUE KEY_GENERIC_TYPE implements PRIORITY_DEQUEUE KEY_GENERIC_TYPE, ITrimmable
{ {
/** Max Possible ArraySize without the JVM Crashing */ /** Max Possible ArraySize without the JVM Crashing */
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
/** The Minimum Capacity that is allowed */ /** The Minimum Capacity that is allowed */
public static final int MIN_CAPACITY = 4; public static final int MIN_CAPACITY = 4;
/** The Backing array */ /** The Backing array */
protected transient KEY_TYPE[] array; protected transient KEY_TYPE[] array;
@@ -29,6 +36,8 @@ public class ARRAY_FIFO_QUEUE KEY_GENERIC_TYPE implements PRIORITY_DEQUEUE KEY_G
protected int first; protected int first;
/** The Last Index pointer */ /** The Last Index pointer */
protected int last; protected int last;
/** The Minimum Capacity of the Queue **/
protected int minCapacity;
/** /**
* Constructor using a initial array * Constructor using a initial array
@@ -57,7 +66,9 @@ public class ARRAY_FIFO_QUEUE KEY_GENERIC_TYPE implements PRIORITY_DEQUEUE KEY_G
*/ */
public ARRAY_FIFO_QUEUE(KEY_TYPE[] values, int offset, int size) { public ARRAY_FIFO_QUEUE(KEY_TYPE[] values, int offset, int size) {
if (values.length < size) throw new IllegalArgumentException("Initial array (" + values.length + ") is smaller then the expected size (" + size + ")"); if (values.length < size) throw new IllegalArgumentException("Initial array (" + values.length + ") is smaller then the expected size (" + size + ")");
if(values.length <= 0) values = NEW_KEY_ARRAY(1); if(values.length <= 0) values = NEW_KEY_ARRAY(MIN_CAPACITY);
else if(values.length < MIN_CAPACITY) values = Arrays.copyOf(values, MIN_CAPACITY);
minCapacity = MIN_CAPACITY;
array = values; array = values;
first = offset; first = offset;
last = (offset + size) % array.length; last = (offset + size) % array.length;
@@ -71,7 +82,8 @@ public class ARRAY_FIFO_QUEUE KEY_GENERIC_TYPE implements PRIORITY_DEQUEUE KEY_G
*/ */
public ARRAY_FIFO_QUEUE(int capacity) { public ARRAY_FIFO_QUEUE(int capacity) {
if (capacity < 0) throw new IllegalArgumentException("Initial capacity (" + capacity + ") is negative"); if (capacity < 0) throw new IllegalArgumentException("Initial capacity (" + capacity + ") is negative");
array = NEW_KEY_ARRAY(Math.max(1, capacity)); array = NEW_KEY_ARRAY(Math.max(MIN_CAPACITY, capacity));
minCapacity = array.length;
} }
/** /**
@@ -101,21 +113,21 @@ public class ARRAY_FIFO_QUEUE KEY_GENERIC_TYPE implements PRIORITY_DEQUEUE KEY_G
} }
@Override @Override
public void ENQUEUE(KEY_TYPE e) { public void enqueue(KEY_TYPE e) {
array[last] = e; array[last] = e;
last = ++last % array.length; last = ++last % array.length;
if(last == first) expand(); if(last == first) expand();
} }
@Override @Override
public void ENQUEUE_FIRST(KEY_TYPE e) { public void enqueueFirst(KEY_TYPE e) {
if(first == 0) first = array.length; if(first == 0) first = array.length;
array[--first] = e; array[--first] = e;
if(first == last) expand(); if(first == last) expand();
} }
@Override @Override
public KEY_TYPE DEQUEUE() { public KEY_TYPE dequeue() {
if(first == last) throw new NoSuchElementException(); if(first == last) throw new NoSuchElementException();
KEY_TYPE data = array[first]; KEY_TYPE data = array[first];
#if TYPE_OBJECT #if TYPE_OBJECT
@@ -127,7 +139,7 @@ public class ARRAY_FIFO_QUEUE KEY_GENERIC_TYPE implements PRIORITY_DEQUEUE KEY_G
} }
@Override @Override
public KEY_TYPE DEQUEUE_LAST() { public KEY_TYPE dequeueLast() {
if(first == last) throw new NoSuchElementException(); if(first == last) throw new NoSuchElementException();
if(last == 0) last = array.length; if(last == 0) last = array.length;
KEY_TYPE data = array[--last]; KEY_TYPE data = array[--last];
@@ -139,13 +151,13 @@ public class ARRAY_FIFO_QUEUE KEY_GENERIC_TYPE implements PRIORITY_DEQUEUE KEY_G
} }
@Override @Override
public KEY_TYPE PEEK(int index) { public KEY_TYPE peek(int index) {
if(first == last || index < 0 || index > size()) throw new NoSuchElementException(); if(first == last || index < 0 || index > size()) throw new NoSuchElementException();
return array[(first + index) % array.length]; return array[(first + index) % array.length];
} }
@Override @Override
public boolean REMOVE(KEY_TYPE e) { public boolean removeFirst(KEY_TYPE e) {
if(first == last) return false; if(first == last) return false;
for(int i = 0,m=size();i<m;i++) { for(int i = 0,m=size();i<m;i++) {
int index = (first + i) % array.length; int index = (first + i) % array.length;
@@ -156,8 +168,7 @@ public class ARRAY_FIFO_QUEUE KEY_GENERIC_TYPE implements PRIORITY_DEQUEUE KEY_G
} }
@Override @Override
public boolean REMOVE_LAST(KEY_TYPE e) { public boolean removeLast(KEY_TYPE e) {
if(first == last) return false;
if(first == last) return false; if(first == last) return false;
for(int i = size()-1;i>=0;i--) { for(int i = size()-1;i>=0;i--) {
int index = (first + i) % array.length; int index = (first + i) % array.length;
@@ -218,12 +229,130 @@ public class ARRAY_FIFO_QUEUE KEY_GENERIC_TYPE implements PRIORITY_DEQUEUE KEY_G
@Override @Override
public void onChanged() {} public void onChanged() {}
@Override
public ARRAY_FIFO_QUEUE KEY_GENERIC_TYPE copy() {
ARRAY_FIFO_QUEUE KEY_GENERIC_TYPE queue = new ARRAY_FIFO_QUEUEBRACES();
queue.first = first;
queue.last = last;
queue.minCapacity = minCapacity;
queue.array = Arrays.copyOf(array, array.length);
return queue;
}
@Override @Override
public COMPARATOR KEY_SUPER_GENERIC_TYPE comparator() { return null; } public COMPARATOR KEY_SUPER_GENERIC_TYPE comparator() { return null; }
@Override
public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) {
Objects.requireNonNull(action);
if(first == last) return;
for(int i = 0,m=size();i<m;i++)
action.accept(array[(first + i) % array.length]);
clearAndTrim(0);
}
@Override
public <E> void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
if(first == last) return;
for(int i = 0,m=size();i<m;i++)
action.accept(input, array[(first + i) % array.length]);
clearAndTrim(0);
}
@Override
public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(int i = 0,m=size();i<m;i++) {
if(filter.TEST_VALUE(array[(first + i) % array.length])) return true;
}
return false;
}
@Override
public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(int i = 0,m=size();i<m;i++) {
if(filter.TEST_VALUE(array[(first + i) % array.length])) return false;
}
return true;
}
@Override
public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(int i = 0,m=size();i<m;i++) {
if(!filter.TEST_VALUE(array[(first + i) % array.length])) return false;
}
return true;
}
@Override
public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(int i = 0,m=size();i<m;i++) {
int index = (first + i) % array.length;
if(filter.TEST_VALUE(array[index])) {
KEY_TYPE data = array[index];
removeIndex(index);
return data;
}
}
return EMPTY_VALUE;
}
#if !TYPE_OBJECT
@Override
public KEY_TYPE reduce(KEY_TYPE identity, UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
KEY_TYPE state = identity;
for(int i = 0,m=size();i<m;i++) {
state = operator.APPLY_VALUE(state, array[(first + i) % array.length]);
}
return state;
}
#else
@Override
public <KEY_SPECIAL_TYPE> KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction<KEY_SPECIAL_TYPE, KEY_TYPE, KEY_SPECIAL_TYPE> operator) {
Objects.requireNonNull(operator);
KEY_SPECIAL_TYPE state = identity;
for(int i = 0,m=size();i<m;i++) {
state = operator.APPLY_VALUE(state, array[(first + i) % array.length]);
}
return state;
}
#endif
@Override
public KEY_TYPE reduce(UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
KEY_TYPE state = EMPTY_VALUE;
boolean empty = true;
for(int i = 0,m=size();i<m;i++) {
if(empty) {
empty = false;
state = array[(first + i) % array.length];
continue;
}
state = operator.APPLY_VALUE(state, array[(first + i) % array.length]);
}
return state;
}
@Override
public int count(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
int result = 0;
for(int i = 0,m=size();i<m;i++) {
if(filter.TEST_VALUE(array[(first + i) % array.length])) result++;
}
return result;
}
@Override @Override
public boolean trim(int size) { public boolean trim(int size) {
int newSize = Math.max(size, size()); int newSize = Math.max(Math.max(size, size()), minCapacity);
if(newSize >= array.length) return false; if(newSize >= array.length) return false;
KEY_TYPE[] newArray = NEW_KEY_ARRAY(newSize); KEY_TYPE[] newArray = NEW_KEY_ARRAY(newSize);
if(first <= last) System.arraycopy(array, first, newArray, 0, last - first); if(first <= last) System.arraycopy(array, first, newArray, 0, last - first);
@@ -237,9 +366,25 @@ public class ARRAY_FIFO_QUEUE KEY_GENERIC_TYPE implements PRIORITY_DEQUEUE KEY_G
return true; return true;
} }
/**
* Trims the collection down to the requested size and clears all elements while doing so
* @param size the amount of elements that should be allowed
* @note this will enforce minimum size of the collection itself
*/
@Override @Override
public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] input) { public void clearAndTrim(int size) {
if(input == null || input.length < size()) input = NEW_KEY_ARRAY(size()); int newSize = Math.max(minCapacity, size);
if(array.length <= newSize) {
clear();
return;
}
first = last = 0;
array = NEW_KEY_ARRAY(newSize);
}
@Override
public GENERIC_SPECIAL_KEY_BRACES<E> KEY_SPECIAL_TYPE[] TO_ARRAY(KEY_SPECIAL_TYPE[] input) {
if(input == null || input.length < size()) input = NEW_SPECIAL_KEY_ARRAY(size());
if (first <= last) System.arraycopy(array, first, input, 0, last - first); if (first <= last) System.arraycopy(array, first, input, 0, last - first);
else { else {
System.arraycopy(array, first, input, 0, array.length - first); System.arraycopy(array, first, input, 0, array.length - first);
@@ -248,28 +393,9 @@ public class ARRAY_FIFO_QUEUE KEY_GENERIC_TYPE implements PRIORITY_DEQUEUE KEY_G
return input; return input;
} }
#if !TYPE_OBJECT
@Override
public CLASS_TYPE[] toArray(CLASS_TYPE[] input) {
if(input == null || input.length < size()) input = NEW_CLASS_ARRAY(size());
if (first <= last) {
for(int i = 0,m=last-first;i<m;i++)
input[i] = KEY_TO_OBJ(array[first + i]);
}
else {
int offset = 0;
for(int i = 0,m=array.length-first;i<m;i++,offset++)
input[i] = KEY_TO_OBJ(array[first + i]);
for(int i = 0;i<last;i++)
input[offset+i] = KEY_TO_OBJ(array[i]);
}
return input;
}
#endif
protected void reduce() { protected void reduce() {
final int size = size(); final int size = size();
if (array.length > MIN_CAPACITY && size <= array.length / 4) resize(size, array.length / 2); if (array.length > minCapacity && size <= array.length / 4) resize(size, Math.max(array.length / 2, minCapacity));
} }
protected void expand() { protected void expand() {
@@ -4,14 +4,20 @@ import java.util.Arrays;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
#if TYPE_OBJECT #if TYPE_OBJECT
import java.util.Comparator; import java.util.Comparator;
import java.util.Objects; import java.util.function.Consumer;
import java.util.function.BiFunction;
#endif #endif
import java.util.Objects;
import speiger.src.collections.PACKAGE.collections.COLLECTION; import speiger.src.collections.PACKAGE.collections.COLLECTION;
import speiger.src.collections.PACKAGE.collections.ITERATOR; import speiger.src.collections.PACKAGE.collections.ITERATOR;
#if !TYPE_OBJECT #if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.functions.COMPARATOR; import speiger.src.collections.PACKAGE.functions.COMPARATOR;
import speiger.src.collections.PACKAGE.functions.CONSUMER;
#endif #endif
import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER;
import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR;
import speiger.src.collections.PACKAGE.utils.ARRAYS; import speiger.src.collections.PACKAGE.utils.ARRAYS;
/** /**
@@ -20,7 +26,7 @@ import speiger.src.collections.PACKAGE.utils.ARRAYS;
* It is highly suggested to use HeapPriorityQueue otherwise, unless you know why you need this specific implementation * It is highly suggested to use HeapPriorityQueue otherwise, unless you know why you need this specific implementation
* @Type(T) * @Type(T)
*/ */
public class ARRAY_PRIORITY_QUEUE KEY_GENERIC_TYPE implements PRIORITY_QUEUE KEY_GENERIC_TYPE public class ARRAY_PRIORITY_QUEUE KEY_GENERIC_TYPE extends ABSTRACT_PRIORITY_QUEUE KEY_GENERIC_TYPE
{ {
/** The Backing Array */ /** The Backing Array */
protected transient KEY_TYPE[] array = EMPTY_KEY_ARRAY; protected transient KEY_TYPE[] array = EMPTY_KEY_ARRAY;
@@ -180,7 +186,7 @@ public class ARRAY_PRIORITY_QUEUE KEY_GENERIC_TYPE implements PRIORITY_QUEUE KEY
} }
@Override @Override
public void ENQUEUE(KEY_TYPE e) { public void enqueue(KEY_TYPE e) {
if(size == array.length) array = Arrays.copyOf(array, size+1); if(size == array.length) array = Arrays.copyOf(array, size+1);
if(firstIndex != -1){ if(firstIndex != -1){
int compare = comparator == null ? COMPAREABLE_TO_KEY(e, array[firstIndex]) : comparator.compare(e, array[firstIndex]); int compare = comparator == null ? COMPAREABLE_TO_KEY(e, array[firstIndex]) : comparator.compare(e, array[firstIndex]);
@@ -191,7 +197,7 @@ public class ARRAY_PRIORITY_QUEUE KEY_GENERIC_TYPE implements PRIORITY_QUEUE KEY
} }
@Override @Override
public KEY_TYPE DEQUEUE() { public KEY_TYPE dequeue() {
if(size <= 0) throw new NoSuchElementException(); if(size <= 0) throw new NoSuchElementException();
int index = findFirstIndex(); int index = findFirstIndex();
KEY_TYPE value = array[index]; KEY_TYPE value = array[index];
@@ -204,20 +210,20 @@ public class ARRAY_PRIORITY_QUEUE KEY_GENERIC_TYPE implements PRIORITY_QUEUE KEY
} }
@Override @Override
public KEY_TYPE PEEK(int index) { public KEY_TYPE peek(int index) {
if(index < 0 || index >= size) throw new NoSuchElementException(); if(index < 0 || index >= size) throw new NoSuchElementException();
return array[index]; return array[index];
} }
@Override @Override
public boolean REMOVE(KEY_TYPE e) { public boolean removeFirst(KEY_TYPE e) {
for(int i = 0;i<size;i++) for(int i = 0;i<size;i++)
if(KEY_EQUALS(e, array[i])) return removeIndex(i); if(KEY_EQUALS(e, array[i])) return removeIndex(i);
return false; return false;
} }
@Override @Override
public boolean REMOVE_LAST(KEY_TYPE e) { public boolean removeLast(KEY_TYPE e) {
for(int i = size-1;i>=0;i--) for(int i = size-1;i>=0;i--)
if(KEY_EQUALS(e, array[i])) return removeIndex(i); if(KEY_EQUALS(e, array[i])) return removeIndex(i);
return false; return false;
@@ -251,32 +257,134 @@ public class ARRAY_PRIORITY_QUEUE KEY_GENERIC_TYPE implements PRIORITY_QUEUE KEY
size = 0; size = 0;
} }
@Override
public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) {
Objects.requireNonNull(action);
for(int i = 0,m=size;i<m;i++) action.accept(dequeue());
}
@Override
public <E> void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
for(int i = 0,m=size;i<m;i++) action.accept(input, dequeue());
}
@Override
public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(int i = 0;i<size;i++) {
if(filter.TEST_VALUE(array[i])) return true;
}
return false;
}
@Override
public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(int i = 0;i<size;i++) {
if(filter.TEST_VALUE(array[i])) return false;
}
return true;
}
@Override
public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(int i = 0;i<size;i++) {
if(!filter.TEST_VALUE(array[i])) return false;
}
return true;
}
#if !TYPE_OBJECT
@Override
public KEY_TYPE reduce(KEY_TYPE identity, UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
KEY_TYPE state = identity;
for(int i = 0;i<size;i++) {
state = operator.APPLY_VALUE(state, array[i]);
}
return state;
}
#else
@Override
public <KEY_SPECIAL_TYPE> KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction<KEY_SPECIAL_TYPE, KEY_TYPE, KEY_SPECIAL_TYPE> operator) {
Objects.requireNonNull(operator);
KEY_SPECIAL_TYPE state = identity;
for(int i = 0;i<size;i++) {
state = operator.APPLY_VALUE(state, array[i]);
}
return state;
}
#endif
@Override
public KEY_TYPE reduce(UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
KEY_TYPE state = EMPTY_VALUE;
boolean empty = true;
for(int i = 0;i<size;i++) {
if(empty) {
empty = false;
state = array[i];
continue;
}
state = operator.APPLY_VALUE(state, array[i]);
}
return state;
}
@Override
public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(int i = 0;i<size;i++) {
if(filter.TEST_VALUE(array[i])) {
KEY_TYPE data = array[i];
removeIndex(i);
return data;
}
}
return EMPTY_VALUE;
}
@Override
public int count(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
int result = 0;
for(int i = 0;i<size;i++) {
if(filter.TEST_VALUE(array[i])) result++;
}
return result;
}
@Override @Override
public ITERATOR KEY_GENERIC_TYPE iterator() { public ITERATOR KEY_GENERIC_TYPE iterator() {
return new Iter(); return new Iter();
} }
@Override
public ARRAY_PRIORITY_QUEUE KEY_GENERIC_TYPE copy() {
ARRAY_PRIORITY_QUEUE KEY_GENERIC_TYPE queue = new ARRAY_PRIORITY_QUEUEBRACES();
queue.firstIndex = firstIndex;
queue.size = size;
queue.comparator = comparator;
queue.array = Arrays.copyOf(array, array.length);
return queue;
}
@Override @Override
public COMPARATOR KEY_SUPER_GENERIC_TYPE comparator() { public COMPARATOR KEY_SUPER_GENERIC_TYPE comparator() {
return comparator; return comparator;
} }
@Override @Override
public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] input) { public GENERIC_SPECIAL_KEY_BRACES<E> KEY_SPECIAL_TYPE[] TO_ARRAY(KEY_SPECIAL_TYPE[] input) {
if(input == null || input.length < size()) input = NEW_KEY_ARRAY(size()); if(input == null || input.length < size()) input = NEW_SPECIAL_KEY_ARRAY(size());
System.arraycopy(array, 0, input, 0, size()); System.arraycopy(array, 0, input, 0, size());
return input; return input;
} }
#if !TYPE_OBJECT
@Override
public CLASS_TYPE[] toArray(CLASS_TYPE[] input) {
if(input == null || input.length < size()) input = new CLASS_TYPE[size()];
for(int i = 0;i<size;i++) input[i] = KEY_TO_OBJ(array[i]);
return input;
}
#endif
protected int findFirstIndex() { protected int findFirstIndex() {
if(firstIndex == -1) { if(firstIndex == -1) {
int index = size-1; int index = size-1;
@@ -306,7 +414,7 @@ public class ARRAY_PRIORITY_QUEUE KEY_GENERIC_TYPE implements PRIORITY_QUEUE KEY
@Override @Override
public KEY_TYPE NEXT() { public KEY_TYPE NEXT() {
return DEQUEUE(); return dequeue();
} }
} }
} }
@@ -4,14 +4,20 @@ import java.util.Arrays;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
#if TYPE_OBJECT #if TYPE_OBJECT
import java.util.Comparator; import java.util.Comparator;
import java.util.Objects; import java.util.function.Consumer;
import java.util.function.BiFunction;
#endif #endif
import java.util.Objects;
import speiger.src.collections.PACKAGE.collections.COLLECTION; import speiger.src.collections.PACKAGE.collections.COLLECTION;
import speiger.src.collections.PACKAGE.collections.ITERATOR; import speiger.src.collections.PACKAGE.collections.ITERATOR;
#if !TYPE_OBJECT #if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.functions.COMPARATOR; import speiger.src.collections.PACKAGE.functions.COMPARATOR;
import speiger.src.collections.PACKAGE.functions.CONSUMER;
#endif #endif
import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER;
import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR;
import speiger.src.collections.PACKAGE.utils.ARRAYS; import speiger.src.collections.PACKAGE.utils.ARRAYS;
/** /**
@@ -19,7 +25,7 @@ import speiger.src.collections.PACKAGE.utils.ARRAYS;
* It is a ArrayBased Alternative to TreeSets that has less object allocations * It is a ArrayBased Alternative to TreeSets that has less object allocations
* @Type(T) * @Type(T)
*/ */
public class HEAP_PRIORITY_QUEUE KEY_GENERIC_TYPE implements PRIORITY_QUEUE KEY_GENERIC_TYPE public class HEAP_PRIORITY_QUEUE KEY_GENERIC_TYPE extends ABSTRACT_PRIORITY_QUEUE KEY_GENERIC_TYPE
{ {
/** The Backing Array */ /** The Backing Array */
protected transient KEY_TYPE[] array = EMPTY_KEY_ARRAY; protected transient KEY_TYPE[] array = EMPTY_KEY_ARRAY;
@@ -200,14 +206,14 @@ public class HEAP_PRIORITY_QUEUE KEY_GENERIC_TYPE implements PRIORITY_QUEUE KEY_
} }
@Override @Override
public void ENQUEUE(KEY_TYPE e) { public void enqueue(KEY_TYPE e) {
if(size == array.length) array = Arrays.copyOf(array, size + 1); if(size == array.length) array = Arrays.copyOf(array, size + 1);
array[size++] = e; array[size++] = e;
ARRAYS.shiftUp(array, size-1, comparator); ARRAYS.shiftUp(array, size-1, comparator);
} }
@Override @Override
public KEY_TYPE DEQUEUE() { public KEY_TYPE dequeue() {
if(size <= 0) throw new NoSuchElementException(); if(size <= 0) throw new NoSuchElementException();
KEY_TYPE value = array[0]; KEY_TYPE value = array[0];
array[0] = array[--size]; array[0] = array[--size];
@@ -219,25 +225,126 @@ public class HEAP_PRIORITY_QUEUE KEY_GENERIC_TYPE implements PRIORITY_QUEUE KEY_
} }
@Override @Override
public KEY_TYPE PEEK(int index) { public KEY_TYPE peek(int index) {
if(index < 0 || index >= size) throw new NoSuchElementException(); if(index < 0 || index >= size) throw new NoSuchElementException();
return array[index]; return array[index];
} }
@Override @Override
public boolean REMOVE(KEY_TYPE e) { public boolean removeFirst(KEY_TYPE e) {
for(int i = 0;i<size;i++) for(int i = 0;i<size;i++)
if(KEY_EQUALS(e, array[i])) return removeIndex(i); if(KEY_EQUALS(e, array[i])) return removeIndex(i);
return false; return false;
} }
@Override @Override
public boolean REMOVE_LAST(KEY_TYPE e) { public boolean removeLast(KEY_TYPE e) {
for(int i = size-1;i>=0;i--) for(int i = size-1;i>=0;i--)
if(KEY_EQUALS(e, array[i])) return removeIndex(i); if(KEY_EQUALS(e, array[i])) return removeIndex(i);
return false; return false;
} }
@Override
public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) {
Objects.requireNonNull(action);
for(int i = 0,m=size;i<m;i++) action.accept(dequeue());
}
@Override
public <E> void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
for(int i = 0,m=size;i<m;i++) action.accept(input, dequeue());
}
@Override
public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(int i = 0;i<size;i++) {
if(filter.TEST_VALUE(array[i])) return true;
}
return false;
}
@Override
public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(int i = 0;i<size;i++) {
if(filter.TEST_VALUE(array[i])) return false;
}
return true;
}
@Override
public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(int i = 0;i<size;i++) {
if(!filter.TEST_VALUE(array[i])) return false;
}
return true;
}
#if !TYPE_OBJECT
@Override
public KEY_TYPE reduce(KEY_TYPE identity, UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
KEY_TYPE state = identity;
for(int i = 0;i<size;i++) {
state = operator.APPLY_VALUE(state, array[i]);
}
return state;
}
#else
@Override
public <KEY_SPECIAL_TYPE> KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction<KEY_SPECIAL_TYPE, KEY_TYPE, KEY_SPECIAL_TYPE> operator) {
Objects.requireNonNull(operator);
KEY_SPECIAL_TYPE state = identity;
for(int i = 0;i<size;i++) {
state = operator.APPLY_VALUE(state, array[i]);
}
return state;
}
#endif
@Override
public KEY_TYPE reduce(UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
KEY_TYPE state = EMPTY_VALUE;
boolean empty = true;
for(int i = 0;i<size;i++) {
if(empty) {
empty = false;
state = array[i];
continue;
}
state = operator.APPLY_VALUE(state, array[i]);
}
return state;
}
@Override
public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(int i = 0;i<size;i++) {
if(filter.TEST_VALUE(array[i])) {
KEY_TYPE data = array[i];
removeIndex(i);
return data;
}
}
return EMPTY_VALUE;
}
@Override
public int count(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
int result = 0;
for(int i = 0;i<size;i++) {
if(filter.TEST_VALUE(array[i])) result++;
}
return result;
}
protected boolean removeIndex(int index) { protected boolean removeIndex(int index) {
array[index] = array[--size]; array[index] = array[--size];
#if TYPE_OBJECT #if TYPE_OBJECT
@@ -253,27 +360,27 @@ public class HEAP_PRIORITY_QUEUE KEY_GENERIC_TYPE implements PRIORITY_QUEUE KEY_
ARRAYS.shiftDown(array, size, 0, comparator); ARRAYS.shiftDown(array, size, 0, comparator);
} }
@Override
public HEAP_PRIORITY_QUEUE KEY_GENERIC_TYPE copy() {
HEAP_PRIORITY_QUEUE KEY_GENERIC_TYPE queue = new HEAP_PRIORITY_QUEUEBRACES();
queue.size = size;
queue.comparator = comparator;
queue.array = Arrays.copyOf(array, array.length);
return queue;
}
@Override @Override
public COMPARATOR KEY_SUPER_GENERIC_TYPE comparator() { public COMPARATOR KEY_SUPER_GENERIC_TYPE comparator() {
return comparator; return comparator;
} }
@Override @Override
public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] input) { public GENERIC_SPECIAL_KEY_BRACES<E> KEY_SPECIAL_TYPE[] TO_ARRAY(KEY_SPECIAL_TYPE[] input) {
if(input == null || input.length < size()) input = NEW_KEY_ARRAY(size()); if(input == null || input.length < size()) input = NEW_SPECIAL_KEY_ARRAY(size());
System.arraycopy(array, 0, input, 0, size()); System.arraycopy(array, 0, input, 0, size());
return input; return input;
} }
#if !TYPE_OBJECT
@Override
public CLASS_TYPE[] toArray(CLASS_TYPE[] input) {
if(input == null || input.length < size()) input = new CLASS_TYPE[size()];
for(int i = 0;i<size;i++) input[i] = KEY_TO_OBJ(array[i]);
return input;
}
#endif
private class Iter implements ITERATOR KEY_GENERIC_TYPE { private class Iter implements ITERATOR KEY_GENERIC_TYPE {
@Override @Override
public boolean hasNext() { public boolean hasNext() {
@@ -282,7 +389,7 @@ public class HEAP_PRIORITY_QUEUE KEY_GENERIC_TYPE implements PRIORITY_QUEUE KEY_
@Override @Override
public KEY_TYPE NEXT() { public KEY_TYPE NEXT() {
return DEQUEUE(); return dequeue();
} }
} }
} }
@@ -1,5 +1,13 @@
package speiger.src.collections.PACKAGE.queues; package speiger.src.collections.PACKAGE.queues;
#if TYPE_OBJECT
import java.util.Collection;
import java.util.Iterator;
#endif
import speiger.src.collections.PACKAGE.collections.COLLECTION;
import speiger.src.collections.PACKAGE.collections.ITERATOR;
import speiger.src.collections.PACKAGE.utils.PRIORITY_QUEUES;
/** /**
* A Type Speciifc PriorityDeque or Dequeue interface to allow implementations like FIFO queues. * A Type Speciifc PriorityDeque or Dequeue interface to allow implementations like FIFO queues.
* @Type(T) * @Type(T)
@@ -10,39 +18,84 @@ public interface PRIORITY_DEQUEUE KEY_GENERIC_TYPE extends PRIORITY_QUEUE KEY_GE
* Method to insert a element into the first Index instead of the last. * Method to insert a element into the first Index instead of the last.
* @param e the element that should be inserted into the first place * @param e the element that should be inserted into the first place
*/ */
public void ENQUEUE_FIRST(KEY_TYPE e); public void enqueueFirst(KEY_TYPE e);
/**
* Method to mass insert a elements into the first Index of the PriorityDequeue.
* @param e the elements that should be inserted
*/
public default void enqueueAllFirst(KEY_TYPE... e) {
enqueueAllFirst(e, 0, e.length);
}
/**
* Method to mass insert a elements into the first Index of the PriorityDequeue.
* @param e the elements that should be inserted
* @param length the amount of elements that should be inserted
*/
public default void enqueueAllFirst(KEY_TYPE[] e, int length) {
enqueueAllFirst(e, 0, length);
}
/**
* Method to mass insert a elements into the first Index of the PriorityDequeue.
* @param e the elements that should be inserted
* @param offset the offset where in the array should be started
* @param length the amount of elements that should be inserted
*/
public default void enqueueAllFirst(KEY_TYPE[] e, int offset, int length) {
for(int i = 0;i<length;i++)
enqueueFirst(e[i+offset]);
}
/**
* Method to mass insert elements into first Index of the PriorityDequeue.
* @param c the elements that should be inserted from the Collection
*/
public default void enqueueAllFirst(COLLECTION KEY_GENERIC_TYPE c) {
for(ITERATOR KEY_GENERIC_TYPE iter = c.iterator();iter.hasNext();)
enqueueFirst(iter.NEXT());
}
#if TYPE_OBJECT
/**
* Method to mass insert elements into first Index of the PriorityDequeue.
* This method exists to add support for Java Collections to make it more useable
* @param c the elements that should be inserted from the Collection
*/
public default void enqueueAllFirst(Collection<? extends CLASS_TYPE> c) {
for(Iterator<? extends CLASS_TYPE> iter = c.iterator();iter.hasNext();)
enqueueFirst(iter.next());
}
#endif
/** /**
* A Method to remove a element from the last place instead of the first * A Method to remove a element from the last place instead of the first
* @return the last element inserted * @return the last element inserted
* @throws java.util.NoSuchElementException if no element is in the deque * @throws java.util.NoSuchElementException if no element is in the deque
*/ */
public KEY_TYPE DEQUEUE_LAST(); public KEY_TYPE dequeueLast();
/** /**
* Peeking function for the last element * Peeking function for the last element
* @return the Last Element within the dequeue without deleting it * @return the Last Element within the dequeue without deleting it
*/ */
public default KEY_TYPE LAST_KEY() { return PEEK(size()-1); } public default KEY_TYPE last() { return peek(size()-1); }
#if !TYPE_OBJECT
/** /**
* Boxed Method for the enqueue first method * Creates a Wrapped PriorityDequeue that is Synchronized
* @param e the boxed element that should be inserted * @return a new PriorityDequeue that is synchronized
* @see PRIORITY_QUEUES#synchronize
*/ */
@Deprecated public default PRIORITY_DEQUEUE KEY_GENERIC_TYPE synchronizeQueue() { return PRIORITY_QUEUES.synchronize(this); }
public default void enqueueFirst(CLASS_TYPE e) { ENQUEUE_FIRST(OBJ_TO_KEY(e)); }
/** /**
* Boxed Method for the dequeue last method * Creates a Wrapped PriorityDequeue that is Synchronized
* @return the last element of the Dequeue * @param mutex is the controller of the synchronization block
* @throws java.util.NoSuchElementException if no element is in the dequeue * @return a new PriorityDequeue Wrapper that is synchronized
* * @see PRIORITY_QUEUES#synchronize
*/ */
@Deprecated public default PRIORITY_DEQUEUE KEY_GENERIC_TYPE synchronizeQueue(Object mutex) { return PRIORITY_QUEUES.synchronize(this, mutex); }
public default CLASS_TYPE dequeueLast() { return KEY_TO_OBJ(DEQUEUE_LAST()); }
/** @Override
* Peeking function for the last element public PRIORITY_DEQUEUE KEY_GENERIC_TYPE copy();
* @return the Last Element within the dequeue without deleting it as boxed element
*/
@Deprecated
public default CLASS_TYPE last() { return peek(size()-1); }
#endif
} }
@@ -2,23 +2,25 @@ package speiger.src.collections.PACKAGE.queues;
#if TYPE_OBJECT #if TYPE_OBJECT
import java.util.Comparator; import java.util.Comparator;
import java.util.Collection;
import java.util.Iterator;
import speiger.src.collections.ints.functions.function.Int2ObjectFunction;
#else #else
import speiger.src.collections.PACKAGE.collections.ITERABLE;
import speiger.src.collections.PACKAGE.functions.COMPARATOR; import speiger.src.collections.PACKAGE.functions.COMPARATOR;
import speiger.src.collections.objects.queues.ObjectPriorityQueue;
#endif #endif
import speiger.src.collections.PACKAGE.collections.COLLECTION;
import speiger.src.collections.PACKAGE.collections.ITERABLE;
import speiger.src.collections.PACKAGE.collections.ITERATOR;
import speiger.src.collections.PACKAGE.utils.PRIORITY_QUEUES;
/** /**
* A Simple PriorityQueue (or Queue) interface that provides with the nessesary functions to interact with it, without cluttering with the Collection interface. * A Simple PriorityQueue (or Queue) interface that provides with the nessesary functions to interact with it, without cluttering with the Collection interface.
* @Type(T) * @Type(T)
*/ */
#if TYPE_OBJECT public interface PRIORITY_QUEUE KEY_GENERIC_TYPE extends ITERABLE KEY_GENERIC_TYPE
public interface PRIORITY_QUEUE KEY_GENERIC_TYPE extends Iterable<KEY_TYPE>
#else
public interface PRIORITY_QUEUE KEY_GENERIC_TYPE extends ObjectPriorityQueue<CLASS_TYPE>, ITERABLE KEY_GENERIC_TYPE
#endif
{ {
#if TYPE_OBJECT
/** /**
* @return true if the PriorityQueue is empty * @return true if the PriorityQueue is empty
*/ */
@@ -33,88 +35,158 @@ public interface PRIORITY_QUEUE KEY_GENERIC_TYPE extends ObjectPriorityQueue<CLA
*/ */
public void clear(); public void clear();
#endif
/** /**
* Method to insert a element into the PriorityQueue * Method to insert a element into the PriorityQueue
* @param e the element that should be inserted * @param e the element that should be inserted
*/ */
public void ENQUEUE(KEY_TYPE e); public void enqueue(KEY_TYPE e);
/**
* Method to mass insert elements into the PriorityQueue
* @param e the elements that should be inserted
*/
public default void enqueueAll(KEY_TYPE... e) {
enqueueAll(e, 0, e.length);
}
/**
* Method to mass insert elements into the PriorityQueue
* @param e the elements that should be inserted
* @param length the amount of elements that should be inserted
*/
public default void enqueueAll(KEY_TYPE[] e, int length) {
enqueueAll(e, 0, length);
}
/**
* Method to mass insert elements into the PriorityQueue
* @param e the elements that should be inserted
* @param offset the offset where in the array should be started
* @param length the amount of elements that should be inserted
*/
public default void enqueueAll(KEY_TYPE[] e, int offset, int length) {
for(int i = 0;i<length;i++)
enqueue(e[i+offset]);
}
/**
* Method to mass insert elements into the PriorityQueue
* @param c the elements that should be inserted from the Collection
*/
public default void enqueueAll(COLLECTION KEY_GENERIC_TYPE c) {
for(ITERATOR KEY_GENERIC_TYPE iter = c.iterator();iter.hasNext();)
enqueue(iter.NEXT());
}
#if TYPE_OBJECT
/**
* Method to mass insert elements into the PriorityQueue
* This method exists to add support for Java Collections to make it more useable
* @param c the elements that should be inserted from the Collection
*/
public default void enqueueAll(Collection<? extends CLASS_TYPE> c) {
for(Iterator<? extends CLASS_TYPE> iter = c.iterator();iter.hasNext();)
enqueue(iter.next());
}
#endif
/** /**
* Method to extract a element from the PriorityQueue * Method to extract a element from the PriorityQueue
* @return a element from the Queue * @return a element from the Queue
* @throws java.util.NoSuchElementException if no element is present * @throws java.util.NoSuchElementException if no element is present
*/ */
public KEY_TYPE DEQUEUE(); public KEY_TYPE dequeue();
/** /**
* Peeking function to see whats inside the queue. * Peeking function to see whats inside the queue.
* @param index of the element that is requested to be viewed. * @param index of the element that is requested to be viewed.
* @return the element that is requested * @return the element that is requested
*/ */
public KEY_TYPE PEEK(int index); public KEY_TYPE peek(int index);
/** /**
* Shows the element that is to be returned next * Shows the element that is to be returned next
* @return the first element in the Queue * @return the first element in the Queue
*/ */
public default KEY_TYPE FIRST_KEY() { return PEEK(0); } public default KEY_TYPE first() { return peek(0); }
/** /**
* Removes the first found element in the queue * Removes the first found element in the queue
* @param e the element that should be removed * @param e the element that should be removed
* @return if a searched element was removed * @return if a searched element was removed
*/ */
public boolean REMOVE(KEY_TYPE e); public boolean removeFirst(KEY_TYPE e);
/** /**
* Removes the last found element in the queue * Removes the last found element in the queue
* @param e the element that should be removed * @param e the element that should be removed
* @return if a searched element was removed * @return if a searched element was removed
*/ */
public boolean REMOVE_LAST(KEY_TYPE e); public boolean removeLast(KEY_TYPE e);
/** /**
* Allows to notify the Queue to be revalidate its data * Allows to notify the Queue to be revalidate its data
*/ */
public void onChanged(); public void onChanged();
/**
* A Function that does a shallow clone of the PriorityQueue itself.
* This function is more optimized then a copy constructor since the PriorityQueue does not have to be unsorted/resorted.
* It can be compared to Cloneable but with less exception risk
* @return a Shallow Copy of the PriorityQueue
* @note Wrappers and view PriorityQueues will not support this feature
*/
public PRIORITY_QUEUE KEY_GENERIC_TYPE copy();
/** /**
* @return the sorter of the Queue, can be null * @return the sorter of the Queue, can be null
*/ */
@PrimitiveOverride
public COMPARATOR KEY_SUPER_GENERIC_TYPE comparator(); public COMPARATOR KEY_SUPER_GENERIC_TYPE comparator();
#if TYPE_OBJECT
/**
* @return draining iterator of the PriorityQueue
*/
public ITERATOR KEY_GENERIC_TYPE iterator();
#endif
/**
* Creates a Wrapped PriorityQueue that is Synchronized
* @return a new PriorityQueue that is synchronized
* @see PRIORITY_QUEUES#synchronize
*/
public default PRIORITY_QUEUE KEY_GENERIC_TYPE synchronizeQueue() { return PRIORITY_QUEUES.synchronize(this); }
/**
* Creates a Wrapped PriorityQueue that is Synchronized
* @param mutex is the controller of the synchronization block
* @return a new PriorityQueue Wrapper that is synchronized
* @see PRIORITY_QUEUES#synchronize
*/
public default PRIORITY_QUEUE KEY_GENERIC_TYPE synchronizeQueue(Object mutex) { return PRIORITY_QUEUES.synchronize(this, mutex); }
/** /**
* A method to drop the contents of the Queue without clearing the queue * A method to drop the contents of the Queue without clearing the queue
* @Type(E)
* @return the contents of the queue into a seperate array. * @return the contents of the queue into a seperate array.
*/ */
public default KEY_TYPE[] TO_ARRAY() { return TO_ARRAY(NEW_KEY_ARRAY(size())); } public default GENERIC_SPECIAL_KEY_BRACES<E> KEY_SPECIAL_TYPE[] TO_ARRAY() { return TO_ARRAY(NEW_SPECIAL_KEY_ARRAY(size())); }
/** /**
* A method to drop the contents of the Queue without clearing the queue * A method to drop the contents of the Queue without clearing the queue
* @param input where the elements should be inserted to. If it does not fit then it creates a new appropiatly created array * @param input where the elements should be inserted to. If it does not fit then it creates a new appropiatly created array
* @Type(E)
* @return the contents of the queue into a seperate array. * @return the contents of the queue into a seperate array.
* @note if the Type is generic then a Object Array is created instead of a Type Array * @note if the Type is generic then a Object Array is created instead of a Type Array
*/ */
public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] input); public GENERIC_SPECIAL_KEY_BRACES<E> KEY_SPECIAL_TYPE[] TO_ARRAY(KEY_SPECIAL_TYPE[] input);
#if TYPE_OBJECT
#if !TYPE_OBJECT /**
@Deprecated * A Helper function that simplifies the process of creating a new Array.
public default void enqueue(CLASS_TYPE e) { ENQUEUE(OBJ_TO_KEY(e)); } * @param action the array creation function
@Deprecated * @return an array containing all of the elements in this collection
public default CLASS_TYPE dequeue() { return KEY_TO_OBJ(DEQUEUE()); } * @see Collection#toArray(Object[])
*/
@Deprecated default KEY_TYPE[] TO_ARRAY(Int2ObjectFunction<KEY_TYPE[]> action) {
public default CLASS_TYPE peek(int index) { return KEY_TO_OBJ(PEEK(index)); } return TO_ARRAY(action.get(size()));
@Deprecated }
public default CLASS_TYPE first() { return peek(0); }
@Deprecated
public default boolean remove(CLASS_TYPE e) { return REMOVE(OBJ_TO_KEY(e)); }
@Deprecated
public default boolean removeLast(CLASS_TYPE e) { return REMOVE_LAST(OBJ_TO_KEY(e)); }
@Deprecated
public default CLASS_TYPE[] toArray() { return toArray(new CLASS_TYPE[size()]); }
@Deprecated
public CLASS_TYPE[] toArray(CLASS_TYPE[] input);
#endif #endif
} }
@@ -3,13 +3,20 @@ package speiger.src.collections.PACKAGE.sets;
import java.util.Collection; import java.util.Collection;
#if TYPE_OBJECT #if TYPE_OBJECT
import java.util.Comparator; import java.util.Comparator;
import java.util.function.Consumer;
import java.util.function.BiFunction;
#endif #endif
import java.util.Iterator; import java.util.Iterator;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import java.util.Objects;
import speiger.src.collections.PACKAGE.collections.BI_ITERATOR; import speiger.src.collections.PACKAGE.collections.BI_ITERATOR;
#if !TYPE_OBJECT #if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.functions.COMPARATOR; import speiger.src.collections.PACKAGE.functions.COMPARATOR;
import speiger.src.collections.PACKAGE.functions.CONSUMER;
#endif #endif
import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER;
import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR;
import speiger.src.collections.PACKAGE.collections.COLLECTION; import speiger.src.collections.PACKAGE.collections.COLLECTION;
import speiger.src.collections.PACKAGE.collections.ITERATOR; import speiger.src.collections.PACKAGE.collections.ITERATOR;
import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR; import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR;
@@ -115,7 +122,7 @@ public class AVL_TREE_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE
* A Helper constructor that allows to create a Set with exactly the same values as the provided collection. * A Helper constructor that allows to create a Set with exactly the same values as the provided collection.
* @param collection the set the elements should be added to the TreeSet * @param collection the set the elements should be added to the TreeSet
*/ */
@Deprecated @Primitive
public AVL_TREE_SET(Collection<? extends CLASS_TYPE> collection) { public AVL_TREE_SET(Collection<? extends CLASS_TYPE> collection) {
addAll(collection); addAll(collection);
} }
@@ -125,7 +132,7 @@ public class AVL_TREE_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE
* @param collection the set the elements should be added to the TreeSet * @param collection the set the elements should be added to the TreeSet
* @param comp the sorter of the tree, can be null * @param comp the sorter of the tree, can be null
*/ */
@Deprecated @Primitive
public AVL_TREE_SET(Collection<? extends CLASS_TYPE> collection, COMPARATOR KEY_GENERIC_TYPE comp) { public AVL_TREE_SET(Collection<? extends CLASS_TYPE> collection, COMPARATOR KEY_GENERIC_TYPE comp) {
comparator = comp; comparator = comp;
addAll(collection); addAll(collection);
@@ -206,6 +213,9 @@ public class AVL_TREE_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE
#endif #endif
@Override @Override
public boolean add(KEY_TYPE o) { public boolean add(KEY_TYPE o) {
#if TYPE_OBJECT
validate(o);
#endif
if(tree == null) { if(tree == null) {
tree = first = last = new EntryBRACES(o, null); tree = first = last = new EntryBRACES(o, null);
size++; size++;
@@ -235,7 +245,7 @@ public class AVL_TREE_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE
} }
fixAfterInsertion(adding); fixAfterInsertion(adding);
size++; size++;
return false; return true;
} }
@Override @Override
@@ -290,6 +300,106 @@ public class AVL_TREE_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE
#endif #endif
} }
@Override
public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) {
Objects.requireNonNull(action);
for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) {
action.accept(entry.key);
}
}
@Override
public <E> void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next())
action.accept(input, entry.key);
}
@Override
public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) {
if(filter.TEST_VALUE(entry.key)) return true;
}
return false;
}
@Override
public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) {
if(filter.TEST_VALUE(entry.key)) return false;
}
return true;
}
@Override
public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) {
if(!filter.TEST_VALUE(entry.key)) return false;
}
return true;
}
@Override
public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) {
if(filter.TEST_VALUE(entry.key)) return entry.key;
}
return EMPTY_VALUE;
}
#if !TYPE_OBJECT
@Override
public KEY_TYPE reduce(KEY_TYPE identity, UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
KEY_TYPE state = identity;
for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) {
state = operator.APPLY_VALUE(state, entry.key);
}
return state;
}
#else
@Override
public <KEY_SPECIAL_TYPE> KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction<KEY_SPECIAL_TYPE, KEY_TYPE, KEY_SPECIAL_TYPE> operator) {
Objects.requireNonNull(operator);
KEY_SPECIAL_TYPE state = identity;
for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) {
state = operator.APPLY_VALUE(state, entry.key);
}
return state;
}
#endif
@Override
public KEY_TYPE reduce(UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
KEY_TYPE state = EMPTY_VALUE;
boolean empty = true;
for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) {
if(empty) {
empty = false;
state = entry.key;
continue;
}
state = operator.APPLY_VALUE(state, entry.key);
}
return state;
}
@Override
public int count(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
int result = 0;
for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) {
if(filter.TEST_VALUE(entry.key)) result++;
}
return result;
}
protected Entry KEY_GENERIC_TYPE findNode(KEY_TYPE o) { protected Entry KEY_GENERIC_TYPE findNode(KEY_TYPE o) {
Entry KEY_GENERIC_TYPE node = tree; Entry KEY_GENERIC_TYPE node = tree;
int compare; int compare;
@@ -472,6 +582,21 @@ public class AVL_TREE_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE
tree = null; tree = null;
} }
public AVL_TREE_SET KEY_GENERIC_TYPE copy() {
AVL_TREE_SET KEY_GENERIC_TYPE set = new AVL_TREE_SETBRACES();
set.size = size;
if(tree != null) {
set.tree = tree.copy();
Entry KEY_GENERIC_TYPE lastFound = null;
for(Entry KEY_GENERIC_TYPE entry = tree;entry != null;entry = entry.left) lastFound = entry;
set.first = lastFound;
lastFound = null;
for(Entry KEY_GENERIC_TYPE entry = tree;entry != null;entry = entry.right) lastFound = entry;
set.last = lastFound;
}
return set;
}
@Override @Override
public COMPARATOR KEY_GENERIC_TYPE comparator() { return comparator; } public COMPARATOR KEY_GENERIC_TYPE comparator() { return comparator; }
@@ -514,11 +639,11 @@ public class AVL_TREE_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE
entry.key = successor.key; entry.key = successor.key;
entry = successor; entry = successor;
} }
if(entry.previous() == null) first = entry.next();
if(entry.next() == null) last = entry.previous();
Entry KEY_GENERIC_TYPE replacement = entry.left != null ? entry.left : entry.right; Entry KEY_GENERIC_TYPE replacement = entry.left != null ? entry.left : entry.right;
if(replacement != null) { if(replacement != null) {
if(entry.replace(replacement)) tree = replacement; if(entry.replace(replacement)) tree = replacement;
if(entry == first) first = replacement;
if(entry == last) last = entry.right != null ? entry.right : replacement;
entry.left = entry.right = entry.parent = null; entry.left = entry.right = entry.parent = null;
fixAfterDeletion(replacement); fixAfterDeletion(replacement);
} }
@@ -526,15 +651,11 @@ public class AVL_TREE_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE
else { else {
fixAfterDeletion(entry); fixAfterDeletion(entry);
entry.replace(null); entry.replace(null);
if(entry.parent != null) {
Entry KEY_GENERIC_TYPE parent = entry.parent;
if(entry == first) first = parent.left != null ? parent.left : parent;
if(entry == last) last = entry.right != null ? parent.right : parent;
}
entry.parent = null; entry.parent = null;
} }
} }
protected void validate(KEY_TYPE k) { compare(k, k); }
protected int compare(KEY_TYPE k, KEY_TYPE v) { return comparator != null ? comparator.compare(k, v) : COMPAREABLE_TO_KEY(k, v);} protected int compare(KEY_TYPE k, KEY_TYPE v) { return comparator != null ? comparator.compare(k, v) : COMPAREABLE_TO_KEY(k, v);}
/** From CLR */ /** From CLR */
@@ -549,6 +670,8 @@ public class AVL_TREE_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE
else entry.parent.right = right; else entry.parent.right = right;
right.left = entry; right.left = entry;
entry.parent = right; entry.parent = right;
entry.updateHeight();
right.updateHeight();
} }
} }
@@ -564,6 +687,8 @@ public class AVL_TREE_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE
else entry.parent.left = left; else entry.parent.left = left;
left.right = entry; left.right = entry;
entry.parent = left; entry.parent = left;
entry.updateHeight();
left.updateHeight();
} }
} }
@@ -692,6 +817,9 @@ public class AVL_TREE_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE
return new DescendingSubSetBRACES(set, fromStart, start, loInclusive, false, fromElement, inclusive); return new DescendingSubSetBRACES(set, fromStart, start, loInclusive, false, fromElement, inclusive);
} }
protected Entry KEY_GENERIC_TYPE next(Entry KEY_GENERIC_TYPE entry) { return entry.previous(); }
protected Entry KEY_GENERIC_TYPE start() { return findHighest(); }
@Override @Override
public KEY_TYPE FIRST_KEY() { return super.LAST_KEY(); } public KEY_TYPE FIRST_KEY() { return super.LAST_KEY(); }
@@ -758,13 +886,13 @@ public class AVL_TREE_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE
AVL_TREE_SET KEY_GENERIC_TYPE set; AVL_TREE_SET KEY_GENERIC_TYPE set;
KEY_TYPE start; KEY_TYPE start;
KEY_TYPE end; KEY_TYPE end;
boolean fromStart; boolean fromStart;
boolean toEnd; boolean toEnd;
boolean loInclusive; boolean loInclusive;
boolean hiInclusive; boolean hiInclusive;
SubSet(AVL_TREE_SET KEY_GENERIC_TYPE set, boolean fromStart, KEY_TYPE start, boolean loInclusive, boolean toEnd, KEY_TYPE end, boolean hiInclusive) { SubSet(AVL_TREE_SET KEY_GENERIC_TYPE set, boolean fromStart, KEY_TYPE start, boolean loInclusive, boolean toEnd, KEY_TYPE end, boolean hiInclusive) {
this.set = set; this.set = set;
this.start = start; this.start = start;
this.end = end; this.end = end;
this.fromStart = fromStart; this.fromStart = fromStart;
@@ -793,10 +921,12 @@ public class AVL_TREE_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE
#endif #endif
boolean tooLow(KEY_TYPE key) { return !fromStart && (loInclusive ? set.compare(key, start) < 0 : set.compare(key, start) <= 0); } boolean tooLow(KEY_TYPE key) { return !fromStart && (loInclusive ? set.compare(key, start) < 0 : set.compare(key, start) <= 0); }
boolean tooHigh(KEY_TYPE key) { return !toEnd && (hiInclusive ? set.compare(key, end) > 0 : set.compare(key, end) >= 0); } boolean tooHigh(KEY_TYPE key) { return !toEnd && (hiInclusive ? set.compare(key, end) > 0 : set.compare(key, end) >= 0); }
boolean inRange(KEY_TYPE key) { return !tooLow(key) && !tooHigh(key); } boolean inRange(KEY_TYPE key) { return !tooLow(key) && !tooHigh(key); }
boolean inClosedRange(KEY_TYPE key) { return (fromStart || set.compare(key, start) >= 0) && (toEnd || set.compare(end, key) >= 0); } boolean inClosedRange(KEY_TYPE key) { return (fromStart || set.compare(key, start) >= 0) && (toEnd || set.compare(end, key) >= 0); }
boolean inRange(KEY_TYPE key, boolean inclusive) { return inclusive ? inRange(key) : inClosedRange(key); } boolean inRange(KEY_TYPE key, boolean inclusive) { return inclusive ? inRange(key) : inClosedRange(key); }
protected Entry KEY_GENERIC_TYPE next(Entry KEY_GENERIC_TYPE entry) { return entry.next(); }
protected Entry KEY_GENERIC_TYPE start() { return findLowest(); }
@Override @Override
public boolean addAndMoveToFirst(KEY_TYPE o) { throw new UnsupportedOperationException(); } public boolean addAndMoveToFirst(KEY_TYPE o) { throw new UnsupportedOperationException(); }
@@ -939,6 +1069,109 @@ public class AVL_TREE_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE
return fromStart && toEnd ? set.size() : iterator().skip(Integer.MAX_VALUE); return fromStart && toEnd ? set.size() : iterator().skip(Integer.MAX_VALUE);
} }
@Override
public SubSet KEY_GENERIC_TYPE copy() { throw new UnsupportedOperationException(); }
@Override
public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) {
Objects.requireNonNull(action);
for(Entry KEY_GENERIC_TYPE entry = start();entry != null && inRange(entry.key);entry = next(entry)) {
action.accept(entry.key);
}
}
@Override
public <E> void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
for(Entry KEY_GENERIC_TYPE entry = start();entry != null && inRange(entry.key);entry = next(entry))
action.accept(input, entry.key);
}
@Override
public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(Entry KEY_GENERIC_TYPE entry = start();entry != null && inRange(entry.key);entry = next(entry)) {
if(filter.TEST_VALUE(entry.key)) return true;
}
return false;
}
@Override
public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(Entry KEY_GENERIC_TYPE entry = start();entry != null && inRange(entry.key);entry = next(entry)) {
if(filter.TEST_VALUE(entry.key)) return false;
}
return true;
}
@Override
public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(Entry KEY_GENERIC_TYPE entry = start();entry != null && inRange(entry.key);entry = next(entry)) {
if(!filter.TEST_VALUE(entry.key)) return false;
}
return true;
}
#if !TYPE_OBJECT
@Override
public KEY_TYPE reduce(KEY_TYPE identity, UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
KEY_TYPE state = identity;
for(Entry KEY_GENERIC_TYPE entry = start();entry != null && inRange(entry.key);entry = next(entry)) {
state = operator.APPLY_VALUE(state, entry.key);
}
return state;
}
#else
@Override
public <KEY_SPECIAL_TYPE> KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction<KEY_SPECIAL_TYPE, KEY_TYPE, KEY_SPECIAL_TYPE> operator) {
Objects.requireNonNull(operator);
KEY_SPECIAL_TYPE state = identity;
for(Entry KEY_GENERIC_TYPE entry = start();entry != null && inRange(entry.key);entry = next(entry)) {
state = operator.APPLY_VALUE(state, entry.key);
}
return state;
}
#endif
@Override
public KEY_TYPE reduce(UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
KEY_TYPE state = EMPTY_VALUE;
boolean empty = true;
for(Entry KEY_GENERIC_TYPE entry = start();entry != null && inRange(entry.key);entry = next(entry)) {
if(empty) {
empty = false;
state = entry.key;
continue;
}
state = operator.APPLY_VALUE(state, entry.key);
}
return state;
}
@Override
public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(Entry KEY_GENERIC_TYPE entry = start();entry != null && inRange(entry.key);entry = next(entry)) {
if(filter.TEST_VALUE(entry.key)) return entry.key;
}
return EMPTY_VALUE;
}
@Override
public int count(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
int result = 0;
for(Entry KEY_GENERIC_TYPE entry = start();entry != null && inRange(entry.key);entry = next(entry)) {
if(filter.TEST_VALUE(entry.key)) result++;
}
return result;
}
class SubSetIterator implements LIST_ITERATOR KEY_GENERIC_TYPE class SubSetIterator implements LIST_ITERATOR KEY_GENERIC_TYPE
{ {
Entry KEY_GENERIC_TYPE previous; Entry KEY_GENERIC_TYPE previous;
@@ -1094,6 +1327,7 @@ public class AVL_TREE_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE
if(current == previous) index--; if(current == previous) index--;
updateNext(); updateNext();
updatePrevious(); updatePrevious();
if(current.needsSuccessor()) next = current;
removeNode(current); removeNode(current);
current = null; current = null;
} }
@@ -1118,11 +1352,27 @@ public class AVL_TREE_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE
this.parent = parent; this.parent = parent;
} }
Entry KEY_GENERIC_TYPE copy() {
Entry KEY_GENERIC_TYPE entry = new EntryBRACES(key, null);
entry.state = state;
if(left != null) {
Entry KEY_GENERIC_TYPE newLeft = left.copy();
entry.left = newLeft;
newLeft.parent = entry;
}
if(right != null) {
Entry KEY_GENERIC_TYPE newRight = right.copy();
entry.right = newRight;
newRight.parent = entry;
}
return entry;
}
int getHeight() { return state; } int getHeight() { return state; }
void updateHeight() { state = (1 + Math.max(left == null ? 0 : left.getHeight(), right == null ? 0 : right.getHeight())); } void updateHeight() { state = (1 + Math.max(left == null ? -1 : left.getHeight(), right == null ? -1 : right.getHeight())); }
int getBalance() { return (left == null ? 0 : left.getHeight()) - (right == null ? 0 : right.getBalance()); } int getBalance() { return (left == null ? -1 : left.getHeight()) - (right == null ? -1 : right.getHeight()); }
boolean needsSuccessor() { return left != null && right != null; } boolean needsSuccessor() { return left != null && right != null; }
@@ -1,7 +1,8 @@
package speiger.src.collections.PACKAGE.sets; package speiger.src.collections.PACKAGE.sets;
import java.util.Iterator; #if TYPE_OBJECT
import java.util.Objects; import java.util.Objects;
#endif
import java.util.Set; import java.util.Set;
import speiger.src.collections.PACKAGE.collections.ABSTRACT_COLLECTION; import speiger.src.collections.PACKAGE.collections.ABSTRACT_COLLECTION;
@@ -15,42 +16,30 @@ public abstract class ABSTRACT_SET KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION
{ {
@Override @Override
public abstract ITERATOR KEY_GENERIC_TYPE iterator(); public abstract ITERATOR KEY_GENERIC_TYPE iterator();
@Override
public ABSTRACT_SET KEY_GENERIC_TYPE copy() { throw new UnsupportedOperationException(); }
@Override @Override
public int hashCode() { public int hashCode() {
int hashCode = 1; int hashCode = 0;
ITERATOR KEY_GENERIC_TYPE i = iterator(); ITERATOR KEY_GENERIC_TYPE i = iterator();
while(i.hasNext()) while(i.hasNext())
hashCode = 31 * hashCode + KEY_TO_HASH(i.NEXT()); hashCode += KEY_TO_HASH(i.NEXT());
return hashCode; return hashCode;
} }
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (o == this) if (o == this)
return true; return true;
if (!(o instanceof Set)) if (!(o instanceof Set))
return false; return false;
Set<?> l = (Set<?>)o; Set<?> l = (Set<?>)o;
if(l.size() != size()) return false; if(l.size() != size()) return false;
#if !TYPE_OBJECT try {
if(l instanceof SET) return containsAll(l);
{ } catch (ClassCastException | NullPointerException unused) {
ITERATOR e1 = iterator(); return false;
ITERATOR e2 = ((SET)l).iterator();
while (e1.hasNext() && e2.hasNext()) {
if(!(KEY_EQUALS(e1.NEXT(), e2.NEXT())))
return false;
}
return !(e1.hasNext() || e2.hasNext());
} }
#endif
Iterator<CLASS_TYPE> e1 = iterator();
Iterator<?> e2 = l.iterator();
while (e1.hasNext() && e2.hasNext()) {
if(!Objects.equals(e1.next(), e2.next()))
return false;
}
return !(e1.hasNext() || e2.hasNext());
} }
} }
@@ -5,6 +5,7 @@ import java.util.Collection;
#if TYPE_OBJECT #if TYPE_OBJECT
import java.util.Comparator; import java.util.Comparator;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.function.BiFunction;
#endif #endif
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import java.util.Objects; import java.util.Objects;
@@ -12,17 +13,22 @@ import java.util.Set;
#if PRIMITIVES #if PRIMITIVES
import java.util.function.JAVA_PREDICATE; import java.util.function.JAVA_PREDICATE;
#endif #endif
import speiger.src.collections.PACKAGE.collections.BI_ITERATOR; import speiger.src.collections.PACKAGE.collections.BI_ITERATOR;
import speiger.src.collections.PACKAGE.collections.COLLECTION; import speiger.src.collections.PACKAGE.collections.COLLECTION;
import speiger.src.collections.PACKAGE.collections.ITERATOR; import speiger.src.collections.PACKAGE.collections.ITERATOR;
import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER;
import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR;
#if !TYPE_OBJECT #if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.functions.COMPARATOR; import speiger.src.collections.PACKAGE.functions.COMPARATOR;
import speiger.src.collections.PACKAGE.functions.CONSUMER; import speiger.src.collections.PACKAGE.functions.CONSUMER;
import speiger.src.collections.objects.utils.ObjectArrays;
#endif #endif
import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR; import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR;
import speiger.src.collections.PACKAGE.utils.ARRAYS; import speiger.src.collections.PACKAGE.utils.ARRAYS;
/** /**
* A Type Specific ArraySet implementation. * A Type Specific ArraySet implementation.
* That is based around the idea of {@link java.util.List#indexOf(Object)} for no duplication. * That is based around the idea of {@link java.util.List#indexOf(Object)} for no duplication.
@@ -68,8 +74,8 @@ public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE im
* @throws NegativeArraySizeException if the length is negative * @throws NegativeArraySizeException if the length is negative
*/ */
public ARRAY_SET(KEY_TYPE[] array, int length) { public ARRAY_SET(KEY_TYPE[] array, int length) {
data = Arrays.copyOf(array, length); this(length);
size = length; addAll(array, length);
} }
/** /**
@@ -77,7 +83,7 @@ public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE im
* @param c the elements that should be added to the set. * @param c the elements that should be added to the set.
* @note this slowly checks every element to remove duplicates * @note this slowly checks every element to remove duplicates
*/ */
@Deprecated @Primitive
public ARRAY_SET(Collection<? extends CLASS_TYPE> c) { public ARRAY_SET(Collection<? extends CLASS_TYPE> c) {
this(c.size()); this(c.size());
addAll(c); addAll(c);
@@ -98,7 +104,7 @@ public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE im
* Since it is assumed that there is no duplication in the first place * Since it is assumed that there is no duplication in the first place
* @param s the set the element should be taken from * @param s the set the element should be taken from
*/ */
@Deprecated @Primitive
public ARRAY_SET(Set<? extends CLASS_TYPE> s) { public ARRAY_SET(Set<? extends CLASS_TYPE> s) {
this(s.size()); this(s.size());
for(CLASS_TYPE e : s) for(CLASS_TYPE e : s)
@@ -208,6 +214,98 @@ public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE im
return data[size - 1]; return data[size - 1];
} }
@Override
public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c) {
int j = 0;
for(int i = 0;i<size;i++) {
if(!c.contains(data[i]))
data[j++] = data[i];
}
boolean result = j != size;
#if TYPE_OBJECT
Arrays.fill(data, j, size, null);
#endif
size = j;
return result;
}
@Override
public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c, CONSUMER KEY_GENERIC_TYPE r) {
int j = 0;
for(int i = 0;i<size;i++) {
if(!c.contains(data[i])) data[j++] = data[i];
else r.accept(data[i]);
}
boolean result = j != size;
#if TYPE_OBJECT
Arrays.fill(data, j, size, null);
#endif
size = j;
return result;
}
@Override
public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c) {
int j = 0;
for(int i = 0;i<size;i++) {
if(c.contains(data[i]))
data[j++] = data[i];
}
boolean result = j != size;
#if TYPE_OBJECT
Arrays.fill(data, j, size, null);
#endif
size = j;
return result;
}
@Override
public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c, CONSUMER KEY_GENERIC_TYPE r) {
int j = 0;
for(int i = 0;i<size;i++) {
if(c.contains(data[i])) data[j++] = data[i];
else r.accept(data[i]);
}
boolean result = j != size;
#if TYPE_OBJECT
Arrays.fill(data, j, size, null);
#endif
size = j;
return result;
}
@Override
@Primitive
public boolean removeAll(Collection<?> c) {
int j = 0;
for(int i = 0;i<size;i++) {
if(!c.contains(KEY_TO_OBJ(data[i])))
data[j++] = data[i];
}
boolean result = j != size;
#if TYPE_OBJECT
Arrays.fill(data, j, size, null);
#endif
size = j;
return result;
}
@Override
@Primitive
public boolean retainAll(Collection<?> c) {
int j = 0;
for(int i = 0;i<size;i++) {
if(c.contains(KEY_TO_OBJ(data[i])))
data[j++] = data[i];
}
boolean result = j != size;
#if TYPE_OBJECT
Arrays.fill(data, j, size, null);
#endif
size = j;
return result;
}
#if !TYPE_OBJECT #if !TYPE_OBJECT
@Override @Override
public boolean remove(KEY_TYPE o) { public boolean remove(KEY_TYPE o) {
@@ -277,21 +375,104 @@ public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE im
} }
#endif #endif
#if TYPE_OBJECT
@Override @Override
public void forEach(Consumer KEY_SUPER_GENERIC_TYPE action) { public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) {
Objects.requireNonNull(action); Objects.requireNonNull(action);
for(int i = 0;i<size;action.accept(data[i++])); for(int i = 0;i<size;action.accept(data[i++]));
} }
@Override
public <E> void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
for(int i = 0;i<size;i++)
action.accept(input, data[i]);
}
@Override
public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(int i = 0;i<size;i++) {
if(filter.TEST_VALUE(data[i])) return true;
}
return false;
}
@Override
public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(int i = 0;i<size;i++) {
if(filter.TEST_VALUE(data[i])) return false;
}
return true;
}
@Override
public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(int i = 0;i<size;i++) {
if(!filter.TEST_VALUE(data[i])) return false;
}
return true;
}
@Override
public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(int i = 0;i<size;i++) {
if(filter.TEST_VALUE(data[i])) return data[i];
}
return EMPTY_VALUE;
}
#if !TYPE_OBJECT
@Override
public KEY_TYPE reduce(KEY_TYPE identity, UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
KEY_TYPE state = identity;
for(int i = 0;i<size;i++) {
state = operator.APPLY_VALUE(state, data[i]);
}
return state;
}
#else #else
@Override @Override
public void forEach(CONSUMER KEY_GENERIC_TYPE action) { public <KEY_SPECIAL_TYPE> KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction<KEY_SPECIAL_TYPE, KEY_TYPE, KEY_SPECIAL_TYPE> operator) {
Objects.requireNonNull(action); Objects.requireNonNull(operator);
for(int i = 0;i<size;action.accept(data[i++])); KEY_SPECIAL_TYPE state = identity;
for(int i = 0;i<size;i++) {
state = operator.APPLY_VALUE(state, data[i]);
}
return state;
} }
#endif #endif
@Override
public KEY_TYPE reduce(UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
KEY_TYPE state = EMPTY_VALUE;
boolean empty = true;
for(int i = 0;i<size;i++) {
if(empty) {
empty = false;
state = data[i];
continue;
}
state = operator.APPLY_VALUE(state, data[i]);
}
return state;
}
@Override
public int count(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
int result = 0;
for(int i = 0;i<size;i++) {
if(filter.TEST_VALUE(data[i])) result++;
}
return result;
}
#if !TYPE_OBJECT #if !TYPE_OBJECT
protected int findIndex(KEY_TYPE o) { protected int findIndex(KEY_TYPE o) {
for(int i = size-1;i>=0;i--) for(int i = size-1;i>=0;i--)
@@ -340,6 +521,13 @@ public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE im
return new SubSet(fromIndex, size - fromIndex); return new SubSet(fromIndex, size - fromIndex);
} }
public ARRAY_SET KEY_GENERIC_TYPE copy() {
ARRAY_SET KEY_GENERIC_TYPE set = new ARRAY_SETBRACES();
set.data = Arrays.copyOf(data, data.length);
set.size = size;
return set;
}
@Override @Override
public COMPARATOR KEY_GENERIC_TYPE comparator() { public COMPARATOR KEY_GENERIC_TYPE comparator() {
return null; return null;
@@ -355,6 +543,36 @@ public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE im
return size; return size;
} }
#if !TYPE_OBJECT
@Override
public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] a) {
if(a == null || a.length < size()) return Arrays.copyOf(data, size());
System.arraycopy(data, 0, a, 0, size());
if (a.length > size) a[size] = EMPTY_KEY_VALUE;
return a;
}
#endif
@Override
@Deprecated
public Object[] toArray() {
Object[] obj = new Object[size()];
for(int i = 0;i<size();i++)
obj[i] = KEY_TO_OBJ(data[i]);
return obj;
}
@Override
@Primitive
public <E> E[] toArray(E[] a) {
if(a == null) a = (E[])new Object[size()];
else if(a.length < size()) a = (E[])ObjectArrays.newArray(a.getClass().getComponentType(), size());
for(int i = 0;i<size();i++)
a[i] = (E)KEY_TO_OBJ(data[i]);
if (a.length > size) a[size] = null;
return a;
}
private class SubSet extends ABSTRACT_SET KEY_GENERIC_TYPE implements SORTED_SET KEY_GENERIC_TYPE { private class SubSet extends ABSTRACT_SET KEY_GENERIC_TYPE implements SORTED_SET KEY_GENERIC_TYPE {
int offset; int offset;
int length; int length;
@@ -538,19 +756,22 @@ public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE im
throw new NoSuchElementException(); throw new NoSuchElementException();
} }
@Override
public SubSet copy() { throw new UnsupportedOperationException(); }
@Override @Override
public SORTED_SET KEY_GENERIC_TYPE subSet(KEY_TYPE fromElement, KEY_TYPE toElement) { public SORTED_SET KEY_GENERIC_TYPE subSet(KEY_TYPE fromElement, KEY_TYPE toElement) {
int fromIndex = findIndex(fromElement); int fromIndex = findIndex(fromElement);
int toIndex = findIndex(toElement); int toIndex = findIndex(toElement);
if(fromIndex == -1 || toIndex == -1) throw new NoSuchElementException(); if(fromIndex == -1 || toIndex == -1) throw new NoSuchElementException();
return new SubSet(fromIndex, toIndex - fromIndex); return new SubSet(fromIndex, toIndex - fromIndex + 1);
} }
@Override @Override
public SORTED_SET KEY_GENERIC_TYPE headSet(KEY_TYPE toElement) { public SORTED_SET KEY_GENERIC_TYPE headSet(KEY_TYPE toElement) {
int toIndex = findIndex(toElement); int toIndex = findIndex(toElement);
if(toIndex == -1) throw new NoSuchElementException(); if(toIndex == -1) throw new NoSuchElementException();
return new SubSet(0, toIndex); return new SubSet(0, toIndex+1);
} }
@Override @Override
@@ -565,6 +786,34 @@ public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE im
return length; return length;
} }
#if !TYPE_OBJECT
@Override
public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] a) {
if(a == null || a.length < size()) return Arrays.copyOfRange(data, offset, end());
System.arraycopy(data, offset, a, 0, size());
return a;
}
#endif
@Override
@Deprecated
public Object[] toArray() {
Object[] obj = new Object[size()];
for(int i = 0;i<size();i++)
obj[i] = KEY_TO_OBJ(data[offset+i]);
return obj;
}
@Override
@Primitive
public <E> E[] toArray(E[] a) {
if(a == null) a = (E[])new Object[size()];
else if(a.length < size()) a = (E[])ObjectArrays.newArray(a.getClass().getComponentType(), size());
for(int i = 0;i<size();i++)
a[i] = (E)KEY_TO_OBJ(data[offset+i]);
return a;
}
#if !TYPE_OBJECT #if !TYPE_OBJECT
protected int findIndex(KEY_TYPE o) { protected int findIndex(KEY_TYPE o) {
for(int i = length-1;i>=0;i--) for(int i = length-1;i>=0;i--)
@@ -594,6 +843,7 @@ public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE im
@Override @Override
public KEY_TYPE NEXT() { public KEY_TYPE NEXT() {
if(!hasNext()) throw new NoSuchElementException();
lastReturned = index; lastReturned = index;
return data[index++]; return data[index++];
} }
@@ -605,6 +855,7 @@ public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE im
@Override @Override
public KEY_TYPE PREVIOUS() { public KEY_TYPE PREVIOUS() {
if(!hasPrevious()) throw new NoSuchElementException();
lastReturned = index; lastReturned = index;
return data[index--]; return data[index--];
} }
@@ -677,6 +928,7 @@ public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE im
@Override @Override
public KEY_TYPE NEXT() { public KEY_TYPE NEXT() {
if(!hasNext()) throw new NoSuchElementException();
lastReturned = index; lastReturned = index;
return data[index++]; return data[index++];
} }
@@ -688,6 +940,7 @@ public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE im
@Override @Override
public KEY_TYPE PREVIOUS() { public KEY_TYPE PREVIOUS() {
if(!hasPrevious()) throw new NoSuchElementException();
lastReturned = index; lastReturned = index;
return data[index--]; return data[index--];
} }
@@ -704,11 +957,9 @@ public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE im
@Override @Override
public void remove() { public void remove() {
if(lastReturned == -1) if(lastReturned == -1) throw new IllegalStateException();
throw new IllegalStateException();
ARRAY_SET.this.remove(data[lastReturned]); ARRAY_SET.this.remove(data[lastReturned]);
if(lastReturned < index) if(lastReturned < index) index--;
index--;
lastReturned = -1; lastReturned = -1;
} }
@@ -0,0 +1,584 @@
package speiger.src.collections.PACKAGE.sets;
#if TYPE_OBJECT
import java.util.Comparator;
import java.util.function.Consumer;
import java.util.function.BiFunction;
#endif
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Objects;
import speiger.src.collections.PACKAGE.collections.BI_ITERATOR;
import speiger.src.collections.PACKAGE.collections.COLLECTION;
import speiger.src.collections.PACKAGE.collections.ITERATOR;
#if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.functions.COMPARATOR;
import speiger.src.collections.PACKAGE.functions.CONSUMER;
#endif
import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER;
import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR;
import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR;
import speiger.src.collections.PACKAGE.utils.ARRAYS;
import speiger.src.collections.PACKAGE.utils.ITERATORS;
import speiger.src.collections.utils.HashUtil;
import speiger.src.collections.utils.SanityChecks;
/**
* A Type Specific Custom implementation of the HashSet
* Instead of using Wrapper Object Arrays for storing keys and values there is dedicated arrays for storing keys.
* Extra to that there is a couple quality of life functions provided
* @Type(T)
*/
public class IMMUTABLE_HASH_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE implements SORTED_SET KEY_GENERIC_TYPE
{
/** The Backing keys array */
protected transient KEY_TYPE[] keys;
/** The Backing array for links between nodes. Left 32 Bits => Previous Entry, Right 32 Bits => Next Entry */
protected transient long[] links;
/** If a null value is present */
protected transient boolean containsNull;
/** Index of the Null Value */
protected transient int nullIndex;
/** Max Index that is allowed to be searched through nullIndex - 1 */
protected transient int mask;
/** Amount of Elements stored in the HashSet */
protected int size;
/** The First Index in the Map */
protected int firstIndex = -1;
/** The Last Index in the Map */
protected int lastIndex = -1;
/**
* Helper constructor to optimize the copying
* Only accessible through implementations
*/
protected IMMUTABLE_HASH_SET() {}
/**
* Helper constructor that allow to create a set from unboxed values
* @param array the elements that should be put into the set
*/
public IMMUTABLE_HASH_SET(KEY_TYPE[] array) {
this(array, 0, array.length, HashUtil.DEFAULT_LOAD_FACTOR);
}
/**
* Helper constructor that allow to create a set from unboxed values
* @param array the elements that should be put into the set
* @param loadFactor the percentage of how full the backing array can be before they resize
* @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1
*/
public IMMUTABLE_HASH_SET(KEY_TYPE[] array, float loadFactor) {
this(array, 0, array.length, loadFactor);
}
/**
* Helper constructor that allow to create a set from unboxed values
* @param array the elements that should be put into the set
* @param offset the starting index within the array that should be used
* @param length the amount of elements used from the array
* @throws IllegalStateException if offset and length causes to step outside of the arrays range
*/
public IMMUTABLE_HASH_SET(KEY_TYPE[] array, int offset, int length) {
this(array, offset, length, HashUtil.DEFAULT_LOAD_FACTOR);
}
/**
* Helper constructor that allow to create a set from unboxed values
* @param array the elements that should be put into the set
* @param offset the starting index within the array that should be used
* @param length the amount of elements used from the array
* @param loadFactor the percentage of how full the backing array can be before they resize
* @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1
* @throws IllegalStateException if offset and length causes to step outside of the arrays range
*/
public IMMUTABLE_HASH_SET(KEY_TYPE[] array, int offset, int length, float loadFactor) {
init(array, offset, length, loadFactor);
}
/**
* A Helper constructor that allows to create a Set with exactly the same values as the provided collection.
* @param collection the set the elements should be added to the Set
*/
@Primitive
public IMMUTABLE_HASH_SET(Collection<? extends CLASS_TYPE> collection) {
this(collection, HashUtil.DEFAULT_LOAD_FACTOR);
}
/**
* A Helper constructor that allows to create a Set with exactly the same values as the provided collection.
* @param collection the set the elements should be added to the Set
* @param loadFactor the percentage of how full the backing array can be before they resize
* @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1
*/
@Primitive
public IMMUTABLE_HASH_SET(Collection<? extends CLASS_TYPE> collection, float loadFactor) {
#if !TYPE_OBJECT
init(ARRAYS.unwrap(collection.toArray(NEW_CLASS_ARRAY(collection.size()))), 0, collection.size(), loadFactor);
#else
init(collection.toArray(NEW_CLASS_ARRAY(collection.size())), 0, collection.size(), loadFactor);
#endif
}
/**
* A Helper constructor that allows to create a Set with exactly the same values as the provided collection.
* @param collection the set the elements should be added to the Set
*/
public IMMUTABLE_HASH_SET(COLLECTION KEY_GENERIC_TYPE collection) {
this(collection, HashUtil.DEFAULT_LOAD_FACTOR);
}
/**
* A Helper constructor that allows to create a Set with exactly the same values as the provided collection.
* @param collection the set the elements should be added to the Set
* @param loadFactor the percentage of how full the backing array can be before they resize
* @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1
*/
public IMMUTABLE_HASH_SET(COLLECTION KEY_GENERIC_TYPE collection, float loadFactor) {
init(collection.TO_ARRAY(NEW_KEY_ARRAY(collection.size())), 0, collection.size(), loadFactor);
}
/**
* A Helper constructor that allows to create a set from a iterator of an unknown size
* @param iterator the elements that should be added to the set
*/
public IMMUTABLE_HASH_SET(Iterator<CLASS_TYPE> iterator) {
this(iterator, HashUtil.DEFAULT_LOAD_FACTOR);
}
/**
* A Helper constructor that allows to create a set from a iterator of an unknown size
* @param iterator the elements that should be added to the set
* @param loadFactor the percentage of how full the backing array can be before they resize
* @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1
*/
public IMMUTABLE_HASH_SET(Iterator<CLASS_TYPE> iterator, float loadFactor) {
this(ITERATORS.wrap(iterator), loadFactor);
}
/**
* A Helper constructor that allows to create a set from a iterator of an unknown size
* @param iterator the elements that should be added to the set
*/
public IMMUTABLE_HASH_SET(ITERATOR KEY_GENERIC_TYPE iterator) {
this(iterator, HashUtil.DEFAULT_LOAD_FACTOR);
}
/**
* A Helper constructor that allows to create a set from a iterator of an unknown size
* @param iterator the elements that should be added to the set
* @param loadFactor the percentage of how full the backing array can be before they resize
* @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1
*/
public IMMUTABLE_HASH_SET(ITERATOR KEY_GENERIC_TYPE iterator, float loadFactor) {
KEY_TYPE[] array = ARRAYS.pour(iterator);
init(array, 0, array.length, loadFactor);
}
protected void init(KEY_TYPE[] a, int offset, int length, float loadFactor) {
SanityChecks.checkArrayCapacity(a.length, offset, length);
int newSize = HashUtil.arraySize(length+1, loadFactor);
int newMask = newSize - 1;
KEY_TYPE[] newKeys = NEW_KEY_ARRAY(newSize + 1);
long[] newLinks = new long[newSize + 1];
int prev = -1;
for(int i = offset,m=offset+length;i<m;i++)
{
KEY_TYPE o = a[i];
if(KEY_EQUALS_NULL(o)) {
if(!containsNull) {
size++;
if(prev != -1) {
newLinks[prev] ^= ((newLinks[prev] ^ (newSize & 0xFFFFFFFFL)) & 0xFFFFFFFFL);
newLinks[newSize] ^= ((newLinks[newSize] ^ ((prev & 0xFFFFFFFFL) << 32)) & 0xFFFFFFFF00000000L);
prev = newSize;
}
else {
prev = firstIndex = newSize;
newLinks[newSize] = -1L;
}
}
containsNull = true;
continue;
}
boolean found = true;
int pos = HashUtil.mix(KEY_TO_HASH(o)) & newMask;
KEY_TYPE current = newKeys[pos];
if(KEY_EQUALS_NOT_NULL(current)) {
if(KEY_EQUALS(current, o)) continue;
while(KEY_EQUALS_NOT_NULL((current = newKeys[pos = (++pos & newMask)]))) {
if(KEY_EQUALS(current, o)) {
found = false;
break;
}
}
}
if(found) {
size++;
newKeys[pos] = o;
if(prev != -1) {
newLinks[prev] ^= ((newLinks[prev] ^ (pos & 0xFFFFFFFFL)) & 0xFFFFFFFFL);
newLinks[pos] ^= ((newLinks[pos] ^ ((prev & 0xFFFFFFFFL) << 32)) & 0xFFFFFFFF00000000L);
prev = pos;
}
else {
prev = firstIndex = pos;
newLinks[pos] = -1L;
}
}
}
nullIndex = newSize;
mask = newMask;
keys = newKeys;
links = newLinks;
lastIndex = prev;
if(prev != -1) newLinks[prev] |= 0xFFFFFFFFL;
}
@Override
public boolean add(KEY_TYPE o) { throw new UnsupportedOperationException(); }
@Override
@Primitive
public boolean addAll(Collection<? extends CLASS_TYPE> c) { throw new UnsupportedOperationException(); }
@Override
public boolean addAll(COLLECTION KEY_GENERIC_TYPE c) { throw new UnsupportedOperationException(); }
@Override
public boolean addAndMoveToFirst(KEY_TYPE o) { throw new UnsupportedOperationException(); }
@Override
public boolean addAndMoveToLast(KEY_TYPE o) { throw new UnsupportedOperationException(); }
@Override
public boolean moveToFirst(KEY_TYPE o) { throw new UnsupportedOperationException(); }
@Override
public boolean moveToLast(KEY_TYPE o) { throw new UnsupportedOperationException(); }
@Override
public boolean contains(Object o) {
if(o == null) return containsNull;
int pos = HashUtil.mix(o.hashCode()) & mask;
KEY_TYPE current = keys[pos];
if(KEY_EQUALS_NULL(current)) return false;
if(EQUALS_KEY_TYPE(current, o)) return true;
while(true) {
if(KEY_EQUALS_NULL((current = keys[pos = (++pos & mask)]))) return false;
else if(EQUALS_KEY_TYPE(current, o)) return true;
}
}
@Override
public KEY_TYPE FIRST_KEY() {
if(size == 0) throw new NoSuchElementException();
return keys[firstIndex];
}
@Override
public KEY_TYPE POLL_FIRST_KEY() { throw new UnsupportedOperationException(); }
@Override
public KEY_TYPE LAST_KEY() {
if(size == 0) throw new NoSuchElementException();
return keys[lastIndex];
}
@Override
public KEY_TYPE POLL_LAST_KEY() { throw new UnsupportedOperationException(); }
@Override
public boolean remove(Object o) { throw new UnsupportedOperationException(); }
#if !TYPE_OBJECT
@Override
public boolean contains(KEY_TYPE o) {
if(KEY_EQUALS_NULL(o)) return containsNull;
int pos = HashUtil.mix(KEY_TO_HASH(o)) & mask;
KEY_TYPE current = keys[pos];
if(KEY_EQUALS_NULL(current)) return false;
if(KEY_EQUALS(current, o)) return true;
while(true) {
if(KEY_EQUALS_NULL((current = keys[pos = (++pos & mask)]))) return false;
else if(KEY_EQUALS(current, o)) return true;
}
}
@Override
public boolean remove(KEY_TYPE o) { throw new UnsupportedOperationException(); }
#endif
@Override
public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) {
Objects.requireNonNull(action);
int index = firstIndex;
while(index != -1) {
action.accept(keys[index]);
index = (int)links[index];
}
}
@Override
public <E> void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
int index = firstIndex;
while(index != -1) {
action.accept(input, keys[index]);
index = (int)links[index];
}
}
@Override
public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
int index = firstIndex;
while(index != -1) {
if(filter.TEST_VALUE(keys[index])) return true;
index = (int)links[index];
}
return false;
}
@Override
public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
int index = firstIndex;
while(index != -1) {
if(filter.TEST_VALUE(keys[index])) return false;
index = (int)links[index];
}
return true;
}
@Override
public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
int index = firstIndex;
while(index != -1) {
if(!filter.TEST_VALUE(keys[index])) return false;
index = (int)links[index];
}
return true;
}
#if !TYPE_OBJECT
@Override
public KEY_TYPE reduce(KEY_TYPE identity, UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
KEY_TYPE state = identity;
int index = firstIndex;
while(index != -1) {
state = operator.APPLY_VALUE(state, keys[index]);
index = (int)links[index];
}
return state;
}
#else
@Override
public <KEY_SPECIAL_TYPE> KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction<KEY_SPECIAL_TYPE, KEY_TYPE, KEY_SPECIAL_TYPE> operator) {
Objects.requireNonNull(operator);
KEY_SPECIAL_TYPE state = identity;
int index = firstIndex;
while(index != -1) {
state = operator.APPLY_VALUE(state, keys[index]);
index = (int)links[index];
}
return state;
}
#endif
@Override
public KEY_TYPE reduce(UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
KEY_TYPE state = EMPTY_VALUE;
boolean empty = true;
int index = firstIndex;
while(index != -1) {
if(empty) {
state = keys[index];
empty = false;
}
else state = operator.APPLY_VALUE(state, keys[index]);
index = (int)links[index];
}
return state;
}
@Override
public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
int index = firstIndex;
while(index != -1) {
if(filter.TEST_VALUE(keys[index])) return keys[index];
index = (int)links[index];
}
return EMPTY_VALUE;
}
@Override
public int count(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
int result = 0;
int index = firstIndex;
while(index != -1) {
if(filter.TEST_VALUE(keys[index])) result++;
index = (int)links[index];
}
return result;
}
@Override
public LIST_ITERATOR KEY_GENERIC_TYPE iterator() {
return new SetIterator();
}
@Override
public BI_ITERATOR KEY_GENERIC_TYPE iterator(KEY_TYPE fromElement) {
return new SetIterator(fromElement);
}
@Override
public IMMUTABLE_HASH_SET KEY_GENERIC_TYPE copy() {
IMMUTABLE_HASH_SET KEY_GENERIC_TYPE set = new IMMUTABLE_HASH_SETBRACES();
set.containsNull = containsNull;
set.firstIndex = firstIndex;
set.lastIndex = lastIndex;
set.size = size;
set.mask = mask;
set.nullIndex = nullIndex;
set.keys = Arrays.copyOf(keys, keys.length);
set.links = Arrays.copyOf(links, links.length);
return set;
}
@Override
public COMPARATOR KEY_GENERIC_TYPE comparator() { return null; }
@Override
public SORTED_SET KEY_GENERIC_TYPE subSet(KEY_TYPE fromElement, KEY_TYPE toElement) { throw new UnsupportedOperationException(); }
@Override
public SORTED_SET KEY_GENERIC_TYPE headSet(KEY_TYPE toElement) { throw new UnsupportedOperationException(); }
@Override
public SORTED_SET KEY_GENERIC_TYPE tailSet(KEY_TYPE fromElement) { throw new UnsupportedOperationException(); }
@Override
public void clear() { throw new UnsupportedOperationException(); }
@Override
public int size() {
return size;
}
private class SetIterator implements LIST_ITERATOR KEY_GENERIC_TYPE {
int previous = -1;
int next = -1;
int current = -1;
int index = 0;
SetIterator() {
next = firstIndex;
}
SetIterator(KEY_TYPE from) {
if(KEY_EQUALS_NULL(from)) {
if(containsNull) {
next = (int) links[nullIndex];
previous = nullIndex;
}
else throw new NoSuchElementException("The null element is not in the set");
}
else if(KEY_EQUALS(keys[lastIndex], from)) {
previous = lastIndex;
index = size;
}
else {
int pos = HashUtil.mix(KEY_TO_HASH(from)) & mask;
while(KEY_EQUALS_NOT_NULL(keys[pos])) {
if(KEY_EQUALS(keys[pos], from)) {
next = (int)links[pos];
previous = pos;
break;
}
pos = ++pos & mask;
}
if(previous == -1 && next == -1)
throw new NoSuchElementException("The element was not found");
}
}
@Override
public boolean hasNext() {
return next != -1;
}
@Override
public boolean hasPrevious() {
return previous != -1;
}
@Override
public int nextIndex() {
ensureIndexKnown();
return index;
}
@Override
public int previousIndex() {
ensureIndexKnown();
return index - 1;
}
@Override
public void remove() { throw new UnsupportedOperationException(); }
@Override
public KEY_TYPE PREVIOUS() {
if(!hasPrevious()) throw new NoSuchElementException();
current = previous;
previous = (int)(links[current] >> 32);
next = current;
if(index >= 0) index--;
return keys[current];
}
@Override
public KEY_TYPE NEXT() {
if(!hasNext()) throw new NoSuchElementException();
current = next;
next = (int)(links[current]);
previous = current;
if(index >= 0) index++;
return keys[current];
}
private void ensureIndexKnown() {
if(index == -1) {
if(previous == -1) {
index = 0;
}
else if(next == -1) {
index = size;
}
else {
index = 1;
for(int pos = firstIndex;pos != previous;pos = (int)links[pos], index++);
}
}
}
#if TYPE_OBJECT
@Override
public void set(Object e) { throw new UnsupportedOperationException(); }
@Override
public void add(Object e) { throw new UnsupportedOperationException(); }
#else
@Override
public void set(KEY_TYPE e) { throw new UnsupportedOperationException(); }
@Override
public void add(KEY_TYPE e) { throw new UnsupportedOperationException(); }
#endif
}
}
@@ -2,7 +2,11 @@ package speiger.src.collections.PACKAGE.sets;
#if TYPE_OBJECT #if TYPE_OBJECT
import java.util.Comparator; import java.util.Comparator;
import java.util.function.Consumer;
import java.util.function.BiFunction;
#endif #endif
import java.util.Arrays;
import java.util.Objects;
import java.util.Collection; import java.util.Collection;
import java.util.Iterator; import java.util.Iterator;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
@@ -18,7 +22,11 @@ import speiger.src.collections.PACKAGE.functions.COMPARATOR;
import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR; import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR;
#if !TYPE_OBJECT #if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.utils.ITERATORS; import speiger.src.collections.PACKAGE.utils.ITERATORS;
import speiger.src.collections.PACKAGE.functions.CONSUMER;
#endif #endif
import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER;
import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR;
import speiger.src.collections.PACKAGE.utils.STRATEGY; import speiger.src.collections.PACKAGE.utils.STRATEGY;
import speiger.src.collections.utils.HashUtil; import speiger.src.collections.utils.HashUtil;
import speiger.src.collections.utils.SanityChecks; import speiger.src.collections.utils.SanityChecks;
@@ -130,7 +138,7 @@ public class LINKED_CUSTOM_HASH_SET KEY_GENERIC_TYPE extends CUSTOM_HASH_SET KEY
* @param strategy the strategy that allows hash control. * @param strategy the strategy that allows hash control.
* @throws NullPointerException if Strategy is null * @throws NullPointerException if Strategy is null
*/ */
@Deprecated @Primitive
public LINKED_CUSTOM_HASH_SET(Collection<? extends CLASS_TYPE> collection, STRATEGY KEY_SUPER_GENERIC_TYPE strategy) { public LINKED_CUSTOM_HASH_SET(Collection<? extends CLASS_TYPE> collection, STRATEGY KEY_SUPER_GENERIC_TYPE strategy) {
this(collection, HashUtil.DEFAULT_LOAD_FACTOR, strategy); this(collection, HashUtil.DEFAULT_LOAD_FACTOR, strategy);
} }
@@ -143,7 +151,7 @@ public class LINKED_CUSTOM_HASH_SET KEY_GENERIC_TYPE extends CUSTOM_HASH_SET KEY
* @throws NullPointerException if Strategy is null * @throws NullPointerException if Strategy is null
* @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1
*/ */
@Deprecated @Primitive
public LINKED_CUSTOM_HASH_SET(Collection<? extends CLASS_TYPE> collection, float loadFactor, STRATEGY KEY_SUPER_GENERIC_TYPE strategy) { public LINKED_CUSTOM_HASH_SET(Collection<? extends CLASS_TYPE> collection, float loadFactor, STRATEGY KEY_SUPER_GENERIC_TYPE strategy) {
this(collection.size(), loadFactor, strategy); this(collection.size(), loadFactor, strategy);
addAll(collection); addAll(collection);
@@ -424,7 +432,7 @@ public class LINKED_CUSTOM_HASH_SET KEY_GENERIC_TYPE extends CUSTOM_HASH_SET KEY
} }
else if(lastIndex == pos) { else if(lastIndex == pos) {
lastIndex = (int)(links[pos] >>> 32); lastIndex = (int)(links[pos] >>> 32);
if(0 <= lastIndex) links[pos] |= 0xFFFFFFFFL; if(0 <= lastIndex) links[lastIndex] |= 0xFFFFFFFFL;
} }
else { else {
long link = links[pos]; long link = links[pos];
@@ -501,6 +509,143 @@ public class LINKED_CUSTOM_HASH_SET KEY_GENERIC_TYPE extends CUSTOM_HASH_SET KEY
firstIndex = lastIndex = -1; firstIndex = lastIndex = -1;
} }
@Override
public void clearAndTrim(int size) {
int request = Math.max(minCapacity, HashUtil.nextPowerOfTwo((int)Math.ceil(size / loadFactor)));
if(request >= size) {
clear();
return;
}
nullIndex = request;
mask = request-1;
maxFill = Math.min((int)Math.ceil(nullIndex * loadFactor), nullIndex - 1);
keys = NEW_KEY_ARRAY(request + 1);
links = new long[request + 1];
firstIndex = lastIndex = -1;
this.size = 0;
containsNull = false;
}
@Override
public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) {
Objects.requireNonNull(action);
int index = firstIndex;
while(index != -1){
action.accept(keys[index]);
index = (int)links[index];
}
}
@Override
public <E> void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
int index = firstIndex;
while(index != -1) {
action.accept(input, keys[index]);
index = (int)links[index];
}
}
@Override
public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
int index = firstIndex;
while(index != -1) {
if(filter.TEST_VALUE(keys[index])) return true;
index = (int)links[index];
}
return false;
}
@Override
public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
int index = firstIndex;
while(index != -1) {
if(filter.TEST_VALUE(keys[index])) return false;
index = (int)links[index];
}
return true;
}
@Override
public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
int index = firstIndex;
while(index != -1) {
if(!filter.TEST_VALUE(keys[index])) return false;
index = (int)links[index];
}
return true;
}
#if !TYPE_OBJECT
@Override
public KEY_TYPE reduce(KEY_TYPE identity, UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
KEY_TYPE state = identity;
int index = firstIndex;
while(index != -1) {
state = operator.APPLY_VALUE(state, keys[index]);
index = (int)links[index];
}
return state;
}
#else
@Override
public <KEY_SPECIAL_TYPE> KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction<KEY_SPECIAL_TYPE, KEY_TYPE, KEY_SPECIAL_TYPE> operator) {
Objects.requireNonNull(operator);
KEY_SPECIAL_TYPE state = identity;
int index = firstIndex;
while(index != -1) {
state = operator.APPLY_VALUE(state, keys[index]);
index = (int)links[index];
}
return state;
}
#endif
@Override
public KEY_TYPE reduce(UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
KEY_TYPE state = EMPTY_VALUE;
boolean empty = true;
int index = firstIndex;
while(index != -1) {
if(empty) {
state = keys[index];
empty = false;
}
else state = operator.APPLY_VALUE(state, keys[index]);
index = (int)links[index];
}
return state;
}
@Override
public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
int index = firstIndex;
while(index != -1) {
if(filter.TEST_VALUE(keys[index])) return keys[index];
index = (int)links[index];
}
return EMPTY_VALUE;
}
@Override
public int count(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
int result = 0;
int index = firstIndex;
while(index != -1) {
if(filter.TEST_VALUE(keys[index])) result++;
index = (int)links[index];
}
return result;
}
@Override @Override
public LIST_ITERATOR KEY_GENERIC_TYPE iterator() { public LIST_ITERATOR KEY_GENERIC_TYPE iterator() {
return new SetIterator(); return new SetIterator();
@@ -511,6 +656,22 @@ public class LINKED_CUSTOM_HASH_SET KEY_GENERIC_TYPE extends CUSTOM_HASH_SET KEY
return new SetIterator(fromElement); return new SetIterator(fromElement);
} }
@Override
public LINKED_CUSTOM_HASH_SET KEY_GENERIC_TYPE copy() {
LINKED_CUSTOM_HASH_SET KEY_GENERIC_TYPE set = new LINKED_CUSTOM_HASH_SETBRACES(0, loadFactor, strategy);
set.minCapacity = minCapacity;
set.mask = mask;
set.maxFill = maxFill;
set.nullIndex = nullIndex;
set.containsNull = containsNull;
set.size = size;
set.keys = Arrays.copyOf(keys, keys.length);
set.links = Arrays.copyOf(links, links.length);
set.firstIndex = firstIndex;
set.lastIndex = lastIndex;
return set;
}
@Override @Override
public COMPARATOR KEY_GENERIC_TYPE comparator() { return null; } public COMPARATOR KEY_GENERIC_TYPE comparator() { return null; }
@@ -536,8 +697,8 @@ public class LINKED_CUSTOM_HASH_SET KEY_GENERIC_TYPE extends CUSTOM_HASH_SET KEY
SetIterator(KEY_TYPE from) { SetIterator(KEY_TYPE from) {
if(strategy.equals(from, EMPTY_KEY_VALUE)) { if(strategy.equals(from, EMPTY_KEY_VALUE)) {
if(containsNull) { if(containsNull) {
next = (int) links[nullIndex]; next = (int) links[nullIndex];
previous = nullIndex; previous = nullIndex;
} }
else throw new NoSuchElementException("The null element is not in the set"); else throw new NoSuchElementException("The null element is not in the set");
} }
@@ -3,11 +3,14 @@ package speiger.src.collections.PACKAGE.sets;
#if TYPE_OBJECT #if TYPE_OBJECT
import java.util.Comparator; import java.util.Comparator;
#endif #endif
import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.Iterator; import java.util.Iterator;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
#if TYPE_OBJECT
import java.util.Objects; import java.util.Objects;
#if TYPE_OBJECT
import java.util.function.Consumer;
import java.util.function.BiFunction;
#endif #endif
import speiger.src.collections.PACKAGE.collections.COLLECTION; import speiger.src.collections.PACKAGE.collections.COLLECTION;
@@ -17,7 +20,11 @@ import speiger.src.collections.PACKAGE.collections.ITERATOR;
import speiger.src.collections.PACKAGE.collections.BI_ITERATOR; import speiger.src.collections.PACKAGE.collections.BI_ITERATOR;
#if !TYPE_OBJECT #if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.functions.COMPARATOR; import speiger.src.collections.PACKAGE.functions.COMPARATOR;
import speiger.src.collections.PACKAGE.functions.CONSUMER;
#endif #endif
import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER;
import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR;
import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR; import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR;
#if !TYPE_OBJECT #if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.utils.ITERATORS; import speiger.src.collections.PACKAGE.utils.ITERATORS;
@@ -116,7 +123,7 @@ public class LINKED_HASH_SET KEY_GENERIC_TYPE extends HASH_SET KEY_GENERIC_TYPE
* A Helper constructor that allows to create a Set with exactly the same values as the provided collection. * A Helper constructor that allows to create a Set with exactly the same values as the provided collection.
* @param collection the set the elements should be added to the Set * @param collection the set the elements should be added to the Set
*/ */
@Deprecated @Primitive
public LINKED_HASH_SET(Collection<? extends CLASS_TYPE> collection) { public LINKED_HASH_SET(Collection<? extends CLASS_TYPE> collection) {
this(collection, HashUtil.DEFAULT_LOAD_FACTOR); this(collection, HashUtil.DEFAULT_LOAD_FACTOR);
} }
@@ -127,7 +134,7 @@ public class LINKED_HASH_SET KEY_GENERIC_TYPE extends HASH_SET KEY_GENERIC_TYPE
* @param loadFactor the percentage of how full the backing array can be before they resize * @param loadFactor the percentage of how full the backing array can be before they resize
* @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1
*/ */
@Deprecated @Primitive
public LINKED_HASH_SET(Collection<? extends CLASS_TYPE> collection, float loadFactor) { public LINKED_HASH_SET(Collection<? extends CLASS_TYPE> collection, float loadFactor) {
this(collection.size(), loadFactor); this(collection.size(), loadFactor);
addAll(collection); addAll(collection);
@@ -374,6 +381,126 @@ public class LINKED_HASH_SET KEY_GENERIC_TYPE extends HASH_SET KEY_GENERIC_TYPE
return result; return result;
} }
@Override
public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) {
Objects.requireNonNull(action);
int index = firstIndex;
while(index != -1){
action.accept(keys[index]);
index = (int)links[index];
}
}
@Override
public <E> void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
int index = firstIndex;
while(index != -1) {
action.accept(input, keys[index]);
index = (int)links[index];
}
}
@Override
public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
int index = firstIndex;
while(index != -1) {
if(filter.TEST_VALUE(keys[index])) return true;
index = (int)links[index];
}
return false;
}
@Override
public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
int index = firstIndex;
while(index != -1) {
if(filter.TEST_VALUE(keys[index])) return false;
index = (int)links[index];
}
return true;
}
@Override
public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
int index = firstIndex;
while(index != -1) {
if(!filter.TEST_VALUE(keys[index])) return false;
index = (int)links[index];
}
return true;
}
#if !TYPE_OBJECT
@Override
public KEY_TYPE reduce(KEY_TYPE identity, UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
KEY_TYPE state = identity;
int index = firstIndex;
while(index != -1) {
state = operator.APPLY_VALUE(state, keys[index]);
index = (int)links[index];
}
return state;
}
#else
@Override
public <KEY_SPECIAL_TYPE> KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction<KEY_SPECIAL_TYPE, KEY_TYPE, KEY_SPECIAL_TYPE> operator) {
Objects.requireNonNull(operator);
KEY_SPECIAL_TYPE state = identity;
int index = firstIndex;
while(index != -1) {
state = operator.APPLY_VALUE(state, keys[index]);
index = (int)links[index];
}
return state;
}
#endif
@Override
public KEY_TYPE reduce(UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
KEY_TYPE state = EMPTY_VALUE;
boolean empty = true;
int index = firstIndex;
while(index != -1) {
if(empty) {
state = keys[index];
empty = false;
}
else state = operator.APPLY_VALUE(state, keys[index]);
index = (int)links[index];
}
return state;
}
@Override
public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
int index = firstIndex;
while(index != -1) {
if(filter.TEST_VALUE(keys[index])) return keys[index];
index = (int)links[index];
}
return EMPTY_VALUE;
}
@Override
public int count(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
int result = 0;
int index = firstIndex;
while(index != -1) {
if(filter.TEST_VALUE(keys[index])) result++;
index = (int)links[index];
}
return result;
}
@Override @Override
protected void onNodeAdded(int pos) { protected void onNodeAdded(int pos) {
if(size == 0) { if(size == 0) {
@@ -396,7 +523,7 @@ public class LINKED_HASH_SET KEY_GENERIC_TYPE extends HASH_SET KEY_GENERIC_TYPE
} }
else if(lastIndex == pos) { else if(lastIndex == pos) {
lastIndex = (int)(links[pos] >>> 32); lastIndex = (int)(links[pos] >>> 32);
if(0 <= lastIndex) links[pos] |= 0xFFFFFFFFL; if(0 <= lastIndex) links[lastIndex] |= 0xFFFFFFFFL;
} }
else { else {
long link = links[pos]; long link = links[pos];
@@ -473,6 +600,23 @@ public class LINKED_HASH_SET KEY_GENERIC_TYPE extends HASH_SET KEY_GENERIC_TYPE
firstIndex = lastIndex = -1; firstIndex = lastIndex = -1;
} }
@Override
public void clearAndTrim(int size) {
int request = Math.max(minCapacity, HashUtil.nextPowerOfTwo((int)Math.ceil(size / loadFactor)));
if(request >= size) {
clear();
return;
}
nullIndex = request;
mask = request-1;
maxFill = Math.min((int)Math.ceil(nullIndex * loadFactor), nullIndex - 1);
keys = NEW_KEY_ARRAY(request + 1);
links = new long[request + 1];
firstIndex = lastIndex = -1;
this.size = 0;
containsNull = false;
}
@Override @Override
public LIST_ITERATOR KEY_GENERIC_TYPE iterator() { public LIST_ITERATOR KEY_GENERIC_TYPE iterator() {
return new SetIterator(); return new SetIterator();
@@ -483,6 +627,22 @@ public class LINKED_HASH_SET KEY_GENERIC_TYPE extends HASH_SET KEY_GENERIC_TYPE
return new SetIterator(fromElement); return new SetIterator(fromElement);
} }
@Override
public LINKED_HASH_SET KEY_GENERIC_TYPE copy() {
LINKED_HASH_SET KEY_GENERIC_TYPE set = new LINKED_HASH_SETBRACES(0, loadFactor);
set.minCapacity = minCapacity;
set.mask = mask;
set.maxFill = maxFill;
set.nullIndex = nullIndex;
set.containsNull = containsNull;
set.size = size;
set.keys = Arrays.copyOf(keys, keys.length);
set.links = Arrays.copyOf(links, links.length);
set.firstIndex = firstIndex;
set.lastIndex = lastIndex;
return set;
}
@Override @Override
public COMPARATOR KEY_GENERIC_TYPE comparator() { return null; } public COMPARATOR KEY_GENERIC_TYPE comparator() { return null; }
@@ -508,8 +668,8 @@ public class LINKED_HASH_SET KEY_GENERIC_TYPE extends HASH_SET KEY_GENERIC_TYPE
SetIterator(KEY_TYPE from) { SetIterator(KEY_TYPE from) {
if(KEY_EQUALS_NULL(from)) { if(KEY_EQUALS_NULL(from)) {
if(containsNull) { if(containsNull) {
next = (int) links[nullIndex]; next = (int) links[nullIndex];
previous = nullIndex; previous = nullIndex;
} }
else throw new NoSuchElementException("The null element is not in the set"); else throw new NoSuchElementException("The null element is not in the set");
} }
@@ -4,6 +4,7 @@ import java.util.NavigableSet;
import speiger.src.collections.PACKAGE.collections.BI_ITERATOR; import speiger.src.collections.PACKAGE.collections.BI_ITERATOR;
import speiger.src.collections.PACKAGE.collections.SPLIT_ITERATOR; import speiger.src.collections.PACKAGE.collections.SPLIT_ITERATOR;
import speiger.src.collections.PACKAGE.utils.SETS;
import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS; import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS;
/** /**
@@ -115,7 +116,33 @@ public interface NAVIGABLE_SET KEY_GENERIC_TYPE extends NavigableSet<CLASS_TYPE>
/** @return a Type Specific desendingSet */ /** @return a Type Specific desendingSet */
@Override @Override
public NAVIGABLE_SET KEY_GENERIC_TYPE descendingSet(); public NAVIGABLE_SET KEY_GENERIC_TYPE descendingSet();
@Override
public NAVIGABLE_SET KEY_GENERIC_TYPE copy();
#if !TYPE_BOOLEAN
/**
* Creates a Wrapped NavigableSet that is Synchronized
* @return a new NavigableSet that is synchronized
* @see SETS#synchronize
*/
public default NAVIGABLE_SET KEY_GENERIC_TYPE synchronize() { return SETS.synchronize(this); }
/**
* Creates a Wrapped NavigableSet that is Synchronized
* @param mutex is the controller of the synchronization block
* @return a new NavigableSet Wrapper that is synchronized
* @see SETS#synchronize
*/
public default NAVIGABLE_SET KEY_GENERIC_TYPE synchronize(Object mutex) { return SETS.synchronize(this, mutex); }
/**
* Creates a Wrapped NavigableSet that is unmodifiable
* @return a new NavigableSet Wrapper that is unmodifiable
* @see SETS#unmodifiable
*/
public default NAVIGABLE_SET KEY_GENERIC_TYPE unmodifiable() { return SETS.unmodifiable(this); }
#endif
/** /**
* A Type Specific Type Splititerator to reduce boxing/unboxing * A Type Specific Type Splititerator to reduce boxing/unboxing
* @return type specific splititerator * @return type specific splititerator
@@ -2,8 +2,14 @@ package speiger.src.collections.PACKAGE.sets;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.Iterator; import java.util.Iterator;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import java.util.Objects;
#if TYPE_OBJECT
import java.util.function.Consumer;
import java.util.function.BiFunction;
#endif
import speiger.src.collections.PACKAGE.collections.COLLECTION; import speiger.src.collections.PACKAGE.collections.COLLECTION;
import speiger.src.collections.PACKAGE.collections.ITERATOR; import speiger.src.collections.PACKAGE.collections.ITERATOR;
@@ -11,7 +17,11 @@ import speiger.src.collections.PACKAGE.lists.ARRAY_LIST;
import speiger.src.collections.PACKAGE.lists.LIST; import speiger.src.collections.PACKAGE.lists.LIST;
#if !TYPE_OBJECT #if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.utils.ITERATORS; import speiger.src.collections.PACKAGE.utils.ITERATORS;
import speiger.src.collections.PACKAGE.functions.CONSUMER;
#endif #endif
import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER;
import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR;
import speiger.src.collections.PACKAGE.utils.STRATEGY; import speiger.src.collections.PACKAGE.utils.STRATEGY;
import speiger.src.collections.utils.HashUtil; import speiger.src.collections.utils.HashUtil;
@@ -143,7 +153,7 @@ public class CUSTOM_HASH_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_T
* @param strategy the strategy that allows hash control. * @param strategy the strategy that allows hash control.
* @throws NullPointerException if Strategy is null * @throws NullPointerException if Strategy is null
*/ */
@Deprecated @Primitive
public CUSTOM_HASH_SET(Collection<? extends CLASS_TYPE> collection, STRATEGY KEY_SUPER_GENERIC_TYPE strategy) { public CUSTOM_HASH_SET(Collection<? extends CLASS_TYPE> collection, STRATEGY KEY_SUPER_GENERIC_TYPE strategy) {
this(collection, HashUtil.DEFAULT_LOAD_FACTOR, strategy); this(collection, HashUtil.DEFAULT_LOAD_FACTOR, strategy);
} }
@@ -156,7 +166,7 @@ public class CUSTOM_HASH_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_T
* @throws NullPointerException if Strategy is null * @throws NullPointerException if Strategy is null
* @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1
*/ */
@Deprecated @Primitive
public CUSTOM_HASH_SET(Collection<? extends CLASS_TYPE> collection, float loadFactor, STRATEGY KEY_SUPER_GENERIC_TYPE strategy) { public CUSTOM_HASH_SET(Collection<? extends CLASS_TYPE> collection, float loadFactor, STRATEGY KEY_SUPER_GENERIC_TYPE strategy) {
this(collection.size(), loadFactor, strategy); this(collection.size(), loadFactor, strategy);
addAll(collection); addAll(collection);
@@ -268,7 +278,7 @@ public class CUSTOM_HASH_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_T
} }
@Override @Override
@Deprecated @Primitive
public boolean addAll(Collection<? extends CLASS_TYPE> c) { public boolean addAll(Collection<? extends CLASS_TYPE> c) {
if(loadFactor <= 0.5F) ensureCapacity(c.size()); if(loadFactor <= 0.5F) ensureCapacity(c.size());
else ensureCapacity(c.size() + size()); else ensureCapacity(c.size() + size());
@@ -348,12 +358,29 @@ public class CUSTOM_HASH_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_T
return true; return true;
} }
@Override
public void clearAndTrim(int size) {
int request = Math.max(minCapacity, HashUtil.nextPowerOfTwo((int)Math.ceil(size / loadFactor)));
if(request >= size) {
clear();
return;
}
nullIndex = request;
mask = request-1;
maxFill = Math.min((int)Math.ceil(nullIndex * loadFactor), nullIndex - 1);
keys = NEW_KEY_ARRAY(request + 1);
this.size = 0;
containsNull = false;
}
private void ensureCapacity(int newCapacity) { private void ensureCapacity(int newCapacity) {
int size = HashUtil.arraySize(newCapacity, loadFactor); int size = HashUtil.arraySize(newCapacity, loadFactor);
if(size > nullIndex) rehash(size); if(size > nullIndex) rehash(size);
} }
protected boolean removeIndex(int pos) { protected boolean removeIndex(int pos) {
if(pos == nullIndex) return containsNull ? removeNullIndex() : false;
keys[pos] = EMPTY_KEY_VALUE;
size--; size--;
onNodeRemoved(pos); onNodeRemoved(pos);
shiftKeys(pos); shiftKeys(pos);
@@ -405,7 +432,10 @@ public class CUSTOM_HASH_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_T
int newMask = newSize - 1; int newMask = newSize - 1;
KEY_TYPE[] newKeys = NEW_KEY_ARRAY(newSize + 1); KEY_TYPE[] newKeys = NEW_KEY_ARRAY(newSize + 1);
for(int i = nullIndex, pos = 0, j = (size - (containsNull ? 1 : 0));j-- != 0;) { for(int i = nullIndex, pos = 0, j = (size - (containsNull ? 1 : 0));j-- != 0;) {
while(strategy.equals(keys[--i], EMPTY_KEY_VALUE)); while(true) {
if(--i < 0) throw new ConcurrentModificationException("Set was modified during rehash");
if(!strategy.equals(keys[i], EMPTY_KEY_VALUE)) break;
}
if(!strategy.equals(newKeys[pos = HashUtil.mix(KEY_TO_HASH(keys[i])) & newMask], EMPTY_KEY_VALUE)) if(!strategy.equals(newKeys[pos = HashUtil.mix(KEY_TO_HASH(keys[i])) & newMask], EMPTY_KEY_VALUE))
while(!strategy.equals(newKeys[pos = (++pos & newMask)], EMPTY_KEY_VALUE)); while(!strategy.equals(newKeys[pos = (++pos & newMask)], EMPTY_KEY_VALUE));
newKeys[pos] = keys[i]; newKeys[pos] = keys[i];
@@ -421,6 +451,19 @@ public class CUSTOM_HASH_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_T
return new SetIterator(); return new SetIterator();
} }
@Override
public CUSTOM_HASH_SET KEY_GENERIC_TYPE copy() {
CUSTOM_HASH_SET KEY_GENERIC_TYPE set = new CUSTOM_HASH_SETBRACES(0, loadFactor, strategy);
set.minCapacity = minCapacity;
set.mask = mask;
set.maxFill = maxFill;
set.nullIndex = nullIndex;
set.containsNull = containsNull;
set.size = size;
set.keys = Arrays.copyOf(keys, keys.length);
return set;
}
@Override @Override
public void clear() { public void clear() {
if(size == 0) return; if(size == 0) return;
@@ -434,8 +477,132 @@ public class CUSTOM_HASH_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_T
return size; return size;
} }
@Override
public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) {
if(size() <= 0) return;
if(containsNull) action.accept(keys[nullIndex]);
for(int i = nullIndex-1;i>=0;i--) {
if(!strategy.equals(keys[i], EMPTY_KEY_VALUE)) action.accept(keys[i]);
}
}
@Override
public <E> void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
if(size() <= 0) return;
if(containsNull) action.accept(input, keys[nullIndex]);
for(int i = nullIndex-1;i>=0;i--) {
if(!strategy.equals(keys[i], EMPTY_KEY_VALUE)) action.accept(input, keys[i]);
}
}
@Override
public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return false;
if(containsNull && filter.TEST_VALUE(keys[nullIndex])) return true;
for(int i = nullIndex-1;i>=0;i--) {
if(!strategy.equals(keys[i], EMPTY_KEY_VALUE) && filter.TEST_VALUE(keys[i])) return true;
}
return false;
}
@Override
public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return true;
if(containsNull && filter.TEST_VALUE(keys[nullIndex])) return false;
for(int i = nullIndex-1;i>=0;i--) {
if(!strategy.equals(keys[i], EMPTY_KEY_VALUE) && filter.TEST_VALUE(keys[i])) return false;
}
return true;
}
@Override
public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return true;
if(containsNull && !filter.TEST_VALUE(keys[nullIndex])) return false;
for(int i = nullIndex-1;i>=0;i--) {
if(!strategy.equals(keys[i], EMPTY_KEY_VALUE) && !filter.TEST_VALUE(keys[i])) return false;
}
return true;
}
#if !TYPE_OBJECT
@Override
public KEY_TYPE reduce(KEY_TYPE identity, UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
KEY_TYPE state = identity;
if(containsNull) state = operator.APPLY_VALUE(state, keys[nullIndex]);
for(int i = nullIndex-1;i>=0;i--) {
if(strategy.equals(keys[i], EMPTY_KEY_VALUE)) continue;
state = operator.APPLY_VALUE(state, keys[i]);
}
return state;
}
#else
@Override
public <KEY_SPECIAL_TYPE> KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction<KEY_SPECIAL_TYPE, KEY_TYPE, KEY_SPECIAL_TYPE> operator) {
Objects.requireNonNull(operator);
KEY_SPECIAL_TYPE state = identity;
if(containsNull) state = operator.APPLY_VALUE(state, keys[nullIndex]);
for(int i = nullIndex-1;i>=0;i--) {
if(strategy.equals(keys[i], EMPTY_KEY_VALUE)) continue;
state = operator.APPLY_VALUE(state, keys[i]);
}
return state;
}
#endif
@Override
public KEY_TYPE reduce(UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
KEY_TYPE state = EMPTY_VALUE;
boolean empty = true;
if(containsNull) {
state = keys[nullIndex];
empty = false;
}
for(int i = 0;i<size;i++) {
if(strategy.equals(keys[i], EMPTY_KEY_VALUE)) continue;
if(empty) {
empty = false;
state = keys[i];
continue;
}
state = operator.APPLY_VALUE(state, keys[i]);
}
return state;
}
@Override
public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return EMPTY_VALUE;
if(containsNull && filter.TEST_VALUE(keys[nullIndex])) return keys[nullIndex];
for(int i = nullIndex-1;i>=0;i--) {
if(!strategy.equals(keys[i], EMPTY_KEY_VALUE) && filter.TEST_VALUE(keys[i])) return keys[i];
}
return EMPTY_VALUE;
}
@Override
public int count(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return 0;
int result = 0;
if(containsNull && filter.TEST_VALUE(keys[nullIndex])) result++;
for(int i = nullIndex-1;i>=0;i--) {
if(!strategy.equals(keys[i], EMPTY_KEY_VALUE) && filter.TEST_VALUE(keys[i])) result++;
}
return result;
}
private class SetIterator implements ITERATOR KEY_GENERIC_TYPE { private class SetIterator implements ITERATOR KEY_GENERIC_TYPE {
int pos = nullIndex; int pos = nullIndex;
int returnedPos = -1;
int lastReturned = -1; int lastReturned = -1;
int nextIndex = Integer.MIN_VALUE; int nextIndex = Integer.MIN_VALUE;
boolean returnNull = containsNull; boolean returnNull = containsNull;
@@ -468,6 +635,7 @@ public class CUSTOM_HASH_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_T
@Override @Override
public KEY_TYPE NEXT() { public KEY_TYPE NEXT() {
if(!hasNext()) throw new NoSuchElementException(); if(!hasNext()) throw new NoSuchElementException();
returnedPos = pos;
if(nextIndex < 0){ if(nextIndex < 0){
lastReturned = Integer.MAX_VALUE; lastReturned = Integer.MAX_VALUE;
KEY_TYPE value = wrapped.GET_KEY(nextIndex); KEY_TYPE value = wrapped.GET_KEY(nextIndex);
@@ -486,9 +654,10 @@ public class CUSTOM_HASH_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_T
containsNull = false; containsNull = false;
keys[nullIndex] = EMPTY_KEY_VALUE; keys[nullIndex] = EMPTY_KEY_VALUE;
} }
else if(pos >= 0) shiftKeys(pos); else if(returnedPos >= 0) shiftKeys(returnedPos);
else { else {
CUSTOM_HASH_SET.this.remove(wrapped.GET_KEY(-pos - 1)); CUSTOM_HASH_SET.this.remove(wrapped.GET_KEY(-returnedPos - 1));
lastReturned = -1;
return; return;
} }
size--; size--;
@@ -2,9 +2,14 @@ package speiger.src.collections.PACKAGE.sets;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.Iterator; import java.util.Iterator;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import java.util.Objects; import java.util.Objects;
#if TYPE_OBJECT
import java.util.function.Consumer;
import java.util.function.BiFunction;
#endif
import speiger.src.collections.PACKAGE.collections.COLLECTION; import speiger.src.collections.PACKAGE.collections.COLLECTION;
import speiger.src.collections.PACKAGE.collections.ITERATOR; import speiger.src.collections.PACKAGE.collections.ITERATOR;
@@ -12,7 +17,11 @@ import speiger.src.collections.PACKAGE.lists.ARRAY_LIST;
import speiger.src.collections.PACKAGE.lists.LIST; import speiger.src.collections.PACKAGE.lists.LIST;
#if !TYPE_OBJECT #if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.utils.ITERATORS; import speiger.src.collections.PACKAGE.utils.ITERATORS;
import speiger.src.collections.PACKAGE.functions.CONSUMER;
#endif #endif
import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER;
import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR;
import speiger.src.collections.utils.HashUtil; import speiger.src.collections.utils.HashUtil;
import speiger.src.collections.utils.ITrimmable; import speiger.src.collections.utils.ITrimmable;
import speiger.src.collections.utils.SanityChecks; import speiger.src.collections.utils.SanityChecks;
@@ -124,7 +133,7 @@ public class HASH_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE imp
* A Helper constructor that allows to create a Set with exactly the same values as the provided collection. * A Helper constructor that allows to create a Set with exactly the same values as the provided collection.
* @param collection the set the elements should be added to the Set * @param collection the set the elements should be added to the Set
*/ */
@Deprecated @Primitive
public HASH_SET(Collection<? extends CLASS_TYPE> collection) { public HASH_SET(Collection<? extends CLASS_TYPE> collection) {
this(collection, HashUtil.DEFAULT_LOAD_FACTOR); this(collection, HashUtil.DEFAULT_LOAD_FACTOR);
} }
@@ -135,7 +144,7 @@ public class HASH_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE imp
* @param loadFactor the percentage of how full the backing array can be before they resize * @param loadFactor the percentage of how full the backing array can be before they resize
* @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1
*/ */
@Deprecated @Primitive
public HASH_SET(Collection<? extends CLASS_TYPE> collection, float loadFactor) { public HASH_SET(Collection<? extends CLASS_TYPE> collection, float loadFactor) {
this(collection.size(), loadFactor); this(collection.size(), loadFactor);
addAll(collection); addAll(collection);
@@ -227,7 +236,7 @@ public class HASH_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE imp
} }
@Override @Override
@Deprecated @Primitive
public boolean addAll(Collection<? extends CLASS_TYPE> c) { public boolean addAll(Collection<? extends CLASS_TYPE> c) {
if(loadFactor <= 0.5F) ensureCapacity(c.size()); if(loadFactor <= 0.5F) ensureCapacity(c.size());
else ensureCapacity(c.size() + size()); else ensureCapacity(c.size() + size());
@@ -283,7 +292,7 @@ public class HASH_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE imp
@Override @Override
public boolean remove(KEY_TYPE o) { public boolean remove(KEY_TYPE o) {
if(KEY_EQUALS_NULL(o)) return (containsNull ? removeNullIndex() : false); if(KEY_EQUALS_NULL(o)) return containsNull ? removeNullIndex() : false;
int pos = HashUtil.mix(KEY_TO_HASH(o)) & mask; int pos = HashUtil.mix(KEY_TO_HASH(o)) & mask;
KEY_TYPE current = keys[pos]; KEY_TYPE current = keys[pos];
if(KEY_EQUALS_NULL(current)) return false; if(KEY_EQUALS_NULL(current)) return false;
@@ -306,12 +315,152 @@ public class HASH_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE imp
return true; return true;
} }
@Override
public void clearAndTrim(int size) {
int request = Math.max(minCapacity, HashUtil.nextPowerOfTwo((int)Math.ceil(size / loadFactor)));
if(request >= size) {
clear();
return;
}
nullIndex = request;
mask = request-1;
maxFill = Math.min((int)Math.ceil(nullIndex * loadFactor), nullIndex - 1);
keys = NEW_KEY_ARRAY(request + 1);
this.size = 0;
containsNull = false;
}
@Override
public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) {
if(size() <= 0) return;
if(containsNull) action.accept(keys[nullIndex]);
for(int i = nullIndex-1;i>=0;i--) {
if(KEY_EQUALS_NOT_NULL(keys[i])) action.accept(keys[i]);
}
}
@Override
public <E> void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
if(size() <= 0) return;
if(containsNull) action.accept(input, keys[nullIndex]);
for(int i = nullIndex-1;i>=0;i--) {
if(KEY_EQUALS_NOT_NULL(keys[i])) action.accept(input, keys[i]);
}
}
@Override
public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return false;
if(containsNull && filter.TEST_VALUE(keys[nullIndex])) return true;
for(int i = nullIndex-1;i>=0;i--) {
if(KEY_EQUALS_NOT_NULL(keys[i]) && filter.TEST_VALUE(keys[i])) return true;
}
return false;
}
@Override
public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return true;
if(containsNull && filter.TEST_VALUE(keys[nullIndex])) return false;
for(int i = nullIndex-1;i>=0;i--) {
if(KEY_EQUALS_NOT_NULL(keys[i]) && filter.TEST_VALUE(keys[i])) return false;
}
return true;
}
@Override
public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return true;
if(containsNull && !filter.TEST_VALUE(keys[nullIndex])) return false;
for(int i = nullIndex-1;i>=0;i--) {
if(KEY_EQUALS_NOT_NULL(keys[i]) && !filter.TEST_VALUE(keys[i])) return false;
}
return true;
}
#if !TYPE_OBJECT
@Override
public KEY_TYPE reduce(KEY_TYPE identity, UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
KEY_TYPE state = identity;
if(containsNull) state = operator.APPLY_VALUE(state, keys[nullIndex]);
for(int i = nullIndex-1;i>=0;i--) {
if(KEY_EQUALS_NULL(keys[i])) continue;
state = operator.APPLY_VALUE(state, keys[i]);
}
return state;
}
#else
@Override
public <KEY_SPECIAL_TYPE> KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction<KEY_SPECIAL_TYPE, KEY_TYPE, KEY_SPECIAL_TYPE> operator) {
Objects.requireNonNull(operator);
KEY_SPECIAL_TYPE state = identity;
if(containsNull) state = operator.APPLY_VALUE(state, keys[nullIndex]);
for(int i = nullIndex-1;i>=0;i--) {
if(KEY_EQUALS_NULL(keys[i])) continue;
state = operator.APPLY_VALUE(state, keys[i]);
}
return state;
}
#endif
@Override
public KEY_TYPE reduce(UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
KEY_TYPE state = EMPTY_VALUE;
boolean empty = true;
if(containsNull) {
state = keys[nullIndex];
empty = false;
}
for(int i = 0;i<size;i++) {
if(KEY_EQUALS_NULL(keys[i])) continue;
if(empty) {
empty = false;
state = keys[i];
continue;
}
state = operator.APPLY_VALUE(state, keys[i]);
}
return state;
}
@Override
public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return EMPTY_VALUE;
if(containsNull && filter.TEST_VALUE(keys[nullIndex])) return keys[nullIndex];
for(int i = nullIndex-1;i>=0;i--) {
if(KEY_EQUALS_NOT_NULL(keys[i]) && filter.TEST_VALUE(keys[i])) return keys[i];
}
return EMPTY_VALUE;
}
@Override
public int count(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return 0;
int result = 0;
if(containsNull && filter.TEST_VALUE(keys[nullIndex])) result++;
for(int i = nullIndex-1;i>=0;i--) {
if(KEY_EQUALS_NOT_NULL(keys[i]) && filter.TEST_VALUE(keys[i])) result++;
}
return result;
}
private void ensureCapacity(int newCapacity) { private void ensureCapacity(int newCapacity) {
int size = HashUtil.arraySize(newCapacity, loadFactor); int size = HashUtil.arraySize(newCapacity, loadFactor);
if(size > nullIndex) rehash(size); if(size > nullIndex) rehash(size);
} }
protected boolean removeIndex(int pos) { protected boolean removeIndex(int pos) {
if(pos == nullIndex) return containsNull ? removeNullIndex() : false;
keys[pos] = EMPTY_KEY_VALUE;
size--; size--;
onNodeRemoved(pos); onNodeRemoved(pos);
shiftKeys(pos); shiftKeys(pos);
@@ -363,7 +512,10 @@ public class HASH_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE imp
int newMask = newSize - 1; int newMask = newSize - 1;
KEY_TYPE[] newKeys = NEW_KEY_ARRAY(newSize + 1); KEY_TYPE[] newKeys = NEW_KEY_ARRAY(newSize + 1);
for(int i = nullIndex, pos = 0, j = (size - (containsNull ? 1 : 0));j-- != 0;) { for(int i = nullIndex, pos = 0, j = (size - (containsNull ? 1 : 0));j-- != 0;) {
while(KEY_EQUALS_NULL(keys[--i])); while(true) {
if(--i < 0) throw new ConcurrentModificationException("Set was modified during rehash");
if(KEY_EQUALS_NOT_NULL(keys[i])) break;
}
if(KEY_EQUALS_NOT_NULL(newKeys[pos = HashUtil.mix(KEY_TO_HASH(keys[i])) & newMask])) if(KEY_EQUALS_NOT_NULL(newKeys[pos = HashUtil.mix(KEY_TO_HASH(keys[i])) & newMask]))
while(KEY_EQUALS_NOT_NULL(newKeys[pos = (++pos & newMask)])); while(KEY_EQUALS_NOT_NULL(newKeys[pos = (++pos & newMask)]));
newKeys[pos] = keys[i]; newKeys[pos] = keys[i];
@@ -379,6 +531,19 @@ public class HASH_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE imp
return new SetIterator(); return new SetIterator();
} }
@Override
public HASH_SET KEY_GENERIC_TYPE copy() {
HASH_SET KEY_GENERIC_TYPE set = new HASH_SETBRACES(0, loadFactor);
set.minCapacity = minCapacity;
set.mask = mask;
set.maxFill = maxFill;
set.nullIndex = nullIndex;
set.containsNull = containsNull;
set.size = size;
set.keys = Arrays.copyOf(keys, keys.length);
return set;
}
@Override @Override
public void clear() { public void clear() {
if(size == 0) return; if(size == 0) return;
@@ -394,6 +559,7 @@ public class HASH_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE imp
private class SetIterator implements ITERATOR KEY_GENERIC_TYPE { private class SetIterator implements ITERATOR KEY_GENERIC_TYPE {
int pos = nullIndex; int pos = nullIndex;
int returnedPos = -1;
int lastReturned = -1; int lastReturned = -1;
int nextIndex = Integer.MIN_VALUE; int nextIndex = Integer.MIN_VALUE;
boolean returnNull = containsNull; boolean returnNull = containsNull;
@@ -427,6 +593,7 @@ public class HASH_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE imp
@Override @Override
public KEY_TYPE NEXT() { public KEY_TYPE NEXT() {
if(!hasNext()) throw new NoSuchElementException(); if(!hasNext()) throw new NoSuchElementException();
returnedPos = pos;
if(nextIndex < 0){ if(nextIndex < 0){
lastReturned = Integer.MAX_VALUE; lastReturned = Integer.MAX_VALUE;
KEY_TYPE value = wrapped.GET_KEY(nextIndex); KEY_TYPE value = wrapped.GET_KEY(nextIndex);
@@ -445,9 +612,10 @@ public class HASH_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE imp
containsNull = false; containsNull = false;
keys[nullIndex] = EMPTY_KEY_VALUE; keys[nullIndex] = EMPTY_KEY_VALUE;
} }
else if(pos >= 0) shiftKeys(pos); else if(returnedPos >= 0) shiftKeys(returnedPos);
else { else {
HASH_SET.this.remove(wrapped.GET_KEY(-pos - 1)); HASH_SET.this.remove(wrapped.GET_KEY(-returnedPos - 1));
lastReturned = -1;
return; return;
} }
size--; size--;
@@ -3,13 +3,20 @@ package speiger.src.collections.PACKAGE.sets;
import java.util.Collection; import java.util.Collection;
#if TYPE_OBJECT #if TYPE_OBJECT
import java.util.Comparator; import java.util.Comparator;
import java.util.function.Consumer;
import java.util.function.BiFunction;
#endif #endif
import java.util.Iterator; import java.util.Iterator;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import java.util.Objects;
import speiger.src.collections.PACKAGE.collections.BI_ITERATOR; import speiger.src.collections.PACKAGE.collections.BI_ITERATOR;
#if !TYPE_OBJECT #if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.functions.COMPARATOR; import speiger.src.collections.PACKAGE.functions.COMPARATOR;
import speiger.src.collections.PACKAGE.functions.CONSUMER;
#endif #endif
import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER;
import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR;
import speiger.src.collections.PACKAGE.collections.COLLECTION; import speiger.src.collections.PACKAGE.collections.COLLECTION;
import speiger.src.collections.PACKAGE.collections.ITERATOR; import speiger.src.collections.PACKAGE.collections.ITERATOR;
import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR; import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR;
@@ -115,7 +122,7 @@ public class RB_TREE_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE
* A Helper constructor that allows to create a Set with exactly the same values as the provided collection. * A Helper constructor that allows to create a Set with exactly the same values as the provided collection.
* @param collection the set the elements should be added to the TreeSet * @param collection the set the elements should be added to the TreeSet
*/ */
@Deprecated @Primitive
public RB_TREE_SET(Collection<? extends CLASS_TYPE> collection) { public RB_TREE_SET(Collection<? extends CLASS_TYPE> collection) {
addAll(collection); addAll(collection);
} }
@@ -125,7 +132,7 @@ public class RB_TREE_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE
* @param collection the set the elements should be added to the TreeSet * @param collection the set the elements should be added to the TreeSet
* @param comp the sorter of the tree, can be null * @param comp the sorter of the tree, can be null
*/ */
@Deprecated @Primitive
public RB_TREE_SET(Collection<? extends CLASS_TYPE> collection, COMPARATOR KEY_GENERIC_TYPE comp) { public RB_TREE_SET(Collection<? extends CLASS_TYPE> collection, COMPARATOR KEY_GENERIC_TYPE comp) {
comparator = comp; comparator = comp;
addAll(collection); addAll(collection);
@@ -206,6 +213,9 @@ public class RB_TREE_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE
#endif #endif
@Override @Override
public boolean add(KEY_TYPE o) { public boolean add(KEY_TYPE o) {
#if TYPE_OBJECT
validate(o);
#endif
if(tree == null) { if(tree == null) {
tree = first = last = new EntryBRACES(o, null); tree = first = last = new EntryBRACES(o, null);
size++; size++;
@@ -235,7 +245,7 @@ public class RB_TREE_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE
} }
fixAfterInsertion(adding); fixAfterInsertion(adding);
size++; size++;
return false; return true;
} }
@Override @Override
@@ -290,6 +300,106 @@ public class RB_TREE_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE
#endif #endif
} }
@Override
public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) {
Objects.requireNonNull(action);
for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) {
action.accept(entry.key);
}
}
@Override
public <E> void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next())
action.accept(input, entry.key);
}
@Override
public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) {
if(filter.TEST_VALUE(entry.key)) return true;
}
return false;
}
@Override
public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) {
if(filter.TEST_VALUE(entry.key)) return false;
}
return true;
}
@Override
public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) {
if(!filter.TEST_VALUE(entry.key)) return false;
}
return true;
}
#if !TYPE_OBJECT
@Override
public KEY_TYPE reduce(KEY_TYPE identity, UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
KEY_TYPE state = identity;
for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) {
state = operator.APPLY_VALUE(state, entry.key);
}
return state;
}
#else
@Override
public <KEY_SPECIAL_TYPE> KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction<KEY_SPECIAL_TYPE, KEY_TYPE, KEY_SPECIAL_TYPE> operator) {
Objects.requireNonNull(operator);
KEY_SPECIAL_TYPE state = identity;
for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) {
state = operator.APPLY_VALUE(state, entry.key);
}
return state;
}
#endif
@Override
public KEY_TYPE reduce(UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
KEY_TYPE state = EMPTY_VALUE;
boolean empty = true;
for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) {
if(empty) {
empty = false;
state = entry.key;
continue;
}
state = operator.APPLY_VALUE(state, entry.key);
}
return state;
}
@Override
public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) {
if(filter.TEST_VALUE(entry.key)) return entry.key;
}
return EMPTY_VALUE;
}
@Override
public int count(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
int result = 0;
for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) {
if(filter.TEST_VALUE(entry.key)) result++;
}
return result;
}
protected Entry KEY_GENERIC_TYPE findNode(KEY_TYPE o) { protected Entry KEY_GENERIC_TYPE findNode(KEY_TYPE o) {
Entry KEY_GENERIC_TYPE node = tree; Entry KEY_GENERIC_TYPE node = tree;
int compare; int compare;
@@ -474,6 +584,21 @@ public class RB_TREE_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE
tree = null; tree = null;
} }
public RB_TREE_SET KEY_GENERIC_TYPE copy() {
RB_TREE_SET KEY_GENERIC_TYPE set = new RB_TREE_SETBRACES();
set.size = size;
if(tree != null) {
set.tree = tree.copy();
Entry KEY_GENERIC_TYPE lastFound = null;
for(Entry KEY_GENERIC_TYPE entry = tree;entry != null;entry = entry.left) lastFound = entry;
set.first = lastFound;
lastFound = null;
for(Entry KEY_GENERIC_TYPE entry = tree;entry != null;entry = entry.right) lastFound = entry;
set.last = lastFound;
}
return set;
}
@Override @Override
public COMPARATOR KEY_GENERIC_TYPE comparator() { return comparator; } public COMPARATOR KEY_GENERIC_TYPE comparator() { return comparator; }
@@ -538,6 +663,7 @@ public class RB_TREE_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE
} }
} }
protected void validate(KEY_TYPE k) { compare(k, k); }
protected int compare(KEY_TYPE k, KEY_TYPE v) { return comparator != null ? comparator.compare(k, v) : COMPAREABLE_TO_KEY(k, v);} protected int compare(KEY_TYPE k, KEY_TYPE v) { return comparator != null ? comparator.compare(k, v) : COMPAREABLE_TO_KEY(k, v);}
protected static GENERIC_KEY_BRACES boolean isBlack(Entry KEY_GENERIC_TYPE p) { return p == null || p.isBlack(); } protected static GENERIC_KEY_BRACES boolean isBlack(Entry KEY_GENERIC_TYPE p) { return p == null || p.isBlack(); }
protected static GENERIC_KEY_BRACES Entry KEY_GENERIC_TYPE parentOf(Entry KEY_GENERIC_TYPE p) { return (p == null ? null : p.parent); } protected static GENERIC_KEY_BRACES Entry KEY_GENERIC_TYPE parentOf(Entry KEY_GENERIC_TYPE p) { return (p == null ? null : p.parent); }
@@ -752,6 +878,9 @@ public class RB_TREE_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE
return new DescendingSubSetBRACES(set, fromStart, start, loInclusive, false, fromElement, inclusive); return new DescendingSubSetBRACES(set, fromStart, start, loInclusive, false, fromElement, inclusive);
} }
protected Entry KEY_GENERIC_TYPE next(Entry KEY_GENERIC_TYPE entry) { return entry.previous(); }
protected Entry KEY_GENERIC_TYPE start() { return findHighest(); }
@Override @Override
public KEY_TYPE FIRST_KEY() { return super.LAST_KEY(); } public KEY_TYPE FIRST_KEY() { return super.LAST_KEY(); }
@@ -818,13 +947,13 @@ public class RB_TREE_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE
RB_TREE_SET KEY_GENERIC_TYPE set; RB_TREE_SET KEY_GENERIC_TYPE set;
KEY_TYPE start; KEY_TYPE start;
KEY_TYPE end; KEY_TYPE end;
boolean fromStart; boolean fromStart;
boolean toEnd; boolean toEnd;
boolean loInclusive; boolean loInclusive;
boolean hiInclusive; boolean hiInclusive;
SubSet(RB_TREE_SET KEY_GENERIC_TYPE set, boolean fromStart, KEY_TYPE start, boolean loInclusive, boolean toEnd, KEY_TYPE end, boolean hiInclusive) { SubSet(RB_TREE_SET KEY_GENERIC_TYPE set, boolean fromStart, KEY_TYPE start, boolean loInclusive, boolean toEnd, KEY_TYPE end, boolean hiInclusive) {
this.set = set; this.set = set;
this.start = start; this.start = start;
this.end = end; this.end = end;
this.fromStart = fromStart; this.fromStart = fromStart;
@@ -853,10 +982,12 @@ public class RB_TREE_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE
#endif #endif
boolean tooLow(KEY_TYPE key) { return !fromStart && (loInclusive ? set.compare(key, start) < 0 : set.compare(key, start) <= 0); } boolean tooLow(KEY_TYPE key) { return !fromStart && (loInclusive ? set.compare(key, start) < 0 : set.compare(key, start) <= 0); }
boolean tooHigh(KEY_TYPE key) { return !toEnd && (hiInclusive ? set.compare(key, end) > 0 : set.compare(key, end) >= 0); } boolean tooHigh(KEY_TYPE key) { return !toEnd && (hiInclusive ? set.compare(key, end) > 0 : set.compare(key, end) >= 0); }
boolean inRange(KEY_TYPE key) { return !tooLow(key) && !tooHigh(key); } boolean inRange(KEY_TYPE key) { return !tooLow(key) && !tooHigh(key); }
boolean inClosedRange(KEY_TYPE key) { return (fromStart || set.compare(key, start) >= 0) && (toEnd || set.compare(end, key) >= 0); } boolean inClosedRange(KEY_TYPE key) { return (fromStart || set.compare(key, start) >= 0) && (toEnd || set.compare(end, key) >= 0); }
boolean inRange(KEY_TYPE key, boolean inclusive) { return inclusive ? inRange(key) : inClosedRange(key); } boolean inRange(KEY_TYPE key, boolean inclusive) { return inclusive ? inRange(key) : inClosedRange(key); }
protected Entry KEY_GENERIC_TYPE next(Entry KEY_GENERIC_TYPE entry) { return entry.next(); }
protected Entry KEY_GENERIC_TYPE start() { return findLowest(); }
@Override @Override
public boolean addAndMoveToFirst(KEY_TYPE o) { throw new UnsupportedOperationException(); } public boolean addAndMoveToFirst(KEY_TYPE o) { throw new UnsupportedOperationException(); }
@@ -999,6 +1130,109 @@ public class RB_TREE_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE
return fromStart && toEnd ? set.size() : iterator().skip(Integer.MAX_VALUE); return fromStart && toEnd ? set.size() : iterator().skip(Integer.MAX_VALUE);
} }
@Override
public SubSet KEY_GENERIC_TYPE copy() { throw new UnsupportedOperationException(); }
@Override
public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) {
Objects.requireNonNull(action);
for(Entry KEY_GENERIC_TYPE entry = start();entry != null && inRange(entry.key);entry = next(entry)) {
action.accept(entry.key);
}
}
@Override
public <E> void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
for(Entry KEY_GENERIC_TYPE entry = start();entry != null && inRange(entry.key);entry = next(entry))
action.accept(input, entry.key);
}
@Override
public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(Entry KEY_GENERIC_TYPE entry = start();entry != null && inRange(entry.key);entry = next(entry)) {
if(filter.TEST_VALUE(entry.key)) return true;
}
return false;
}
@Override
public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(Entry KEY_GENERIC_TYPE entry = start();entry != null && inRange(entry.key);entry = next(entry)) {
if(filter.TEST_VALUE(entry.key)) return false;
}
return true;
}
@Override
public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(Entry KEY_GENERIC_TYPE entry = start();entry != null && inRange(entry.key);entry = next(entry)) {
if(!filter.TEST_VALUE(entry.key)) return false;
}
return true;
}
#if !TYPE_OBJECT
@Override
public KEY_TYPE reduce(KEY_TYPE identity, UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
KEY_TYPE state = identity;
for(Entry KEY_GENERIC_TYPE entry = start();entry != null && inRange(entry.key);entry = next(entry)) {
state = operator.APPLY_VALUE(state, entry.key);
}
return state;
}
#else
@Override
public <KEY_SPECIAL_TYPE> KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction<KEY_SPECIAL_TYPE, KEY_TYPE, KEY_SPECIAL_TYPE> operator) {
Objects.requireNonNull(operator);
KEY_SPECIAL_TYPE state = identity;
for(Entry KEY_GENERIC_TYPE entry = start();entry != null && inRange(entry.key);entry = next(entry)) {
state = operator.APPLY_VALUE(state, entry.key);
}
return state;
}
#endif
@Override
public KEY_TYPE reduce(UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
Objects.requireNonNull(operator);
KEY_TYPE state = EMPTY_VALUE;
boolean empty = true;
for(Entry KEY_GENERIC_TYPE entry = start();entry != null && inRange(entry.key);entry = next(entry)) {
if(empty) {
empty = false;
state = entry.key;
continue;
}
state = operator.APPLY_VALUE(state, entry.key);
}
return state;
}
@Override
public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(Entry KEY_GENERIC_TYPE entry = start();entry != null && inRange(entry.key);entry = next(entry)) {
if(filter.TEST_VALUE(entry.key)) return entry.key;
}
return EMPTY_VALUE;
}
@Override
public int count(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
int result = 0;
for(Entry KEY_GENERIC_TYPE entry = start();entry != null && inRange(entry.key);entry = next(entry)) {
if(filter.TEST_VALUE(entry.key)) result++;
}
return result;
}
class SubSetIterator implements LIST_ITERATOR KEY_GENERIC_TYPE class SubSetIterator implements LIST_ITERATOR KEY_GENERIC_TYPE
{ {
Entry KEY_GENERIC_TYPE previous; Entry KEY_GENERIC_TYPE previous;
@@ -1182,6 +1416,22 @@ public class RB_TREE_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE
this.parent = parent; this.parent = parent;
} }
Entry KEY_GENERIC_TYPE copy() {
Entry KEY_GENERIC_TYPE entry = new EntryBRACES(key, null);
entry.state = state;
if(left != null) {
Entry KEY_GENERIC_TYPE newLeft = left.copy();
entry.left = newLeft;
newLeft.parent = entry;
}
if(right != null) {
Entry KEY_GENERIC_TYPE newRight = right.copy();
entry.right = newRight;
newRight.parent = entry;
}
return entry;
}
boolean isBlack() { boolean isBlack() {
return (state & BLACK) != 0; return (state & BLACK) != 0;
} }
@@ -5,8 +5,12 @@ import java.util.Set;
import speiger.src.collections.PACKAGE.collections.COLLECTION; import speiger.src.collections.PACKAGE.collections.COLLECTION;
import speiger.src.collections.PACKAGE.collections.ITERATOR; import speiger.src.collections.PACKAGE.collections.ITERATOR;
import speiger.src.collections.PACKAGE.collections.SPLIT_ITERATOR; import speiger.src.collections.PACKAGE.collections.SPLIT_ITERATOR;
#if !TYPE_BOOLEAN
import speiger.src.collections.PACKAGE.utils.SETS;
#endif
import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS; import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS;
/** /**
* A Type Specific Set class to reduce boxing/unboxing * A Type Specific Set class to reduce boxing/unboxing
* @Type(T) * @Type(T)
@@ -16,6 +20,9 @@ public interface SET KEY_GENERIC_TYPE extends Set<CLASS_TYPE>, COLLECTION KEY_GE
@Override @Override
public ITERATOR KEY_GENERIC_TYPE iterator(); public ITERATOR KEY_GENERIC_TYPE iterator();
@Override
public SET KEY_GENERIC_TYPE copy();
#if !TYPE_OBJECT #if !TYPE_OBJECT
/** /**
* A Type Specific remove function to reduce boxing/unboxing * A Type Specific remove function to reduce boxing/unboxing
@@ -46,6 +53,31 @@ public interface SET KEY_GENERIC_TYPE extends Set<CLASS_TYPE>, COLLECTION KEY_GE
public default boolean remove(Object o) { public default boolean remove(Object o) {
return COLLECTION.super.remove(o); return COLLECTION.super.remove(o);
} }
#endif
#if !TYPE_BOOLEAN
/**
* Creates a Wrapped Set that is Synchronized
* @return a new Set that is synchronized
* @see SETS#synchronize
*/
public default SET KEY_GENERIC_TYPE synchronize() { return SETS.synchronize(this); }
/**
* Creates a Wrapped Set that is Synchronized
* @param mutex is the controller of the synchronization block
* @return a new Set Wrapper that is synchronized
* @see SETS#synchronize
*/
public default SET KEY_GENERIC_TYPE synchronize(Object mutex) { return SETS.synchronize(this, mutex); }
/**
* Creates a Wrapped Set that is unmodifiable
* @return a new Set Wrapper that is unmodifiable
* @see SETS#unmodifiable
*/
public default SET KEY_GENERIC_TYPE unmodifiable() { return SETS.unmodifiable(this); }
#endif #endif
/** /**
* A Type Specific Type Splititerator to reduce boxing/unboxing * A Type Specific Type Splititerator to reduce boxing/unboxing
@@ -9,6 +9,7 @@ import java.util.Comparator;
#else #else
import speiger.src.collections.PACKAGE.functions.COMPARATOR; import speiger.src.collections.PACKAGE.functions.COMPARATOR;
#endif #endif
import speiger.src.collections.PACKAGE.utils.SETS;
import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS; import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS;
/** /**
@@ -60,6 +61,9 @@ public interface SORTED_SET KEY_GENERIC_TYPE extends SET KEY_GENERIC_TYPE, Sorte
@Override @Override
public COMPARATOR KEY_GENERIC_TYPE comparator(); public COMPARATOR KEY_GENERIC_TYPE comparator();
@Override
public SORTED_SET KEY_GENERIC_TYPE copy();
@Override @Override
public BI_ITERATOR KEY_GENERIC_TYPE iterator(); public BI_ITERATOR KEY_GENERIC_TYPE iterator();
/** /**
@@ -70,6 +74,30 @@ public interface SORTED_SET KEY_GENERIC_TYPE extends SET KEY_GENERIC_TYPE, Sorte
*/ */
public BI_ITERATOR KEY_GENERIC_TYPE iterator(KEY_TYPE fromElement); public BI_ITERATOR KEY_GENERIC_TYPE iterator(KEY_TYPE fromElement);
#if !TYPE_BOOLEAN
/**
* Creates a Wrapped SortedSet that is Synchronized
* @return a new SortedSet that is synchronized
* @see SETS#synchronize
*/
public default SORTED_SET KEY_GENERIC_TYPE synchronize() { return SETS.synchronize(this); }
/**
* Creates a Wrapped SortedSet that is Synchronized
* @param mutex is the controller of the synchronization block
* @return a new SortedSet Wrapper that is synchronized
* @see SETS#synchronize
*/
public default SORTED_SET KEY_GENERIC_TYPE synchronize(Object mutex) { return SETS.synchronize(this, mutex); }
/**
* Creates a Wrapped SortedSet that is unmodifiable
* @return a new SortedSet Wrapper that is unmodifiable
* @see SETS#unmodifiable
*/
public default SORTED_SET KEY_GENERIC_TYPE unmodifiable() { return SETS.unmodifiable(this); }
#endif
/** /**
* A Type Specific Type Splititerator to reduce boxing/unboxing * A Type Specific Type Splititerator to reduce boxing/unboxing
* @return type specific splititerator * @return type specific splititerator
@@ -10,6 +10,9 @@ import speiger.src.collections.PACKAGE.functions.COMPARATOR;
import java.util.Comparator; import java.util.Comparator;
#endif #endif
import speiger.src.collections.PACKAGE.collections.ITERATOR;
import speiger.src.collections.PACKAGE.lists.ARRAY_LIST;
import speiger.src.collections.PACKAGE.utils.ITERATORS;
import speiger.src.collections.utils.SanityChecks; import speiger.src.collections.utils.SanityChecks;
/** /**
@@ -111,6 +114,28 @@ public class ARRAYS
} }
#endif #endif
/**
* A Helper function that pours all elements of a iterator into a Array
* @param iter the elements that should be gathered.
* @ArrayType(T)
* @return array with all elements of the iterator
*/
public static GENERIC_KEY_BRACES KEY_TYPE[] pour(ITERATOR KEY_GENERIC_TYPE iter) {
return pour(iter, Integer.MAX_VALUE);
}
/**
* A Helper function that pours all elements of a iterator into a Array
* @param iter the elements that should be gathered.
* @param max how many elements should be added
* @ArrayType(T)
* @return array with all requested elements of the iterator
*/
public static GENERIC_KEY_BRACES KEY_TYPE[] pour(ITERATOR KEY_GENERIC_TYPE iter, int max) {
ARRAY_LIST KEY_GENERIC_TYPE list = new ARRAY_LISTBRACES();
ITERATORS.pour(iter, list, max);
return list.TO_ARRAY(NEW_KEY_ARRAY(list.size()));
}
/** /**
* Method to validate if the current value is the lowest value in the heap * Method to validate if the current value is the lowest value in the heap
* @param data the current heap. * @param data the current heap.
@@ -205,6 +230,31 @@ public class ARRAYS
return shuffle(array, SanityChecks.getRandom()); return shuffle(array, SanityChecks.getRandom());
} }
/**
* Simple Shuffle method for Arrays.
* @param array the elements that should be shuffled
* @param length the length of the array
* @ArrayType(T)
* @note This uses the SanityChecks#getRandom
* @return the provided sorted array
*/
public static GENERIC_KEY_BRACES KEY_TYPE[] shuffle(KEY_TYPE[] array, int length) {
return shuffle(array, 0, length, SanityChecks.getRandom());
}
/**
* Simple Shuffle method for Arrays.
* @param array the elements that should be shuffled
* @param offset the start array
* @param length the length of the array
* @ArrayType(T)
* @note This uses the SanityChecks#getRandom
* @return the provided sorted array
*/
public static GENERIC_KEY_BRACES KEY_TYPE[] shuffle(KEY_TYPE[] array, int offset, int length) {
return shuffle(array, offset, length, SanityChecks.getRandom());
}
/** /**
* Simple Shuffle method for Arrays. * Simple Shuffle method for Arrays.
* @param array the elements that should be shuffled * @param array the elements that should be shuffled
@@ -222,6 +272,75 @@ public class ARRAYS
return array; return array;
} }
/**
* Simple Shuffle method for Arrays.
* @param array the elements that should be shuffled
* @param length the length of the array
* @param random the Random Number Generator that should be used for the shuffling
* @ArrayType(T)
* @return the provided sorted array
*/
public static GENERIC_KEY_BRACES KEY_TYPE[] shuffle(KEY_TYPE[] array, int length, Random random) {
return shuffle(array, 0, length, random);
}
/**
* Simple Shuffle method for Arrays.
* @param array the elements that should be shuffled
* @param offset the start array
* @param length the length of the array
* @param random the Random Number Generator that should be used for the shuffling
* @ArrayType(T)
* @return the provided sorted array
*/
public static GENERIC_KEY_BRACES KEY_TYPE[] shuffle(KEY_TYPE[] array, int offset, int length, Random random) {
for(int i = length-1; i>=0;i--) {
int p = offset + random.nextInt(i + 1);
KEY_TYPE t = array[offset+i];
array[offset+i] = array[p];
array[p] = t;
}
return array;
}
/**
* Simple Array Reversal method
* @param array the Array that should flip
* @ArrayType(T)
* @return the provided array
*/
public static GENERIC_KEY_BRACES KEY_TYPE[] reverse(KEY_TYPE[] array) {
return reverse(array, 0, array.length);
}
/**
* Simple Array Reversal method
* @param array the Array that should flip
* @param length the length of the array
* @ArrayType(T)
* @return the provided array
*/
public static GENERIC_KEY_BRACES KEY_TYPE[] reverse(KEY_TYPE[] array, int length) {
return reverse(array, 0, length);
}
/**
* Simple Array Reversal method
* @param array the Array that should flip
* @param length the length of the array
* @param offset the start of the array
* @ArrayType(T)
* @return the provided array
*/
public static GENERIC_KEY_BRACES KEY_TYPE[] reverse(KEY_TYPE[] array, int offset, int length) {
for (int i = offset, mid = offset + length >> 1, j = offset + length - 1; i < mid; i++, j--) {
KEY_TYPE temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
/** /**
* Sorts the specified range of elements according to the order induced by the specified comparator, * Sorts the specified range of elements according to the order induced by the specified comparator,
* potentially dynamically choosing an appropriate algorithm given the type and size of the array. * potentially dynamically choosing an appropriate algorithm given the type and size of the array.
@@ -268,7 +387,7 @@ public class ARRAYS
* @param array the array that needs to be sorted * @param array the array that needs to be sorted
* @ArrayType(T) * @ArrayType(T)
*/ */
public static COMPAREABLE_KEY_BRACES void stableSort(KEY_TYPE[] array) { public static GENERIC_KEY_BRACES void stableSort(KEY_TYPE[] array) {
stableSort(array, 0, array.length); stableSort(array, 0, array.length);
} }
@@ -280,7 +399,7 @@ public class ARRAYS
* @param length the maxmium size of the array to be sorted * @param length the maxmium size of the array to be sorted
* @ArrayType(T) * @ArrayType(T)
*/ */
public static COMPAREABLE_KEY_BRACES void stableSort(KEY_TYPE[] array, int length) { public static GENERIC_KEY_BRACES void stableSort(KEY_TYPE[] array, int length) {
stableSort(array, 0, length); stableSort(array, 0, length);
} }
@@ -293,7 +412,7 @@ public class ARRAYS
* @param to where the array should be sorted to * @param to where the array should be sorted to
* @ArrayType(T) * @ArrayType(T)
*/ */
public static COMPAREABLE_KEY_BRACES void stableSort(KEY_TYPE[] array, int from, int to) { public static GENERIC_KEY_BRACES void stableSort(KEY_TYPE[] array, int from, int to) {
mergeSort(array, null, from, to); mergeSort(array, null, from, to);
} }
@@ -343,7 +462,7 @@ public class ARRAYS
* @param array the array that needs to be sorted * @param array the array that needs to be sorted
* @ArrayType(T) * @ArrayType(T)
*/ */
public static COMPAREABLE_KEY_BRACES void unstableSort(KEY_TYPE[] array) { public static GENERIC_KEY_BRACES void unstableSort(KEY_TYPE[] array) {
unstableSort(array, 0, array.length); unstableSort(array, 0, array.length);
} }
@@ -355,7 +474,7 @@ public class ARRAYS
* @param length the maxmium size of the array to be sorted * @param length the maxmium size of the array to be sorted
* @ArrayType(T) * @ArrayType(T)
*/ */
public static COMPAREABLE_KEY_BRACES void unstableSort(KEY_TYPE[] array, int length) { public static GENERIC_KEY_BRACES void unstableSort(KEY_TYPE[] array, int length) {
unstableSort(array, 0, length); unstableSort(array, 0, length);
} }
@@ -368,7 +487,7 @@ public class ARRAYS
* @param to where the array should be sorted to * @param to where the array should be sorted to
* @ArrayType(T) * @ArrayType(T)
*/ */
public static COMPAREABLE_KEY_BRACES void unstableSort(KEY_TYPE[] array, int from, int to) { public static GENERIC_KEY_BRACES void unstableSort(KEY_TYPE[] array, int from, int to) {
quickSort(array, from, to); quickSort(array, from, to);
} }
@@ -417,7 +536,7 @@ public class ARRAYS
* @param array the array that needs to be sorted * @param array the array that needs to be sorted
* @ArrayType(T) * @ArrayType(T)
*/ */
public static COMPAREABLE_KEY_BRACES void insertionSort(KEY_TYPE[] array) { public static GENERIC_KEY_BRACES void insertionSort(KEY_TYPE[] array) {
insertionSort(array, 0, array.length); insertionSort(array, 0, array.length);
} }
@@ -427,7 +546,7 @@ public class ARRAYS
* @param length the maxmium size of the array to be sorted * @param length the maxmium size of the array to be sorted
* @ArrayType(T) * @ArrayType(T)
*/ */
public static COMPAREABLE_KEY_BRACES void insertionSort(KEY_TYPE[] array, int length) { public static GENERIC_KEY_BRACES void insertionSort(KEY_TYPE[] array, int length) {
insertionSort(array, 0, length); insertionSort(array, 0, length);
} }
@@ -438,14 +557,14 @@ public class ARRAYS
* @param to where the array should be sorted to * @param to where the array should be sorted to
* @ArrayType(T) * @ArrayType(T)
*/ */
public static COMPAREABLE_KEY_BRACES void insertionSort(KEY_TYPE[] array, int from, int to) { public static GENERIC_KEY_BRACES void insertionSort(KEY_TYPE[] array, int from, int to) {
for (int i = from+1;i<to; i++) { for (int i = from+1;i<to; i++) {
KEY_TYPE current = array[i]; KEY_TYPE current = array[i];
int j = i - 1; int j = i - 1;
while(j >= from && COMPAREABLE_TO_KEY(current, array[j]) < 0) { while(j >= from && COMPAREABLE_TO_KEY(current, array[j]) < 0) {
array[j+1] = array[j--]; array[j+1] = array[j--];
} }
array[j+1] = current; array[j+1] = current;
} }
} }
@@ -479,19 +598,19 @@ public class ARRAYS
* @ArrayType(T) * @ArrayType(T)
*/ */
public static GENERIC_KEY_BRACES void selectionSort(KEY_TYPE[] array, int from, int to, COMPARATOR KEY_GENERIC_TYPE comp) { public static GENERIC_KEY_BRACES void selectionSort(KEY_TYPE[] array, int from, int to, COMPARATOR KEY_GENERIC_TYPE comp) {
for (int i = from; i < to; i++) { for (int i = from; i < to; i++) {
KEY_TYPE min = array[i]; KEY_TYPE min = array[i];
int minId = i; int minId = i;
for(int j = i+1; j < to; j++) { for(int j = i+1; j < to; j++) {
if(comp.compare(array[j], min) < 0) { if(comp.compare(array[j], min) < 0) {
min = array[j]; min = array[j];
minId = j; minId = j;
} }
} }
KEY_TYPE temp = array[i]; KEY_TYPE temp = array[i];
array[i] = min; array[i] = min;
array[minId] = temp; array[minId] = temp;
} }
} }
/** /**
@@ -499,7 +618,7 @@ public class ARRAYS
* @param array the array that needs to be sorted * @param array the array that needs to be sorted
* @ArrayType(T) * @ArrayType(T)
*/ */
public static COMPAREABLE_KEY_BRACES void selectionSort(KEY_TYPE[] array) { public static GENERIC_KEY_BRACES void selectionSort(KEY_TYPE[] array) {
selectionSort(array, 0, array.length); selectionSort(array, 0, array.length);
} }
@@ -509,7 +628,7 @@ public class ARRAYS
* @param length the maxmium size of the array to be sorted * @param length the maxmium size of the array to be sorted
* @ArrayType(T) * @ArrayType(T)
*/ */
public static COMPAREABLE_KEY_BRACES void selectionSort(KEY_TYPE[] array, int length) { public static GENERIC_KEY_BRACES void selectionSort(KEY_TYPE[] array, int length) {
selectionSort(array, 0, length); selectionSort(array, 0, length);
} }
@@ -520,20 +639,20 @@ public class ARRAYS
* @param to where the array should be sorted to * @param to where the array should be sorted to
* @ArrayType(T) * @ArrayType(T)
*/ */
public static COMPAREABLE_KEY_BRACES void selectionSort(KEY_TYPE[] array, int from, int to) { public static GENERIC_KEY_BRACES void selectionSort(KEY_TYPE[] array, int from, int to) {
for (int i = from; i < to; i++) { for (int i = from; i < to; i++) {
KEY_TYPE min = array[i]; KEY_TYPE min = array[i];
int minId = i; int minId = i;
for(int j = i+1; j < to; j++) { for(int j = i+1; j < to; j++) {
if(COMPAREABLE_TO_KEY(array[j], min) < 0) { if(COMPAREABLE_TO_KEY(array[j], min) < 0) {
min = array[j]; min = array[j];
minId = j; minId = j;
} }
} }
KEY_TYPE temp = array[i]; KEY_TYPE temp = array[i];
array[i] = min; array[i] = min;
array[minId] = temp; array[minId] = temp;
} }
} }
/** /**
@@ -595,7 +714,7 @@ public class ARRAYS
* @param array the array that needs to be sorted * @param array the array that needs to be sorted
* @ArrayType(T) * @ArrayType(T)
*/ */
public static COMPAREABLE_KEY_BRACES void mergeSort(KEY_TYPE[] array) { public static GENERIC_KEY_BRACES void mergeSort(KEY_TYPE[] array) {
mergeSort(array, null, 0, array.length); mergeSort(array, null, 0, array.length);
} }
@@ -606,7 +725,7 @@ public class ARRAYS
* @param length the maxmium size of the array to be sorted * @param length the maxmium size of the array to be sorted
* @ArrayType(T) * @ArrayType(T)
*/ */
public static COMPAREABLE_KEY_BRACES void mergeSort(KEY_TYPE[] array, int length) { public static GENERIC_KEY_BRACES void mergeSort(KEY_TYPE[] array, int length) {
mergeSort(array, null, 0, length); mergeSort(array, null, 0, length);
} }
@@ -619,7 +738,7 @@ public class ARRAYS
* @param to where the array should be sorted to * @param to where the array should be sorted to
* @ArrayType(T) * @ArrayType(T)
*/ */
public static COMPAREABLE_KEY_BRACES void mergeSort(KEY_TYPE[] array, KEY_TYPE[] supp, int from, int to) { public static GENERIC_KEY_BRACES void mergeSort(KEY_TYPE[] array, KEY_TYPE[] supp, int from, int to) {
if(to - from < BASE_THRESHOLD) { if(to - from < BASE_THRESHOLD) {
insertionSort(array, from, to); insertionSort(array, from, to);
return; return;
@@ -690,7 +809,7 @@ public class ARRAYS
* @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed * @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed
* @ArrayType(T) * @ArrayType(T)
*/ */
public static COMPAREABLE_KEY_BRACES void parallelMergeSort(KEY_TYPE[] array) { public static GENERIC_KEY_BRACES void parallelMergeSort(KEY_TYPE[] array) {
parallelMergeSort(array, null, 0, array.length); parallelMergeSort(array, null, 0, array.length);
} }
@@ -702,7 +821,7 @@ public class ARRAYS
* @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed * @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed
* @ArrayType(T) * @ArrayType(T)
*/ */
public static COMPAREABLE_KEY_BRACES void parallelMergeSort(KEY_TYPE[] array, int length) { public static GENERIC_KEY_BRACES void parallelMergeSort(KEY_TYPE[] array, int length) {
parallelMergeSort(array, null, 0, length); parallelMergeSort(array, null, 0, length);
} }
@@ -716,7 +835,7 @@ public class ARRAYS
* @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed * @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed
* @ArrayType(T) * @ArrayType(T)
*/ */
public static COMPAREABLE_KEY_BRACES void parallelMergeSort(KEY_TYPE[] array, KEY_TYPE[] supp, int from, int to) { public static GENERIC_KEY_BRACES void parallelMergeSort(KEY_TYPE[] array, KEY_TYPE[] supp, int from, int to) {
if(SanityChecks.canParallelTask() && to - from >= PARALLEL_THRESHOLD) { if(SanityChecks.canParallelTask() && to - from >= PARALLEL_THRESHOLD) {
SanityChecks.invokeTask(new MergeSortActionBRACES(array, supp, from, to)); SanityChecks.invokeTask(new MergeSortActionBRACES(array, supp, from, to));
return; return;
@@ -804,7 +923,7 @@ public class ARRAYS
* @param array the array that needs to be sorted * @param array the array that needs to be sorted
* @ArrayType(T) * @ArrayType(T)
*/ */
public static COMPAREABLE_KEY_BRACES void memFreeMergeSort(KEY_TYPE[] array) { public static GENERIC_KEY_BRACES void memFreeMergeSort(KEY_TYPE[] array) {
memFreeMergeSort(array, 0, array.length); memFreeMergeSort(array, 0, array.length);
} }
@@ -818,7 +937,7 @@ public class ARRAYS
* @param length the maxmium size of the array to be sorted * @param length the maxmium size of the array to be sorted
* @ArrayType(T) * @ArrayType(T)
*/ */
public static COMPAREABLE_KEY_BRACES void memFreeMergeSort(KEY_TYPE[] array, int length) { public static GENERIC_KEY_BRACES void memFreeMergeSort(KEY_TYPE[] array, int length) {
memFreeMergeSort(array, 0, length); memFreeMergeSort(array, 0, length);
} }
@@ -833,7 +952,7 @@ public class ARRAYS
* @param to where the array should be sorted to * @param to where the array should be sorted to
* @ArrayType(T) * @ArrayType(T)
*/ */
public static COMPAREABLE_KEY_BRACES void memFreeMergeSort(KEY_TYPE[] array, int from, int to) { public static GENERIC_KEY_BRACES void memFreeMergeSort(KEY_TYPE[] array, int from, int to) {
if(to - from < BASE_THRESHOLD) { if(to - from < BASE_THRESHOLD) {
insertionSort(array, from, to); insertionSort(array, from, to);
return; return;
@@ -934,7 +1053,7 @@ public class ARRAYS
* @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed * @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed
* @ArrayType(T) * @ArrayType(T)
*/ */
public static COMPAREABLE_KEY_BRACES void parallelMemFreeMergeSort(KEY_TYPE[] array) { public static GENERIC_KEY_BRACES void parallelMemFreeMergeSort(KEY_TYPE[] array) {
parallelMemFreeMergeSort(array, 0, array.length); parallelMemFreeMergeSort(array, 0, array.length);
} }
@@ -949,7 +1068,7 @@ public class ARRAYS
* @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed * @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed
* @ArrayType(T) * @ArrayType(T)
*/ */
public static COMPAREABLE_KEY_BRACES void parallelMemFreeMergeSort(KEY_TYPE[] array, int length) { public static GENERIC_KEY_BRACES void parallelMemFreeMergeSort(KEY_TYPE[] array, int length) {
parallelMemFreeMergeSort(array, 0, length); parallelMemFreeMergeSort(array, 0, length);
} }
@@ -965,7 +1084,7 @@ public class ARRAYS
* @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed * @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed
* @ArrayType(T) * @ArrayType(T)
*/ */
public static COMPAREABLE_KEY_BRACES void parallelMemFreeMergeSort(KEY_TYPE[] array, int from, int to) { public static GENERIC_KEY_BRACES void parallelMemFreeMergeSort(KEY_TYPE[] array, int from, int to) {
if(SanityChecks.canParallelTask() && to - from >= PARALLEL_THRESHOLD) { if(SanityChecks.canParallelTask() && to - from >= PARALLEL_THRESHOLD) {
SanityChecks.invokeTask(new MemFreeMergeSortActionBRACES(array, from, to)); SanityChecks.invokeTask(new MemFreeMergeSortActionBRACES(array, from, to));
return; return;
@@ -1039,7 +1158,7 @@ public class ARRAYS
* @param array the array that needs to be sorted * @param array the array that needs to be sorted
* @ArrayType(T) * @ArrayType(T)
*/ */
public static COMPAREABLE_KEY_BRACES void quickSort(KEY_TYPE[] array) { public static GENERIC_KEY_BRACES void quickSort(KEY_TYPE[] array) {
quickSort(array, 0, array.length); quickSort(array, 0, array.length);
} }
@@ -1051,7 +1170,7 @@ public class ARRAYS
* @param length the maxmium size of the array to be sorted * @param length the maxmium size of the array to be sorted
* @ArrayType(T) * @ArrayType(T)
*/ */
public static COMPAREABLE_KEY_BRACES void quickSort(KEY_TYPE[] array, int length) { public static GENERIC_KEY_BRACES void quickSort(KEY_TYPE[] array, int length) {
quickSort(array, 0, length); quickSort(array, 0, length);
} }
@@ -1064,7 +1183,7 @@ public class ARRAYS
* @param to where the array should be sorted to * @param to where the array should be sorted to
* @ArrayType(T) * @ArrayType(T)
*/ */
public static COMPAREABLE_KEY_BRACES void quickSort(KEY_TYPE[] array, int from, int to) { public static GENERIC_KEY_BRACES void quickSort(KEY_TYPE[] array, int from, int to) {
int length = to - from; int length = to - from;
if(length <= 0) return; if(length <= 0) return;
if(length < BASE_THRESHOLD) { if(length < BASE_THRESHOLD) {
@@ -1142,7 +1261,7 @@ public class ARRAYS
* @ArrayType(T) * @ArrayType(T)
* @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed * @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed
*/ */
public static COMPAREABLE_KEY_BRACES void parallelQuickSort(KEY_TYPE[] array) { public static GENERIC_KEY_BRACES void parallelQuickSort(KEY_TYPE[] array) {
parallelQuickSort(array, 0, array.length); parallelQuickSort(array, 0, array.length);
} }
@@ -1155,7 +1274,7 @@ public class ARRAYS
* @ArrayType(T) * @ArrayType(T)
* @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed * @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed
*/ */
public static COMPAREABLE_KEY_BRACES void parallelQuickSort(KEY_TYPE[] array, int length) { public static GENERIC_KEY_BRACES void parallelQuickSort(KEY_TYPE[] array, int length) {
parallelQuickSort(array, 0, length); parallelQuickSort(array, 0, length);
} }
@@ -1169,7 +1288,7 @@ public class ARRAYS
* @ArrayType(T) * @ArrayType(T)
* @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed * @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed
*/ */
public static COMPAREABLE_KEY_BRACES void parallelQuickSort(KEY_TYPE[] array, int from, int to) { public static GENERIC_KEY_BRACES void parallelQuickSort(KEY_TYPE[] array, int from, int to) {
if(SanityChecks.canParallelTask() && to - from >= PARALLEL_THRESHOLD) { if(SanityChecks.canParallelTask() && to - from >= PARALLEL_THRESHOLD) {
SanityChecks.invokeTask(new QuickSortActionBRACES(array, from, to)); SanityChecks.invokeTask(new QuickSortActionBRACES(array, from, to));
return; return;
@@ -1196,15 +1315,15 @@ public class ARRAYS
return comp.compare(data[a], data[b]) < 0 ? (comp.compare(data[b], data[c]) < 0 ? b : comp.compare(data[a], data[c]) < 0 ? c : a) : (comp.compare(data[b], data[c]) > 0 ? b : comp.compare(data[a], data[c]) > 0 ? c : a); return comp.compare(data[a], data[b]) < 0 ? (comp.compare(data[b], data[c]) < 0 ? b : comp.compare(data[a], data[c]) < 0 ? c : a) : (comp.compare(data[b], data[c]) > 0 ? b : comp.compare(data[a], data[c]) > 0 ? c : a);
} }
static COMPAREABLE_KEY_BRACES int subMedium(KEY_TYPE[] data, int a, int b, int c, int length) { static GENERIC_KEY_BRACES int subMedium(KEY_TYPE[] data, int a, int b, int c, int length) {
return medium(data, medium(data, a, a + length, a + (length * 2)), medium(data, b - length, b, b + length), medium(data, c - (length * 2), c - length, c)); return medium(data, medium(data, a, a + length, a + (length * 2)), medium(data, b - length, b, b + length), medium(data, c - (length * 2), c - length, c));
} }
static COMPAREABLE_KEY_BRACES int medium(KEY_TYPE[] data, int a, int b, int c) { static GENERIC_KEY_BRACES int medium(KEY_TYPE[] data, int a, int b, int c) {
return COMPAREABLE_TO_KEY(data[a], data[b]) < 0 ? (COMPAREABLE_TO_KEY(data[b], data[c]) < 0 ? b : COMPAREABLE_TO_KEY(data[a], data[c]) < 0 ? c : a) : (COMPAREABLE_TO_KEY(data[b], data[c]) > 0 ? b : COMPAREABLE_TO_KEY(data[a], data[c]) > 0 ? c : a); return COMPAREABLE_TO_KEY(data[a], data[b]) < 0 ? (COMPAREABLE_TO_KEY(data[b], data[c]) < 0 ? b : COMPAREABLE_TO_KEY(data[a], data[c]) < 0 ? c : a) : (COMPAREABLE_TO_KEY(data[b], data[c]) > 0 ? b : COMPAREABLE_TO_KEY(data[a], data[c]) > 0 ? c : a);
} }
static class QuickSortAction KEY_COMPAREABLE_TYPE extends RecursiveAction { static class QuickSortAction KEY_GENERIC_TYPE extends RecursiveAction {
private static final long serialVersionUID = 0L; private static final long serialVersionUID = 0L;
KEY_TYPE[] array; KEY_TYPE[] array;
int from; int from;
@@ -1288,7 +1407,7 @@ public class ARRAYS
} }
} }
static class MergeSortAction KEY_COMPAREABLE_TYPE extends RecursiveAction { static class MergeSortAction KEY_GENERIC_TYPE extends RecursiveAction {
private static final long serialVersionUID = 0L; private static final long serialVersionUID = 0L;
KEY_TYPE[] array; KEY_TYPE[] array;
KEY_TYPE[] supp; KEY_TYPE[] supp;
@@ -1312,7 +1431,7 @@ public class ARRAYS
} }
if(supp == null) supp = Arrays.copyOf(array, to); if(supp == null) supp = Arrays.copyOf(array, to);
int mid = (from + to) >>> 1; int mid = (from + to) >>> 1;
invokeAll(new MergeSortActionBRACES(supp, array, from, mid), new MergeSortActionBRACES(supp, array, mid, to)); invokeAll(new MergeSortActionBRACES(supp, array, from, mid), new MergeSortActionBRACES(supp, array, mid, to));
if(COMPAREABLE_TO_KEY(supp[mid - 1], supp[mid]) <= 0) if(COMPAREABLE_TO_KEY(supp[mid - 1], supp[mid]) <= 0)
{ {
System.arraycopy(supp, from, array, from, to - from); System.arraycopy(supp, from, array, from, to - from);
@@ -1351,7 +1470,7 @@ public class ARRAYS
} }
if(supp == null) supp = Arrays.copyOf(array, to); if(supp == null) supp = Arrays.copyOf(array, to);
int mid = (from + to) >>> 1; int mid = (from + to) >>> 1;
invokeAll(new MergeSortActionCompBRACES(supp, array, from, mid, comp), new MergeSortActionCompBRACES(supp, array, mid, to, comp)); invokeAll(new MergeSortActionCompBRACES(supp, array, from, mid, comp), new MergeSortActionCompBRACES(supp, array, mid, to, comp));
if(comp.compare(supp[mid - 1], supp[mid]) <= 0) if(comp.compare(supp[mid - 1], supp[mid]) <= 0)
{ {
System.arraycopy(supp, from, array, from, to - from); System.arraycopy(supp, from, array, from, to - from);
@@ -1364,7 +1483,7 @@ public class ARRAYS
} }
} }
static class MemFreeMergeSortAction KEY_COMPAREABLE_TYPE extends RecursiveAction { static class MemFreeMergeSortAction KEY_GENERIC_TYPE extends RecursiveAction {
private static final long serialVersionUID = 0L; private static final long serialVersionUID = 0L;
KEY_TYPE[] array; KEY_TYPE[] array;
int from; int from;
@@ -1,19 +1,26 @@
package speiger.src.collections.PACKAGE.utils; package speiger.src.collections.PACKAGE.utils;
import java.util.Collection; import java.util.Collection;
#if TYPE_OBJECT
import java.util.function.BiFunction;
#endif
import java.util.function.Predicate; import java.util.function.Predicate;
#if PRIMITIVES #if PRIMITIVES
import java.util.function.JAVA_PREDICATE; import java.util.function.JAVA_PREDICATE;
#endif #endif
import java.util.function.Consumer;
import speiger.src.collections.PACKAGE.collections.ABSTRACT_COLLECTION; import speiger.src.collections.PACKAGE.collections.ABSTRACT_COLLECTION;
import speiger.src.collections.PACKAGE.collections.COLLECTION; import speiger.src.collections.PACKAGE.collections.COLLECTION;
import speiger.src.collections.PACKAGE.collections.ITERATOR; import speiger.src.collections.PACKAGE.collections.ITERATOR;
import speiger.src.collections.objects.utils.ObjectArrays; import speiger.src.collections.objects.utils.ObjectArrays;
#if !TYPE_OBJECT #if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.functions.CONSUMER;
import speiger.src.collections.PACKAGE.utils.ARRAYS; import speiger.src.collections.PACKAGE.utils.ARRAYS;
#endif #endif
import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR;
import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER;
/** /**
* A Helper class for Collections * A Helper class for Collections
*/ */
@@ -29,7 +36,7 @@ public class COLLECTIONS
* @Type(T) * @Type(T)
* @return an empty collection * @return an empty collection
*/ */
public static GENERIC_KEY_BRACES COLLECTION KEY_GENERIC_TYPE emptyCollection() { public static GENERIC_KEY_BRACES COLLECTION KEY_GENERIC_TYPE empty() {
#if TYPE_OBJECT #if TYPE_OBJECT
return (COLLECTION<KEY_TYPE>)EMPTY; return (COLLECTION<KEY_TYPE>)EMPTY;
#else #else
@@ -43,7 +50,7 @@ public class COLLECTIONS
* @Type(T) * @Type(T)
* @return a unmodifiable collection wrapper. If the Collection already a unmodifiable wrapper then it just returns itself. * @return a unmodifiable collection wrapper. If the Collection already a unmodifiable wrapper then it just returns itself.
*/ */
public static GENERIC_KEY_BRACES COLLECTION KEY_GENERIC_TYPE unmodifiableCollection(COLLECTION KEY_GENERIC_TYPE c) { public static GENERIC_KEY_BRACES COLLECTION KEY_GENERIC_TYPE unmodifiable(COLLECTION KEY_GENERIC_TYPE c) {
return c instanceof UnmodifiableCollection ? c : new UnmodifiableCollectionBRACES(c); return c instanceof UnmodifiableCollection ? c : new UnmodifiableCollectionBRACES(c);
} }
@@ -53,7 +60,7 @@ public class COLLECTIONS
* @Type(T) * @Type(T)
* @return a synchronized collection wrapper. If the Collection already a synchronized wrapper then it just returns itself. * @return a synchronized collection wrapper. If the Collection already a synchronized wrapper then it just returns itself.
*/ */
public static GENERIC_KEY_BRACES COLLECTION KEY_GENERIC_TYPE synchronizedCollection(COLLECTION KEY_GENERIC_TYPE c) { public static GENERIC_KEY_BRACES COLLECTION KEY_GENERIC_TYPE synchronize(COLLECTION KEY_GENERIC_TYPE c) {
return c instanceof SynchronizedCollection ? c : new SynchronizedCollectionBRACES(c); return c instanceof SynchronizedCollection ? c : new SynchronizedCollectionBRACES(c);
} }
@@ -64,7 +71,7 @@ public class COLLECTIONS
* @Type(T) * @Type(T)
* @return a synchronized collection wrapper. If the Collection already a synchronized wrapper then it just returns itself. * @return a synchronized collection wrapper. If the Collection already a synchronized wrapper then it just returns itself.
*/ */
public static GENERIC_KEY_BRACES COLLECTION KEY_GENERIC_TYPE synchronizedCollection(COLLECTION KEY_GENERIC_TYPE c, Object mutex) { public static GENERIC_KEY_BRACES COLLECTION KEY_GENERIC_TYPE synchronize(COLLECTION KEY_GENERIC_TYPE c, Object mutex) {
return c instanceof SynchronizedCollection ? c : new SynchronizedCollectionBRACES(c, mutex); return c instanceof SynchronizedCollection ? c : new SynchronizedCollectionBRACES(c, mutex);
} }
@@ -90,18 +97,16 @@ public class COLLECTIONS
public boolean add(KEY_TYPE o) { synchronized(mutex) { return c.add(o); } } public boolean add(KEY_TYPE o) { synchronized(mutex) { return c.add(o); } }
@Override @Override
public boolean addAll(Collection<? extends CLASS_TYPE> c) { synchronized(mutex) { return this.c.addAll(c); } } public boolean addAll(Collection<? extends CLASS_TYPE> c) { synchronized(mutex) { return this.c.addAll(c); } }
@Override @Override
public boolean addAll(COLLECTION KEY_GENERIC_TYPE c) { synchronized(mutex) { return this.c.addAll(c); } } public boolean addAll(COLLECTION KEY_GENERIC_TYPE c) { synchronized(mutex) { return this.c.addAll(c); } }
@Override
public boolean addAll(KEY_TYPE[] e, int offset, int length) { synchronized(mutex) { return c.addAll(e, offset, length); } }
#if !TYPE_OBJECT #if !TYPE_OBJECT
@Override @Override
public boolean contains(KEY_TYPE o) { synchronized(mutex) { return c.contains(o); } } public boolean contains(KEY_TYPE o) { synchronized(mutex) { return c.contains(o); } }
#else #else
@Override @Override
public boolean contains(Object o) { synchronized(mutex) { return c.contains(o); } } public boolean contains(Object o) { synchronized(mutex) { return c.contains(o); } }
#endif #endif
@Override @Override
@Primitive @Primitive
@@ -128,6 +133,9 @@ public class COLLECTIONS
return c.iterator(); return c.iterator();
} }
@Override
public COLLECTION KEY_GENERIC_TYPE copy() { synchronized(mutex) { return c.copy(); } }
@Override @Override
@Primitive @Primitive
public boolean remove(Object o) { synchronized(mutex) { return c.remove(o); } } public boolean remove(Object o) { synchronized(mutex) { return c.remove(o); } }
@@ -144,30 +152,63 @@ public class COLLECTIONS
@Override @Override
public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c) { synchronized(mutex) { return this.c.removeAll(c); } } public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c) { synchronized(mutex) { return this.c.removeAll(c); } }
@Override @Override
public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c, CONSUMER KEY_GENERIC_TYPE r) { synchronized(mutex) { return this.c.removeAll(c, r); } }
@Override
public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c) { synchronized(mutex) { return this.c.retainAll(c); } } public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c) { synchronized(mutex) { return this.c.retainAll(c); } }
@Override
public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c, CONSUMER KEY_GENERIC_TYPE r) { synchronized(mutex) { return this.c.retainAll(c, r); } }
#if PRIMITIVES #if PRIMITIVES
@Override @Override
public boolean remIf(JAVA_PREDICATE filter){ synchronized(mutex) { return c.remIf(filter); } } public boolean remIf(JAVA_PREDICATE filter){ synchronized(mutex) { return c.remIf(filter); } }
#endif #endif
@Override @Override
public void clear() { synchronized(mutex) { c.clear(); } } public void clear() { synchronized(mutex) { c.clear(); } }
@Override @Override
public Object[] toArray() { synchronized(mutex) { return c.toArray(); } } public Object[] toArray() { synchronized(mutex) { return c.toArray(); } }
#if !TYPE_OBJECT #if !TYPE_OBJECT
@Override @Override
public <T> T[] toArray(T[] a) { synchronized(mutex) { return c.toArray(a); } } public <T> T[] toArray(T[] a) { synchronized(mutex) { return c.toArray(a); } }
@Override @Override
public KEY_TYPE[] TO_ARRAY() { synchronized(mutex) { return c.TO_ARRAY(); } } public KEY_TYPE[] TO_ARRAY() { synchronized(mutex) { return c.TO_ARRAY(); } }
@Override @Override
public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] a) { synchronized(mutex) { return c.TO_ARRAY(a); } } public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] a) { synchronized(mutex) { return c.TO_ARRAY(a); } }
@Override
public void forEach(CONSUMER action) { synchronized(mutex) { c.forEach(action); } }
@Override
@Deprecated
public void forEach(Consumer<? super CLASS_TYPE> action) { synchronized(mutex) { c.forEach(action); } }
#else #else
@Override @Override
public <E> E[] toArray(E[] a) { synchronized(mutex) { return c.toArray(a); } } public <E> E[] toArray(E[] a) { synchronized(mutex) { return c.toArray(a); } }
@Override
public void forEach(Consumer<? super CLASS_TYPE> action) { synchronized(mutex) { c.forEach(action); } }
#endif #endif
@Override
public int hashCode() { synchronized(mutex) { return c.hashCode(); } }
@Override
public boolean equals(Object obj) { synchronized(mutex) { return c.equals(obj); } }
@Override
public String toString() { synchronized(mutex) { return c.toString(); } }
@Override
public <E> void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE<E> action) { synchronized(mutex) { c.forEach(input, action); } }
@Override
public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) { synchronized(mutex) { return c.matchesAny(filter); } }
@Override
public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) { synchronized(mutex) { return c.matchesNone(filter); } }
@Override
public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) { synchronized(mutex) { return c.matchesAll(filter); } }
#if TYPE_OBJECT
public <KEY_SPECIAL_TYPE> KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction<KEY_SPECIAL_TYPE, KEY_TYPE, KEY_SPECIAL_TYPE> operator) { synchronized(mutex) { return c.reduce(identity, operator); } }
#else
@Override
public KEY_TYPE reduce(KEY_TYPE identity, UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { synchronized(mutex) { return c.reduce(identity, operator); } }
#endif
@Override
public KEY_TYPE reduce(UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { synchronized(mutex) { return c.reduce(operator); } }
@Override
public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) { synchronized(mutex) { return c.findFirst(filter); } }
@Override
public int count(PREDICATE KEY_GENERIC_TYPE filter) { synchronized(mutex) { return c.count(filter); } }
} }
/** /**
@@ -187,57 +228,33 @@ public class COLLECTIONS
public boolean addAll(Collection<? extends CLASS_TYPE> c) { throw new UnsupportedOperationException(); } public boolean addAll(Collection<? extends CLASS_TYPE> c) { throw new UnsupportedOperationException(); }
@Override @Override
public boolean addAll(COLLECTION KEY_GENERIC_TYPE c) { throw new UnsupportedOperationException(); } public boolean addAll(COLLECTION KEY_GENERIC_TYPE c) { throw new UnsupportedOperationException(); }
@Override
public boolean addAll(KEY_TYPE[] e, int offset, int length) { throw new UnsupportedOperationException(); }
#if !TYPE_OBJECT #if !TYPE_OBJECT
@Override @Override
public boolean contains(KEY_TYPE o) { public boolean contains(KEY_TYPE o) { return c.contains(o); }
return c.contains(o);
}
#else #else
@Override @Override
public boolean contains(Object o) { public boolean contains(Object o) { return c.contains(o); }
return c.contains(o);
}
#endif #endif
@Override @Override
public boolean containsAll(COLLECTION KEY_GENERIC_TYPE c) { public boolean containsAll(COLLECTION KEY_GENERIC_TYPE c) { return this.c.containsAll(c); }
return this.c.containsAll(c);
}
@Override @Override
public boolean containsAny(COLLECTION KEY_GENERIC_TYPE c) { public boolean containsAny(COLLECTION KEY_GENERIC_TYPE c) { return this.c.containsAny(c); }
return this.c.containsAny(c);
}
@Override @Override
@Primitive @Primitive
public boolean containsAny(Collection<?> c) { public boolean containsAny(Collection<?> c) { return this.c.containsAny(c); }
return this.c.containsAny(c);
}
@Override @Override
@Primitive @Primitive
public boolean containsAll(Collection<?> c) { public boolean containsAll(Collection<?> c) { return this.c.containsAll(c); }
return this.c.containsAll(c);
}
@Override @Override
public int size() { public int size() { return c.size(); }
return c.size();
}
@Override @Override
public boolean isEmpty() { public boolean isEmpty() { return c.isEmpty(); }
return c.isEmpty();
}
@Override @Override
public ITERATOR KEY_GENERIC_TYPE iterator() { public ITERATOR KEY_GENERIC_TYPE iterator() { return ITERATORS.unmodifiable(c.iterator()); }
return ITERATORS.unmodifiable(c.iterator()); @Override
} public COLLECTION KEY_GENERIC_TYPE copy() { return c.copy(); }
@Override @Override
@Deprecated @Deprecated
public boolean remove(Object o) { throw new UnsupportedOperationException(); } public boolean remove(Object o) { throw new UnsupportedOperationException(); }
@@ -257,42 +274,63 @@ public class COLLECTIONS
@Override @Override
public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c) { throw new UnsupportedOperationException(); } public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c) { throw new UnsupportedOperationException(); }
@Override @Override
public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c, CONSUMER KEY_GENERIC_TYPE r) { throw new UnsupportedOperationException(); }
@Override
public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c) { throw new UnsupportedOperationException(); } public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c) { throw new UnsupportedOperationException(); }
@Override
public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c, CONSUMER KEY_GENERIC_TYPE r) { throw new UnsupportedOperationException(); }
#if PRIMITIVES #if PRIMITIVES
@Override @Override
public boolean remIf(JAVA_PREDICATE filter){ throw new UnsupportedOperationException(); } public boolean remIf(JAVA_PREDICATE filter){ throw new UnsupportedOperationException(); }
#endif #endif
@Override @Override
public void clear() { throw new UnsupportedOperationException(); } public void clear() { throw new UnsupportedOperationException(); }
@Override @Override
public Object[] toArray() { public Object[] toArray() { return c.toArray(); }
return c.toArray();
}
#if !TYPE_OBJECT #if !TYPE_OBJECT
@Override @Override
public <T> T[] toArray(T[] a) { public <T> T[] toArray(T[] a) { return c.toArray(a); }
return c.toArray(a);
}
@Override @Override
public KEY_TYPE[] TO_ARRAY() { public KEY_TYPE[] TO_ARRAY() { return c.TO_ARRAY(); }
return c.TO_ARRAY();
}
@Override @Override
public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] a) { public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] a) { return c.TO_ARRAY(a); }
return c.TO_ARRAY(a); @Override
} public void forEach(CONSUMER action) { c.forEach(action); }
@Override
@Deprecated
public void forEach(Consumer<? super CLASS_TYPE> action) { c.forEach(action); }
#else #else
@Override @Override
public <E> E[] toArray(E[] a) { public <E> E[] toArray(E[] a) { return c.toArray(a); }
return c.toArray(a); @Override
} public void forEach(Consumer<? super CLASS_TYPE> action) { c.forEach(action); }
#endif #endif
@Override
public int hashCode() { return c.hashCode(); }
@Override
public boolean equals(Object obj) { return c.equals(obj); }
@Override
public String toString() { return c.toString(); }
@Override
public <E> void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE<E> action) { c.forEach(input, action); }
@Override
public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) { return c.matchesAny(filter); }
@Override
public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) { return c.matchesNone(filter); }
@Override
public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) { return c.matchesAll(filter); }
#if TYPE_OBJECT
public <KEY_SPECIAL_TYPE> KEY_SPECIAL_TYPE reduce(KEY_SPECIAL_TYPE identity, BiFunction<KEY_SPECIAL_TYPE, KEY_TYPE, KEY_SPECIAL_TYPE> operator) { return c.reduce(identity, operator); }
#else
@Override
public KEY_TYPE reduce(KEY_TYPE identity, UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { return c.reduce(identity, operator); }
#endif
@Override
public KEY_TYPE reduce(UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { return c.reduce(operator); }
@Override
public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) { return c.findFirst(filter); }
@Override
public int count(PREDICATE KEY_GENERIC_TYPE filter) { return c.count(filter); }
} }
/** /**
@@ -305,46 +343,28 @@ public class COLLECTIONS
@Override @Override
public boolean addAll(COLLECTION KEY_GENERIC_TYPE c) { throw new UnsupportedOperationException(); } public boolean addAll(COLLECTION KEY_GENERIC_TYPE c) { throw new UnsupportedOperationException(); }
@Override
public boolean addAll(KEY_TYPE[] e, int offset, int length) { throw new UnsupportedOperationException(); }
#if !TYPE_OBJECT #if !TYPE_OBJECT
@Override @Override
public boolean contains(KEY_TYPE o) { public boolean contains(KEY_TYPE o) { return false; }
return false;
}
@Override @Override
public boolean containsAll(COLLECTION KEY_GENERIC_TYPE c) { public boolean containsAll(COLLECTION KEY_GENERIC_TYPE c) { return false; }
return false;
}
@Override @Override
public boolean containsAny(COLLECTION KEY_GENERIC_TYPE c) { public boolean containsAny(COLLECTION KEY_GENERIC_TYPE c) { return false; }
return false;
}
#else #else
@Override @Override
public boolean contains(Object o) { public boolean contains(Object o) { return false; }
return false;
}
#endif #endif
@Override @Override
@Primitive @Primitive
public boolean containsAny(Collection<?> c) { public boolean containsAny(Collection<?> c) { return false; }
return false;
}
@Override @Override
@Primitive @Primitive
public boolean containsAll(Collection<?> c) { public boolean containsAll(Collection<?> c) { return false; }
return false;
}
@Override @Override
public int hashCode() { public int hashCode() { return 0; }
return 0;
}
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
@@ -377,47 +397,26 @@ public class COLLECTIONS
@Override @Override
public boolean remIf(JAVA_PREDICATE filter){ throw new UnsupportedOperationException(); } public boolean remIf(JAVA_PREDICATE filter){ throw new UnsupportedOperationException(); }
#endif #endif
@Override @Override
public Object[] toArray() { public Object[] toArray() { return ObjectArrays.EMPTY_ARRAY; }
return ObjectArrays.EMPTY_ARRAY;
}
#if !TYPE_OBJECT #if !TYPE_OBJECT
@Override @Override
public <T> T[] toArray(T[] a) { public <T> T[] toArray(T[] a) { return a; }
return a;
}
@Override @Override
public KEY_TYPE[] TO_ARRAY() { public KEY_TYPE[] TO_ARRAY() { return ARRAYS.EMPTY_ARRAY; }
return ARRAYS.EMPTY_ARRAY;
}
@Override @Override
public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] a) { public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] a) { return a; }
return a;
}
#else #else
@Override @Override
public <E> E[] toArray(E[] a) { public <E> E[] toArray(E[] a) { return a; }
return a;
}
#endif #endif
@Override @Override
public ITERATOR KEY_GENERIC_TYPE iterator() { public ITERATOR KEY_GENERIC_TYPE iterator() { return ITERATORS.empty(); }
return ITERATORS.emptyIterator();
}
@Override @Override
public void clear() { public void clear() {}
}
@Override @Override
public int size() { public int size() { return 0; }
return 0; @Override
} public EmptyCollection KEY_GENERIC_TYPE copy() { return this; }
} }
} }
@@ -0,0 +1,428 @@
package speiger.src.collections.PACKAGE.utils;
import java.util.Objects;
#if TYPE_BOOLEAN
import java.util.concurrent.atomic.AtomicInteger;
#endif
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Consumer;
import speiger.src.collections.PACKAGE.collections.ITERABLE;
#if !TYPE_OBJECT
import speiger.src.collections.objects.collections.ObjectIterable;
import speiger.src.collections.objects.collections.ObjectIterator;
import speiger.src.collections.PACKAGE.functions.CONSUMER;
#endif
import speiger.src.collections.PACKAGE.collections.ITERATOR;
import speiger.src.collections.PACKAGE.functions.function.TO_OBJECT_FUNCTION;
import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
#if !TYPE_BOOLEAN
import speiger.src.collections.PACKAGE.sets.HASH_SET;
import speiger.src.collections.PACKAGE.sets.SET;
#endif
/**
* A Helper class for Iterables
*/
public class ITERABLES
{
/**
* A Helper function that maps a Java-Iterable into a new Type.
* @param iterable the iterable that should be mapped
* @param mapper the function that decides what the result turns into.
* @Type(T)
* @param <E> The return type.
* @return a iterable that is mapped to a new result
*/
public static GENERIC_KEY_SPECIAL_BRACES<E> ObjectIterable<E> map(Iterable<? extends CLASS_TYPE> iterable, TO_OBJECT_FUNCTION KKS_GENERIC_TYPE<E> mapper) {
return new MappedIterable<>(wrap(iterable), mapper);
}
/**
* A Helper function that maps a Iterable into a new Type.
* @param iterable the iterable that should be mapped
* @param mapper the function that decides what the result turns into.
* @Type(T)
* @param <E> The return type.
* @return a iterable that is mapped to a new result
*/
public static GENERIC_KEY_SPECIAL_BRACES<E> ObjectIterable<E> map(ITERABLE KEY_GENERIC_TYPE iterable, TO_OBJECT_FUNCTION KKS_GENERIC_TYPE<E> mapper) {
return new MappedIterable<>(iterable, mapper);
}
/**
* A Helper function that flatMaps a Java-Iterable into a new Type.
* @param iterable the iterable that should be flatMapped
* @param mapper the function that decides what the result turns into.
* @Type(T)
* @param <V> The return type supplier.
* @param <E> The return type.
* @return a iterable that is flatMapped to a new result
*/
public static GENERIC_KEY_SPECIAL_BRACES<E, V extends Iterable<E>> ObjectIterable<E> flatMap(Iterable<? extends CLASS_TYPE> iterable, TO_OBJECT_FUNCTION KKS_GENERIC_TYPE<V> mapper) {
return new FlatMappedIterable<>(wrap(iterable), mapper);
}
/**
* A Helper function that flatMaps a Iterable into a new Type.
* @param iterable the iterable that should be flatMapped
* @param mapper the function that decides what the result turns into.
* @Type(T)
* @param <V> The return type supplier.
* @param <E> The return type.
* @return a iterable that is flatMapped to a new result
*/
public static GENERIC_KEY_SPECIAL_BRACES<E, V extends Iterable<E>> ObjectIterable<E> flatMap(ITERABLE KEY_GENERIC_TYPE iterable, TO_OBJECT_FUNCTION KKS_GENERIC_TYPE<V> mapper) {
return new FlatMappedIterable<>(iterable, mapper);
}
/**
* A Helper function that flatMaps a Java-Iterable into a new Type.
* @param iterable the iterable that should be flatMapped
* @param mapper the function that decides what the result turns into.
* @Type(T)
* @param <E> The return type.
* @return a iterable that is flatMapped to a new result
*/
public static GENERIC_KEY_SPECIAL_BRACES<E> ObjectIterable<E> arrayFlatMap(Iterable<? extends CLASS_TYPE> iterable, TO_OBJECT_FUNCTION KKS_GENERIC_TYPE<E[]> mapper) {
return new FlatMappedArrayIterable<>(wrap(iterable), mapper);
}
/**
* A Helper function that flatMaps a Iterable into a new Type.
* @param iterable the iterable that should be flatMapped
* @param mapper the function that decides what the result turns into.
* @Type(T)
* @param <E> The return type.
* @return a iterable that is flatMapped to a new result
*/
public static GENERIC_KEY_SPECIAL_BRACES<E> ObjectIterable<E> arrayFlatMap(ITERABLE KEY_GENERIC_TYPE iterable, TO_OBJECT_FUNCTION KKS_GENERIC_TYPE<E[]> mapper) {
return new FlatMappedArrayIterable<>(iterable, mapper);
}
/**
* A Helper function that filters out all desired elements from a Java-Iterable
* @param iterable that should be filtered.
* @param filter the filter that decides that should be let through
* @Type(T)
* @return a filtered iterable
*/
public static GENERIC_KEY_BRACES ITERABLE KEY_GENERIC_TYPE filter(Iterable<? extends CLASS_TYPE> iterable, PREDICATE KEY_GENERIC_TYPE filter) {
return new FilteredIterableBRACES(wrap(iterable), filter);
}
/**
* A Helper function that filters out all desired elements
* @param iterable that should be filtered.
* @param filter the filter that decides that should be let through
* @Type(T)
* @return a filtered iterable
*/
public static GENERIC_KEY_BRACES ITERABLE KEY_GENERIC_TYPE filter(ITERABLE KEY_GENERIC_TYPE iterable, PREDICATE KEY_GENERIC_TYPE filter) {
return new FilteredIterableBRACES(iterable, filter);
}
/**
* A Helper function that filters out all duplicated elements.
* @param iterable that should be distinct
* @Type(T)
* @return a distinct iterable
*/
public static GENERIC_KEY_BRACES ITERABLE KEY_GENERIC_TYPE distinct(ITERABLE KEY_GENERIC_TYPE iterable) {
return new DistinctIterableBRACES(iterable);
}
/**
* A Helper function that filters out all duplicated elements from a Java Iterable.
* @param iterable that should be distinct
* @Type(T)
* @return a distinct iterable
*/
public static GENERIC_KEY_BRACES ITERABLE KEY_GENERIC_TYPE distinct(Iterable<? extends CLASS_TYPE> iterable) {
return new DistinctIterableBRACES(wrap(iterable));
}
/**
* A Helper function that hard limits the Iterable to a specific size
* @param iterable that should be limited
* @param limit the amount of elements it should be limited to
* @Type(T)
* @return a limited iterable
*/
public static GENERIC_KEY_BRACES ITERABLE KEY_GENERIC_TYPE limit(ITERABLE KEY_GENERIC_TYPE iterable, long limit) {
return new LimitedIterableBRACES(iterable, limit);
}
/**
* A Helper function that hard limits the Iterable to a specific size from a Java Iterable
* @param iterable that should be limited
* @param limit the amount of elements it should be limited to
* @Type(T)
* @return a limited iterable
*/
public static GENERIC_KEY_BRACES ITERABLE KEY_GENERIC_TYPE limit(Iterable<? extends CLASS_TYPE> iterable, long limit) {
return new LimitedIterableBRACES(wrap(iterable), limit);
}
/**
* A Helper function that allows to preview the result of a Iterable.
* @param iterable that should be peeked at
* @param action callback that receives the value before the iterable returns it
* @Type(T)
* @return a peeked iterable
*/
public static GENERIC_KEY_BRACES ITERABLE KEY_GENERIC_TYPE peek(ITERABLE KEY_GENERIC_TYPE iterable, CONSUMER KEY_GENERIC_TYPE action) {
return new PeekIterableBRACES(iterable, action);
}
/**
* A Helper function that allows to preview the result of a Iterable from a Java Iterable
* @param iterable that should be peeked at
* @param action callback that receives the value before the iterable returns it
* @Type(T)
* @return a peeked iterable
*/
public static GENERIC_KEY_BRACES ITERABLE KEY_GENERIC_TYPE peek(Iterable<? extends CLASS_TYPE> iterable, CONSUMER KEY_GENERIC_TYPE action) {
return new PeekIterableBRACES(wrap(iterable), action);
}
/**
* A Wrapper function that wraps a Java-Iterable into a Type Specific Iterable
* @param iterable that should be wrapped
* @Type(T)
* @return a type specific iterable
*/
public static GENERIC_KEY_BRACES ITERABLE KEY_GENERIC_TYPE wrap(Iterable<? extends CLASS_TYPE> iterable) {
return new WrappedIterableBRACES(iterable);
}
private static class WrappedIterable KEY_GENERIC_TYPE implements ITERABLE KEY_GENERIC_TYPE
{
Iterable<? extends CLASS_TYPE> iterable;
public WrappedIterable(Iterable<? extends CLASS_TYPE> iterable) {
this.iterable = iterable;
}
public ITERATOR KEY_GENERIC_TYPE iterator() {
return ITERATORS.wrap(iterable.iterator());
}
#if !TYPE_OBJECT
@Override
public void forEach(CONSUMER action) {
Objects.requireNonNull(action);
iterable.forEach(action);
}
#else
public void forEach(Consumer<? super CLASS_TYPE> action) {
Objects.requireNonNull(action);
iterable.forEach(action);
}
#endif
}
private static class MappedIterable KSS_GENERIC_TYPE<E, T> implements ObjectIterable<T>
{
ITERABLE KEY_SPECIAL_GENERIC_TYPE<E> iterable;
TO_OBJECT_FUNCTION KSS_GENERIC_TYPE<E, T> mapper;
MappedIterable(ITERABLE KEY_SPECIAL_GENERIC_TYPE<E> iterable, TO_OBJECT_FUNCTION KSS_GENERIC_TYPE<E, T> mapper) {
this.iterable = iterable;
this.mapper = mapper;
}
public ObjectIterator<T> iterator() {
return ITERATORS.map(iterable.iterator(), mapper);
}
@Override
public void forEach(Consumer<? super T> action) {
Objects.requireNonNull(action);
iterable.forEach(E -> action.accept(mapper.GET_VALUE(E)));
}
}
private static class FlatMappedIterable KSS_GENERIC_TYPE<E, T,[SPACE]V extends Iterable<T>> implements ObjectIterable<T>
{
ITERABLE KEY_SPECIAL_GENERIC_TYPE<E> iterable;
TO_OBJECT_FUNCTION KSS_GENERIC_TYPE<E, V> mapper;
FlatMappedIterable(ITERABLE KEY_SPECIAL_GENERIC_TYPE<E> iterable, TO_OBJECT_FUNCTION KSS_GENERIC_TYPE<E, V> mapper) {
this.iterable = iterable;
this.mapper = mapper;
}
@Override
public ObjectIterator<T> iterator() {
return ITERATORS.flatMap(iterable.iterator(), mapper);
}
@Override
public void forEach(Consumer<? super T> action) {
Objects.requireNonNull(action);
iterable.forEach(E -> mapper.GET_VALUE(E).forEach(action));
}
}
private static class FlatMappedArrayIterable KSS_GENERIC_TYPE<E, T> implements ObjectIterable<T>
{
ITERABLE KEY_SPECIAL_GENERIC_TYPE<E> iterable;
TO_OBJECT_FUNCTION KSS_GENERIC_TYPE<E, T[]> mapper;
FlatMappedArrayIterable(ITERABLE KEY_SPECIAL_GENERIC_TYPE<E> iterable, TO_OBJECT_FUNCTION KSS_GENERIC_TYPE<E, T[]> mapper) {
this.iterable = iterable;
this.mapper = mapper;
}
@Override
public ObjectIterator<T> iterator() {
return ITERATORS.arrayFlatMap(iterable.iterator(), mapper);
}
@Override
public void forEach(Consumer<? super T> action) {
Objects.requireNonNull(action);
iterable.forEach(E -> {
T[] array = mapper.GET_VALUE(E);
for(int i = 0,m=array.length;i<m;action.accept(array[i++]));
});
}
}
private static class FilteredIterable KEY_GENERIC_TYPE implements ITERABLE KEY_GENERIC_TYPE
{
ITERABLE KEY_GENERIC_TYPE iterable;
PREDICATE KEY_GENERIC_TYPE filter;
public FilteredIterable(ITERABLE KEY_GENERIC_TYPE iterable, PREDICATE KEY_GENERIC_TYPE filter) {
this.iterable = iterable;
this.filter = filter;
}
@Override
public ITERATOR KEY_GENERIC_TYPE iterator() {
return ITERATORS.filter(iterable.iterator(), filter);
}
#if !TYPE_OBJECT
@Override
public void forEach(CONSUMER action) {
Objects.requireNonNull(action);
iterable.forEach(T -> { if(!filter.TEST_VALUE(T)) action.accept(T); } );
}
#else
public void forEach(Consumer<? super CLASS_TYPE> action) {
Objects.requireNonNull(action);
iterable.forEach(T -> { if(!filter.TEST_VALUE(T)) action.accept(T); } );
}
#endif
}
private static class LimitedIterable KEY_GENERIC_TYPE implements ITERABLE KEY_GENERIC_TYPE
{
ITERABLE KEY_GENERIC_TYPE iterable;
long limit;
public LimitedIterable(ITERABLE KEY_GENERIC_TYPE iterable, long limit) {
this.iterable = iterable;
this.limit = limit;
}
@Override
public ITERATOR KEY_GENERIC_TYPE iterator() {
return ITERATORS.limit(iterable.iterator(), limit);
}
#if !TYPE_OBJECT
@Override
public void forEach(CONSUMER action) {
Objects.requireNonNull(action);
AtomicLong counter = new AtomicLong();
iterable.forEach(T -> {
if(counter.get() >= limit) return;
counter.incrementAndGet();
action.accept(T);
});
}
#else
public void forEach(Consumer<? super CLASS_TYPE> action) {
Objects.requireNonNull(action);
AtomicLong counter = new AtomicLong();
iterable.forEach(T -> {
if(counter.get() >= limit) return;
counter.incrementAndGet();
action.accept(T);
});
}
#endif
}
private static class DistinctIterable KEY_GENERIC_TYPE implements ITERABLE KEY_GENERIC_TYPE
{
ITERABLE KEY_GENERIC_TYPE iterable;
public DistinctIterable(ITERABLE KEY_GENERIC_TYPE iterable) {
this.iterable = iterable;
}
@Override
public ITERATOR KEY_GENERIC_TYPE iterator() {
return ITERATORS.distinct(iterable.iterator());
}
#if !TYPE_OBJECT
@Override
public void forEach(CONSUMER action) {
Objects.requireNonNull(action);
#if TYPE_BOOLEAN
AtomicInteger result = new AtomicInteger();
iterable.forEach(T -> {
if(((result.get() & (T ? 2 : 1)) != 0)) return;
result.getAndAdd(T ? 2 : 1);
action.accept(T);
});
#else
SET KEY_GENERIC_TYPE filtered = new HASH_SETBRACES();
iterable.forEach(T -> { if(filtered.add(T)) action.accept(T); });
#endif
}
#else
public void forEach(Consumer<? super CLASS_TYPE> action) {
Objects.requireNonNull(action);
SET KEY_GENERIC_TYPE filtered = new HASH_SETBRACES();
iterable.forEach(T -> { if(filtered.add(T)) action.accept(T); });
}
#endif
}
private static class PeekIterable KEY_GENERIC_TYPE implements ITERABLE KEY_GENERIC_TYPE
{
ITERABLE KEY_GENERIC_TYPE iterable;
CONSUMER KEY_GENERIC_TYPE action;
public PeekIterable(ITERABLE KEY_GENERIC_TYPE iterable, CONSUMER KEY_GENERIC_TYPE action) {
this.iterable = iterable;
this.action = action;
}
@Override
public ITERATOR KEY_GENERIC_TYPE iterator() {
return ITERATORS.peek(iterable.iterator(), action);
}
#if !TYPE_OBJECT
@Override
public void forEach(CONSUMER action) {
Objects.requireNonNull(action);
iterable.forEach(this.action.andThen(action));
}
#else
public void forEach(Consumer<? super CLASS_TYPE> action) {
Objects.requireNonNull(action);
iterable.forEach(this.action.andThen(action));
}
#endif
}
}
@@ -1,9 +1,28 @@
package speiger.src.collections.PACKAGE.utils; package speiger.src.collections.PACKAGE.utils;
import java.util.Iterator; import java.util.Iterator;
import java.util.NoSuchElementException;
#if TYPE_OBJECT
import java.util.function.CONSUMER;
#endif
import speiger.src.collections.PACKAGE.collections.ITERATOR; import speiger.src.collections.PACKAGE.collections.ITERATOR;
#if !TYPE_OBJECT
import speiger.src.collections.objects.collections.ObjectIterator;
import speiger.src.collections.objects.utils.ObjectIterators;
import speiger.src.collections.PACKAGE.functions.CONSUMER;
#endif
import speiger.src.collections.PACKAGE.functions.function.TO_OBJECT_FUNCTION;
import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
import speiger.src.collections.PACKAGE.lists.ARRAY_LIST;
import speiger.src.collections.PACKAGE.lists.LIST;
import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR; import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR;
import speiger.src.collections.PACKAGE.collections.BI_ITERATOR; import speiger.src.collections.PACKAGE.collections.BI_ITERATOR;
import speiger.src.collections.PACKAGE.collections.COLLECTION;
#if !TYPE_BOOLEAN
import speiger.src.collections.PACKAGE.sets.HASH_SET;
import speiger.src.collections.PACKAGE.sets.SET;
#endif
/** /**
* A Helper class for Iterators * A Helper class for Iterators
@@ -20,7 +39,7 @@ public class ITERATORS
* @Type(T) * @Type(T)
* @return an empty iterator * @return an empty iterator
*/ */
public static GENERIC_KEY_BRACES EmptyIterator KEY_GENERIC_TYPE emptyIterator() { public static GENERIC_KEY_BRACES EmptyIterator KEY_GENERIC_TYPE empty() {
#if TYPE_OBJECT #if TYPE_OBJECT
return (EmptyIterator<KEY_TYPE>)EMPTY; return (EmptyIterator<KEY_TYPE>)EMPTY;
#else #else
@@ -50,9 +69,9 @@ public class ITERATORS
/** /**
* Returns a Immutable Iterator instance based on the instance given. * Returns a Immutable Iterator instance based on the instance given.
* @param iterator that should be made immutable/unmodifyable * @param iterator that should be made immutable/unmodifiable
* @Type(T) * @Type(T)
* @return a unmodifiable iterator wrapper. If the Iterator already a unmodifyable wrapper then it just returns itself. * @return a unmodifiable iterator wrapper. If the Iterator already a unmodifiable wrapper then it just returns itself.
*/ */
public static GENERIC_KEY_BRACES ITERATOR KEY_GENERIC_TYPE unmodifiable(ITERATOR KEY_GENERIC_TYPE iterator) { public static GENERIC_KEY_BRACES ITERATOR KEY_GENERIC_TYPE unmodifiable(ITERATOR KEY_GENERIC_TYPE iterator) {
return iterator instanceof UnmodifiableIterator ? iterator : new UnmodifiableIteratorBRACES(iterator); return iterator instanceof UnmodifiableIterator ? iterator : new UnmodifiableIteratorBRACES(iterator);
@@ -60,9 +79,9 @@ public class ITERATORS
/** /**
* Returns a Immutable Iterator instance based on the instance given. * Returns a Immutable Iterator instance based on the instance given.
* @param iterator that should be made immutable/unmodifyable * @param iterator that should be made immutable/unmodifiable
* @Type(T) * @Type(T)
* @return a unmodifiable iterator wrapper. If the Iterator already a unmodifyable wrapper then it just returns itself. * @return a unmodifiable iterator wrapper. If the Iterator already a unmodifiable wrapper then it just returns itself.
*/ */
public static GENERIC_KEY_BRACES BI_ITERATOR KEY_GENERIC_TYPE unmodifiable(BI_ITERATOR KEY_GENERIC_TYPE iterator) { public static GENERIC_KEY_BRACES BI_ITERATOR KEY_GENERIC_TYPE unmodifiable(BI_ITERATOR KEY_GENERIC_TYPE iterator) {
return iterator instanceof UnmodifiableBiIterator ? iterator : new UnmodifiableBiIteratorBRACES(iterator); return iterator instanceof UnmodifiableBiIterator ? iterator : new UnmodifiableBiIteratorBRACES(iterator);
@@ -70,25 +89,184 @@ public class ITERATORS
/** /**
* Returns a Immutable ListIterator instance based on the instance given. * Returns a Immutable ListIterator instance based on the instance given.
* @param iterator that should be made immutable/unmodifyable * @param iterator that should be made immutable/unmodifiable
* @Type(T) * @Type(T)
* @return a unmodifiable listiterator wrapper. If the ListIterator already a unmodifyable wrapper then it just returns itself. * @return a unmodifiable listiterator wrapper. If the ListIterator already a unmodifiable wrapper then it just returns itself.
*/ */
public static GENERIC_KEY_BRACES LIST_ITERATOR KEY_GENERIC_TYPE unmodifiable(LIST_ITERATOR KEY_GENERIC_TYPE iterator) { public static GENERIC_KEY_BRACES LIST_ITERATOR KEY_GENERIC_TYPE unmodifiable(LIST_ITERATOR KEY_GENERIC_TYPE iterator) {
return iterator instanceof UnmodifiableListIterator ? iterator : new UnmodifiableListIteratorBRACES(iterator); return iterator instanceof UnmodifiableListIterator ? iterator : new UnmodifiableListIteratorBRACES(iterator);
} }
#if !TYPE_OBJECT /**
* A Helper function that maps a Java-Iterator into a new Type.
* @param iterator that should be mapped
* @param mapper the function that decides what the result turns into.
* @Type(T)
* @param <E> The return type.
* @return a iterator that is mapped to a new result
*/
public static GENERIC_KEY_SPECIAL_BRACES<E> ObjectIterator<E> map(Iterator<? extends CLASS_TYPE> iterator, TO_OBJECT_FUNCTION KKS_GENERIC_TYPE<E> mapper) {
return new MappedIterator<>(wrap(iterator), mapper);
}
/**
* A Helper function that maps a Iterator into a new Type.
* @param iterator that should be mapped
* @param mapper the function that decides what the result turns into.
* @Type(T)
* @param <E> The return type.
* @return a iterator that is mapped to a new result
*/
public static GENERIC_KEY_SPECIAL_BRACES<E> ObjectIterator<E> map(ITERATOR KEY_GENERIC_TYPE iterator, TO_OBJECT_FUNCTION KKS_GENERIC_TYPE<E> mapper) {
return new MappedIterator<>(iterator, mapper);
}
/**
* A Helper function that flatMaps a Java-Iterator into a new Type.
* @param iterator that should be flatMapped
* @param mapper the function that decides what the result turns into.
* @Type(T)
* @param <V> The return type supplier.
* @param <E> The return type.
* @return a iterator that is flatMapped to a new result
*/
public static GENERIC_KEY_SPECIAL_BRACES<E, V extends Iterable<E>> ObjectIterator<E> flatMap(Iterator<? extends CLASS_TYPE> iterator, TO_OBJECT_FUNCTION KKS_GENERIC_TYPE<V> mapper) {
return new FlatMappedIterator<>(wrap(iterator), mapper);
}
/**
* A Helper function that flatMaps a Iterator into a new Type.
* @param iterator that should be flatMapped
* @param mapper the function that decides what the result turns into.
* @Type(T)
* @param <V> The return type supplier.
* @param <E> The return type.
* @return a iterator that is flatMapped to a new result
*/
public static GENERIC_KEY_SPECIAL_BRACES<E, V extends Iterable<E>> ObjectIterator<E> flatMap(ITERATOR KEY_GENERIC_TYPE iterator, TO_OBJECT_FUNCTION KKS_GENERIC_TYPE<V> mapper) {
return new FlatMappedIterator<>(iterator, mapper);
}
/**
* A Helper function that flatMaps a Java-Iterator into a new Type.
* @param iterator that should be flatMapped
* @param mapper the function that decides what the result turns into.
* @Type(T)
* @param <E> The return type.
* @return a iterator that is flatMapped to a new result
*/
public static GENERIC_KEY_SPECIAL_BRACES<E> ObjectIterator<E> arrayFlatMap(Iterator<? extends CLASS_TYPE> iterator, TO_OBJECT_FUNCTION KKS_GENERIC_TYPE<E[]> mapper) {
return new FlatMappedArrayIterator<>(wrap(iterator), mapper);
}
/**
* A Helper function that flatMaps a Iterator into a new Type.
* @param iterator that should be flatMapped
* @param mapper the function that decides what the result turns into.
* @Type(T)
* @param <E> The return type.
* @return a iterator that is flatMapped to a new result
*/
public static GENERIC_KEY_SPECIAL_BRACES<E> ObjectIterator<E> arrayFlatMap(ITERATOR KEY_GENERIC_TYPE iterator, TO_OBJECT_FUNCTION KKS_GENERIC_TYPE<E[]> mapper) {
return new FlatMappedArrayIterator<>(iterator, mapper);
}
/**
* A Helper function that filters out all desired elements from a Java-Iterator
* @param iterator that should be filtered.
* @param filter the filter that decides that should be let through
* @Type(T)
* @return a filtered iterator
*/
public static GENERIC_KEY_BRACES ITERATOR KEY_GENERIC_TYPE filter(Iterator<? extends CLASS_TYPE> iterator, PREDICATE KEY_GENERIC_TYPE filter) {
return new FilteredIteratorBRACES(wrap(iterator), filter);
}
/**
* A Helper function that filters out all desired elements
* @param iterator that should be filtered.
* @param filter the filter that decides that should be let through
* @Type(T)
* @return a filtered iterator
*/
public static GENERIC_KEY_BRACES ITERATOR KEY_GENERIC_TYPE filter(ITERATOR KEY_GENERIC_TYPE iterator, PREDICATE KEY_GENERIC_TYPE filter) {
return new FilteredIteratorBRACES(iterator, filter);
}
/**
* A Helper function that filters out all duplicated elements.
* @param iterator that should be distinct
* @Type(T)
* @return a distinct iterator
*/
public static GENERIC_KEY_BRACES ITERATOR KEY_GENERIC_TYPE distinct(ITERATOR KEY_GENERIC_TYPE iterator) {
return new DistinctIteratorBRACES(iterator);
}
/**
* A Helper function that filters out all duplicated elements from a Java Iterator.
* @param iterator that should be distinct
* @Type(T)
* @return a distinct iterator
*/
public static GENERIC_KEY_BRACES ITERATOR KEY_GENERIC_TYPE distinct(Iterator<? extends CLASS_TYPE> iterator) {
return new DistinctIteratorBRACES(wrap(iterator));
}
/**
* A Helper function that hard limits the Iterator to a specific size
* @param iterator that should be limited
* @param limit the amount of elements it should be limited to
* @Type(T)
* @return a limited iterator
*/
public static GENERIC_KEY_BRACES ITERATOR KEY_GENERIC_TYPE limit(ITERATOR KEY_GENERIC_TYPE iterator, long limit) {
return new LimitedIteratorBRACES(iterator, limit);
}
/**
* A Helper function that hard limits the Iterator to a specific size from a Java Iterator
* @param iterator that should be limited
* @param limit the amount of elements it should be limited to
* @Type(T)
* @return a limited iterator
*/
public static GENERIC_KEY_BRACES ITERATOR KEY_GENERIC_TYPE limit(Iterator<? extends CLASS_TYPE> iterator, long limit) {
return new LimitedIteratorBRACES(wrap(iterator), limit);
}
/**
* A Helper function that allows to preview the result of a Iterator.
* @param iterator that should be peeked at
* @param action callback that receives the value before the iterator returns it
* @Type(T)
* @return a peeked iterator
*/
public static GENERIC_KEY_BRACES ITERATOR KEY_GENERIC_TYPE peek(ITERATOR KEY_GENERIC_TYPE iterator, CONSUMER KEY_GENERIC_TYPE action) {
return new PeekIteratorBRACES(iterator, action);
}
/**
* A Helper function that allows to preview the result of a Iterator from a Java Iterator
* @param iterator that should be peeked at
* @param action callback that receives the value before the iterator returns it
* @Type(T)
* @return a peeked iterator
*/
public static GENERIC_KEY_BRACES ITERATOR KEY_GENERIC_TYPE peek(Iterator<? extends CLASS_TYPE> iterator, CONSUMER KEY_GENERIC_TYPE action) {
return new PeekIteratorBRACES(wrap(iterator), action);
}
/** /**
* Helper function to convert a Object Iterator into a Primitive Iterator * Helper function to convert a Object Iterator into a Primitive Iterator
* @param iterator that should be converted to a unboxing iterator * @param iterator that should be converted to a unboxing iterator
* @ArrayType(T)
* @return a primitive iterator * @return a primitive iterator
*/ */
public static ITERATOR wrap(Iterator<CLASS_TYPE> iterator) { public static GENERIC_KEY_BRACES ITERATOR KEY_GENERIC_TYPE wrap(Iterator<? extends CLASS_TYPE> iterator) {
return iterator instanceof ITERATOR ? (ITERATOR)iterator : new IteratorWrapper(iterator); return iterator instanceof ITERATOR ? (ITERATOR KEY_GENERIC_TYPE)iterator : new IteratorWrapperBRACES(iterator);
} }
#endif
/** /**
* Returns a Array Wrapping iterator * Returns a Array Wrapping iterator
* @param a the array that should be wrapped * @param a the array that should be wrapped
@@ -241,11 +419,84 @@ public class ITERATORS
return index; return index;
} }
private static class IteratorWrapper implements ITERATOR #endif
{ /**
Iterator<CLASS_TYPE> iter; * A Helper function to pours all elements of a Iterator into a List
* @param iter the elements that should be poured into list.
* @ArrayType(T)
* @return A list of all elements of the Iterator
*/
public static GENERIC_KEY_BRACES LIST KEY_GENERIC_TYPE pour(ITERATOR KEY_GENERIC_TYPE iter) {
return pour(iter, Integer.MAX_VALUE);
}
public IteratorWrapper(Iterator<CLASS_TYPE> iter) { /**
* A Helper function to pours all elements of a Iterator into a List
* @param iter the elements that should be poured into list.
* @param max the maximum amount of elements that should be collected
* @ArrayType(T)
* @return A list of all requested elements of the Iterator
*/
public static GENERIC_KEY_BRACES LIST KEY_GENERIC_TYPE pour(ITERATOR KEY_GENERIC_TYPE iter, int max) {
ARRAY_LIST KEY_GENERIC_TYPE list = new ARRAY_LISTBRACES();
pour(iter, list, max);
list.trim();
return list;
}
/**
* A Helper function to pours all elements of a Iterator into a Collection
* @param iter the elements that should be poured into list.
* @param c the collection where the elements should be poured into
* @ArrayType(T)
* @return the amount of elements that were added
*/
public static GENERIC_KEY_BRACES int pour(ITERATOR KEY_GENERIC_TYPE iter, COLLECTION KEY_GENERIC_TYPE c) {
return pour(iter, c, Integer.MAX_VALUE);
}
/**
* A Helper function to pours all elements of a Iterator into a Collection
* @param iter the elements that should be poured into list.
* @param c the collection where the elements should be poured into
* @param max the maximum amount of elements that should be collected
* @ArrayType(T)
* @return the amount of elements that were added
*/
public static GENERIC_KEY_BRACES int pour(ITERATOR KEY_GENERIC_TYPE iter, COLLECTION KEY_GENERIC_TYPE c, int max) {
if(max < 0) throw new IllegalStateException("Max is negative");
int done = 0;
for(;done<max && iter.hasNext();done++, c.add(iter.NEXT()));
return done;
}
/**
* Helper Iterator that concats other iterators together
* @param array the Iterators that should be concatenated
* @ArrayType(T)
* @return iterator of the inputted iterators
*/
public static GENERIC_KEY_BRACES ITERATOR KEY_GENERIC_TYPE concat(ITERATOR KEY_GENERIC_TYPE... array) {
return concat(array, 0, array.length);
}
/**
* Helper Iterator that concats other iterators together
* @param array the Iterators that should be concatenated
* @param offset where to start within the array
* @param length the length of the array
* @ArrayType(T)
* @return iterator of the inputted iterators
*/
public static GENERIC_KEY_BRACES ITERATOR KEY_GENERIC_TYPE concat(ITERATOR KEY_GENERIC_TYPE[] array, int offset, int length) {
return new ConcatIteratorBRACES(array, offset, length);
}
private static class IteratorWrapper KEY_GENERIC_TYPE implements ITERATOR KEY_GENERIC_TYPE
{
Iterator<? extends CLASS_TYPE> iter;
public IteratorWrapper(Iterator<? extends CLASS_TYPE> iter) {
this.iter = iter; this.iter = iter;
} }
@@ -259,14 +510,54 @@ public class ITERATORS
return OBJ_TO_KEY(iter.next()); return OBJ_TO_KEY(iter.next());
} }
#if !TYPE_OBJECT
@Override @Override
@Deprecated @Deprecated
public CLASS_TYPE next() { public CLASS_TYPE next() {
return iter.next(); return iter.next();
} }
#endif
}
private static class ConcatIterator KEY_GENERIC_TYPE implements ITERATOR KEY_GENERIC_TYPE
{
ITERATOR KEY_GENERIC_TYPE[] iters;
int offset;
int lastOffset = -1;
int length;
public ConcatIterator(ITERATOR KEY_GENERIC_TYPE[] iters, int offset, int length) {
this.iters = iters;
this.offset = offset;
this.length = length;
find();
}
private void find() {
for(;length != 0 && !iters[offset].hasNext();length--, offset++);
}
@Override
public boolean hasNext() {
return length > 0;
}
@Override
public KEY_TYPE NEXT() {
if(!hasNext()) throw new NoSuchElementException();
KEY_TYPE result = iters[lastOffset = offset].NEXT();
find();
return result;
}
@Override
public void remove() {
if(lastOffset == -1) throw new IllegalStateException();
iters[lastOffset].remove();
lastOffset = -1;
}
} }
#endif
private static class ReverseBiIterator KEY_GENERIC_TYPE implements BI_ITERATOR KEY_GENERIC_TYPE { private static class ReverseBiIterator KEY_GENERIC_TYPE implements BI_ITERATOR KEY_GENERIC_TYPE {
BI_ITERATOR KEY_GENERIC_TYPE it; BI_ITERATOR KEY_GENERIC_TYPE it;
@@ -481,4 +772,237 @@ public class ITERATORS
return amount - left; return amount - left;
} }
} }
private static class MappedIterator KSS_GENERIC_TYPE<E, T> implements ObjectIterator<T>
{
ITERATOR KEY_SPECIAL_GENERIC_TYPE<E> iterator;
TO_OBJECT_FUNCTION KSS_GENERIC_TYPE<E, T> mapper;
MappedIterator(ITERATOR KEY_SPECIAL_GENERIC_TYPE<E> iterator, TO_OBJECT_FUNCTION KSS_GENERIC_TYPE<E, T> mapper) {
this.iterator = iterator;
this.mapper = mapper;
}
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public T next() {
return mapper.GET_VALUE(iterator.NEXT());
}
@Override
public int skip(int amount) {
return iterator.skip(amount);
}
}
private static class FlatMappedIterator KSS_GENERIC_TYPE<E, T,[SPACE]V extends Iterable<T>> implements ObjectIterator<T>
{
ITERATOR KEY_SPECIAL_GENERIC_TYPE<E> iterator;
Iterator<T> last = null;
TO_OBJECT_FUNCTION KSS_GENERIC_TYPE<E, V> mapper;
boolean foundNext = false;
FlatMappedIterator(ITERATOR KEY_SPECIAL_GENERIC_TYPE<E> iterator, TO_OBJECT_FUNCTION KSS_GENERIC_TYPE<E, V> mapper) {
this.iterator = iterator;
this.mapper = mapper;
}
void compute() {
if(foundNext) return;
foundNext = true;
while(iterator.hasNext()) {
if(last != null && last.hasNext()) return;
last = mapper.GET_VALUE(iterator.NEXT()).iterator();
}
}
@Override
public boolean hasNext() {
compute();
return last != null && last.hasNext();
}
@Override
public T next() {
if(!hasNext()) throw new IllegalStateException("End of Iterator");
T result = last.next();
foundNext = false;
return result;
}
}
private static class FlatMappedArrayIterator KSS_GENERIC_TYPE<E, T> implements ObjectIterator<T>
{
ITERATOR KEY_SPECIAL_GENERIC_TYPE<E> iterator;
Iterator<T> last = null;
TO_OBJECT_FUNCTION KSS_GENERIC_TYPE<E, T[]> mapper;
boolean foundNext = false;
FlatMappedArrayIterator(ITERATOR KEY_SPECIAL_GENERIC_TYPE<E> iterator, TO_OBJECT_FUNCTION KSS_GENERIC_TYPE<E, T[]> mapper) {
this.iterator = iterator;
this.mapper = mapper;
}
void compute() {
if(foundNext) return;
foundNext = true;
while(iterator.hasNext()) {
if(last != null && last.hasNext()) return;
last = ObjectIterators.wrap(mapper.GET_VALUE(iterator.NEXT()));
}
}
@Override
public boolean hasNext() {
compute();
return last != null && last.hasNext();
}
@Override
public T next() {
if(!hasNext()) throw new IllegalStateException("End of Iterator");
T result = last.next();
foundNext = false;
return result;
}
}
private static class DistinctIterator KEY_GENERIC_TYPE implements ITERATOR KEY_GENERIC_TYPE
{
ITERATOR KEY_GENERIC_TYPE iterator;
#if TYPE_BOOLEAN
int filtered;
#else
SET KEY_GENERIC_TYPE filtered = new HASH_SETBRACES();
#endif
KEY_TYPE lastFound;
boolean foundNext = false;
public DistinctIterator(ITERATOR KEY_GENERIC_TYPE iterator) {
this.iterator = iterator;
}
void compute() {
if(foundNext) return;
#if TYPE_BOOLEAN
if(filtered == 3) return;
#endif
while(iterator.hasNext()) {
lastFound = iterator.NEXT();
#if TYPE_BOOLEAN
if((filtered & (lastFound ? 1 : 2)) == 0) {
filtered |= (lastFound ? 1 : 2);
foundNext = true;
break;
}
#else
if(filtered.add(lastFound)) {
foundNext = true;
break;
}
#endif
}
}
@Override
public boolean hasNext() {
compute();
return foundNext;
}
@Override
public KEY_TYPE NEXT() {
if(!hasNext()) throw new IllegalStateException("End of Iterator");
foundNext = false;
return lastFound;
}
}
private static class FilteredIterator KEY_GENERIC_TYPE implements ITERATOR KEY_GENERIC_TYPE
{
ITERATOR KEY_GENERIC_TYPE iterator;
PREDICATE KEY_GENERIC_TYPE filter;
KEY_TYPE lastFound;
boolean foundNext = false;
public FilteredIterator(ITERATOR KEY_GENERIC_TYPE iterator, PREDICATE KEY_GENERIC_TYPE filter) {
this.iterator = iterator;
this.filter = filter;
}
void compute() {
if(foundNext) return;
while(iterator.hasNext()) {
lastFound = iterator.NEXT();
if(filter.TEST_VALUE(lastFound)) {
foundNext = true;
break;
}
}
}
@Override
public boolean hasNext() {
compute();
return foundNext;
}
@Override
public KEY_TYPE NEXT() {
if(!hasNext()) throw new IllegalStateException("End of Iterator");
foundNext = false;
return lastFound;
}
}
private static class LimitedIterator KEY_GENERIC_TYPE implements ITERATOR KEY_GENERIC_TYPE
{
ITERATOR KEY_GENERIC_TYPE iterator;
long limit;
public LimitedIterator(ITERATOR KEY_GENERIC_TYPE iterator, long limit) {
this.iterator = iterator;
this.limit = limit;
}
@Override
public boolean hasNext() {
return limit > 0 && iterator.hasNext();
}
@Override
public KEY_TYPE NEXT() {
if(!hasNext()) throw new IllegalStateException("End of Iterator");
limit--;
return iterator.NEXT();
}
}
private static class PeekIterator KEY_GENERIC_TYPE implements ITERATOR KEY_GENERIC_TYPE
{
ITERATOR KEY_GENERIC_TYPE iterator;
CONSUMER KEY_GENERIC_TYPE action;
public PeekIterator(ITERATOR KEY_GENERIC_TYPE iterator, CONSUMER KEY_GENERIC_TYPE action) {
this.iterator = iterator;
this.action = action;
}
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public KEY_TYPE NEXT() {
if(!hasNext()) throw new IllegalStateException("End of Iterator");
KEY_TYPE result = iterator.NEXT();
action.accept(result);
return result;
}
}
} }
@@ -2,8 +2,12 @@ package speiger.src.collections.PACKAGE.utils;
import java.util.Collection; import java.util.Collection;
import java.util.Objects; import java.util.Objects;
import java.util.Random;
import java.util.RandomAccess; import java.util.RandomAccess;
import java.util.function.Consumer; import java.util.function.Consumer;
#if PRIMITIVES
import java.nio.JAVA_BUFFER;
#endif
import speiger.src.collections.PACKAGE.collections.COLLECTION; import speiger.src.collections.PACKAGE.collections.COLLECTION;
#if !TYPE_OBJECT #if !TYPE_OBJECT
@@ -12,6 +16,8 @@ import speiger.src.collections.PACKAGE.functions.CONSUMER;
import speiger.src.collections.PACKAGE.lists.ABSTRACT_LIST; import speiger.src.collections.PACKAGE.lists.ABSTRACT_LIST;
import speiger.src.collections.PACKAGE.lists.LIST; import speiger.src.collections.PACKAGE.lists.LIST;
import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR; import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR;
import speiger.src.collections.PACKAGE.utils.ARRAYS;
import speiger.src.collections.utils.SanityChecks;
/** /**
* A Helper class for Lists * A Helper class for Lists
@@ -28,7 +34,7 @@ public class LISTS
* @Type(T) * @Type(T)
* @return an empty list * @return an empty list
*/ */
public static GENERIC_KEY_BRACES EmptyList KEY_GENERIC_TYPE emptyList() { public static GENERIC_KEY_BRACES EmptyList KEY_GENERIC_TYPE empty() {
#if TYPE_OBJECT #if TYPE_OBJECT
return (EmptyList<KEY_TYPE>)EMPTY; return (EmptyList<KEY_TYPE>)EMPTY;
#else #else
@@ -38,11 +44,11 @@ public class LISTS
/** /**
* Returns a Immutable List instance based on the instance given. * Returns a Immutable List instance based on the instance given.
* @param l that should be made immutable/unmodifyable * @param l that should be made immutable/unmodifiable
* @Type(T) * @Type(T)
* @return a unmodifiable list wrapper. If the list is implementing RandomAccess that is also transferred. If the List already a unmodifyable wrapper then it just returns itself. * @return a unmodifiable list wrapper. If the list is implementing RandomAccess that is also transferred. If the List already a unmodifiable wrapper then it just returns itself.
*/ */
public static GENERIC_KEY_BRACES LIST KEY_GENERIC_TYPE unmodifiableList(LIST KEY_GENERIC_TYPE l) { public static GENERIC_KEY_BRACES LIST KEY_GENERIC_TYPE unmodifiable(LIST KEY_GENERIC_TYPE l) {
return l instanceof UnmodifiableList ? l : l instanceof RandomAccess ? new UnmodifiableRandomListBRACES(l) : new UnmodifiableListBRACES(l); return l instanceof UnmodifiableList ? l : l instanceof RandomAccess ? new UnmodifiableRandomListBRACES(l) : new UnmodifiableListBRACES(l);
} }
@@ -52,7 +58,7 @@ public class LISTS
* @Type(T) * @Type(T)
* @return a synchronized list wrapper. If the list is implementing RandomAccess or IARRAY that is also transferred. If the List already a synchronized wrapper then it just returns itself. * @return a synchronized list wrapper. If the list is implementing RandomAccess or IARRAY that is also transferred. If the List already a synchronized wrapper then it just returns itself.
*/ */
public static GENERIC_KEY_BRACES LIST KEY_GENERIC_TYPE synchronizedList(LIST KEY_GENERIC_TYPE l) { public static GENERIC_KEY_BRACES LIST KEY_GENERIC_TYPE synchronize(LIST KEY_GENERIC_TYPE l) {
return l instanceof SynchronizedList ? l : (l instanceof IARRAY ? new SynchronizedArrayListBRACES(l) : (l instanceof RandomAccess ? new SynchronizedRandomAccessListBRACES(l) : new SynchronizedListBRACES(l))); return l instanceof SynchronizedList ? l : (l instanceof IARRAY ? new SynchronizedArrayListBRACES(l) : (l instanceof RandomAccess ? new SynchronizedRandomAccessListBRACES(l) : new SynchronizedListBRACES(l)));
} }
@@ -63,7 +69,7 @@ public class LISTS
* @Type(T) * @Type(T)
* @return a synchronized list wrapper. If the list is implementing RandomAccess or IARRAY that is also transferred. If the List already a synchronized wrapper then it just returns itself. * @return a synchronized list wrapper. If the list is implementing RandomAccess or IARRAY that is also transferred. If the List already a synchronized wrapper then it just returns itself.
*/ */
public static GENERIC_KEY_BRACES LIST KEY_GENERIC_TYPE synchronizedList(LIST KEY_GENERIC_TYPE l, Object mutex) { public static GENERIC_KEY_BRACES LIST KEY_GENERIC_TYPE synchronize(LIST KEY_GENERIC_TYPE l, Object mutex) {
return l instanceof SynchronizedList ? l : (l instanceof IARRAY ? new SynchronizedArrayListBRACES(l, mutex) : (l instanceof RandomAccess ? new SynchronizedRandomAccessListBRACES(l, mutex) : new SynchronizedListBRACES(l, mutex))); return l instanceof SynchronizedList ? l : (l instanceof IARRAY ? new SynchronizedArrayListBRACES(l, mutex) : (l instanceof RandomAccess ? new SynchronizedRandomAccessListBRACES(l, mutex) : new SynchronizedListBRACES(l, mutex)));
} }
@@ -73,10 +79,99 @@ public class LISTS
* @Type(T) * @Type(T)
* @return a singleton list that is unmodifiable * @return a singleton list that is unmodifiable
*/ */
public static GENERIC_KEY_BRACES LIST KEY_GENERIC_TYPE singletonList(KEY_TYPE element) { public static GENERIC_KEY_BRACES LIST KEY_GENERIC_TYPE singleton(KEY_TYPE element) {
return new SingletonListBRACES(element); return new SingletonListBRACES(element);
} }
/**
* Reverses the list
* @param list that should be reversed.
* @Type(T)
* @return the input list
*/
public static GENERIC_KEY_BRACES LIST KEY_GENERIC_TYPE reverse(LIST KEY_GENERIC_TYPE list) {
int size = list.size();
if(list instanceof IARRAY) {
IARRAY KEY_GENERIC_TYPE array = (IARRAY KEY_GENERIC_TYPE)list;
#if TYPE_OBJECT
if(array.isCastable()) {
if(list instanceof SynchronizedArrayList) array.elements(T -> ARRAYS.reverse(T, size));
else ARRAYS.reverse(array.elements(), size);
return list;
}
#else
if(list instanceof SynchronizedArrayList) array.elements(T -> ARRAYS.reverse(T, size));
else ARRAYS.reverse(array.elements(), size);
return list;
#endif
}
if(list instanceof RandomAccess) {
for (int i = 0, mid = size >> 1, j = size - 1; i < mid; i++, j--) {
KEY_TYPE t = list.GET_KEY(i);
list.set(i, list.GET_KEY(j));
list.set(j, t);
}
return list;
}
LIST_ITERATOR KEY_GENERIC_TYPE fwd = list.listIterator();
LIST_ITERATOR KEY_GENERIC_TYPE rev = list.listIterator(size);
for(int i = 0, mid = size >> 1; i < mid; i++) {
KEY_TYPE tmp = fwd.NEXT();
fwd.set(rev.PREVIOUS());
rev.set(tmp);
}
return list;
}
/**
* Shuffles the list
* @param list that should be Shuffled.
* @Type(T)
* @return the input list
*/
public static GENERIC_KEY_BRACES LIST KEY_GENERIC_TYPE shuffle(LIST KEY_GENERIC_TYPE list) {
return shuffle(list, SanityChecks.getRandom());
}
/**
* Shuffles the list
* @param list that should be Shuffled.
* @param random the random that should be used
* @Type(T)
* @return the input list
*/
public static GENERIC_KEY_BRACES LIST KEY_GENERIC_TYPE shuffle(LIST KEY_GENERIC_TYPE list, Random random) {
int size = list.size();
if(list instanceof IARRAY) {
IARRAY KEY_GENERIC_TYPE array = (IARRAY KEY_GENERIC_TYPE)list;
#if TYPE_OBJECT
if(array.isCastable()) {
if(list instanceof SynchronizedArrayList) array.elements(T -> ARRAYS.shuffle(T, size, random));
else ARRAYS.shuffle(array.elements(), size, random);
}
else {
for(int i = list.size(); i-- != 0;) {
int p = random.nextInt(i + 1);
KEY_TYPE t = list.GET_KEY(i);
list.set(i, list.GET_KEY(p));
list.set(p, t);
}
}
#else
if(list instanceof SynchronizedArrayList) array.elements(T -> ARRAYS.shuffle(T, size, random));
else ARRAYS.shuffle(array.elements(), size, random);
#endif
return list;
}
for(int i = list.size(); i-- != 0;) {
int p = random.nextInt(i + 1);
KEY_TYPE t = list.GET_KEY(i);
list.set(i, list.GET_KEY(p));
list.set(p, t);
}
return list;
}
private static class SingletonList KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE private static class SingletonList KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
{ {
KEY_TYPE element; KEY_TYPE element;
@@ -105,6 +200,8 @@ public class LISTS
@Override @Override
public KEY_TYPE REMOVE(int index) { throw new UnsupportedOperationException(); } public KEY_TYPE REMOVE(int index) { throw new UnsupportedOperationException(); }
@Override @Override
public KEY_TYPE swapRemove(int index) { throw new UnsupportedOperationException(); }
@Override
public void addElements(int from, KEY_TYPE[] a, int offset, int length) { throw new UnsupportedOperationException(); } public void addElements(int from, KEY_TYPE[] a, int offset, int length) { throw new UnsupportedOperationException(); }
@Override @Override
public KEY_TYPE[] getElements(int from, KEY_TYPE[] a, int offset, int length) { public KEY_TYPE[] getElements(int from, KEY_TYPE[] a, int offset, int length) {
@@ -112,6 +209,10 @@ public class LISTS
a[offset] = element; a[offset] = element;
return a; return a;
} }
#if PRIMITIVES
@Override
public void fillBuffer(JAVA_BUFFER buffer) { buffer.put(element); }
#endif
@Override @Override
public void removeElements(int from, int to) { throw new UnsupportedOperationException(); } public void removeElements(int from, int to) { throw new UnsupportedOperationException(); }
@@ -124,6 +225,9 @@ public class LISTS
#endif #endif
@Override @Override
public int size() { return 1; } public int size() { return 1; }
@Override
public SingletonList KEY_GENERIC_TYPE copy() { return new SingletonListBRACES(element); }
} }
private static class SynchronizedArrayList KEY_GENERIC_TYPE extends SynchronizedList KEY_GENERIC_TYPE implements IARRAY KEY_GENERIC_TYPE private static class SynchronizedArrayList KEY_GENERIC_TYPE extends SynchronizedList KEY_GENERIC_TYPE implements IARRAY KEY_GENERIC_TYPE
@@ -146,6 +250,9 @@ public class LISTS
@Override @Override
public boolean trim(int size) { synchronized(mutex) { return l.trim(size); } } public boolean trim(int size) { synchronized(mutex) { return l.trim(size); } }
@Override
public void clearAndTrim(int size) { synchronized(mutex) { l.clearAndTrim(size); } }
@Override @Override
public KEY_TYPE[] elements() { synchronized(mutex) { return l.elements(); } } public KEY_TYPE[] elements() { synchronized(mutex) { return l.elements(); } }
@@ -226,6 +333,12 @@ public class LISTS
@Override @Override
public KEY_TYPE REMOVE(int index) { synchronized(mutex) { return l.REMOVE(index); } } public KEY_TYPE REMOVE(int index) { synchronized(mutex) { return l.REMOVE(index); } }
@Override
public KEY_TYPE swapRemove(int index) { synchronized(mutex) { return l.swapRemove(index); } }
@Override
public boolean REMOVE_SWAP(KEY_TYPE e) { synchronized(mutex) { return l.REMOVE_SWAP(e); } }
@Override @Override
@Primitive @Primitive
public int indexOf(Object e) { synchronized(mutex) { return l.indexOf(e); } } public int indexOf(Object e) { synchronized(mutex) { return l.indexOf(e); } }
@@ -259,6 +372,9 @@ public class LISTS
@Override @Override
public <K> K[] extractElements(int from, int to, Class<K> clz) { synchronized(mutex) { return l.extractElements(from, to, clz); } } public <K> K[] extractElements(int from, int to, Class<K> clz) { synchronized(mutex) { return l.extractElements(from, to, clz); } }
#endif
#if PRIMITIVES
public void fillBuffer(JAVA_BUFFER buffer) { synchronized(mutex) { l.fillBuffer(buffer); } }
#endif #endif
@Override @Override
public LIST_ITERATOR KEY_GENERIC_TYPE listIterator() { public LIST_ITERATOR KEY_GENERIC_TYPE listIterator() {
@@ -272,11 +388,14 @@ public class LISTS
@Override @Override
public LIST KEY_GENERIC_TYPE subList(int from, int to) { public LIST KEY_GENERIC_TYPE subList(int from, int to) {
return synchronizedList(l.subList(from, to)); return LISTS.synchronize(l.subList(from, to));
} }
@Override @Override
public void size(int size) { synchronized(mutex) { l.size(size); } } public void size(int size) { synchronized(mutex) { l.size(size); } }
@Override
public LIST KEY_GENERIC_TYPE copy() { synchronized(mutex) { return l.copy(); } }
} }
private static class UnmodifiableRandomList KEY_GENERIC_TYPE extends UnmodifiableList KEY_GENERIC_TYPE implements RandomAccess private static class UnmodifiableRandomList KEY_GENERIC_TYPE extends UnmodifiableList KEY_GENERIC_TYPE implements RandomAccess
@@ -333,6 +452,12 @@ public class LISTS
@Override @Override
public KEY_TYPE REMOVE(int index) { throw new UnsupportedOperationException(); } public KEY_TYPE REMOVE(int index) { throw new UnsupportedOperationException(); }
@Override
public KEY_TYPE swapRemove(int index) { throw new UnsupportedOperationException(); }
@Override
public boolean REMOVE_SWAP(KEY_TYPE e) { throw new UnsupportedOperationException(); }
@Override @Override
@Primitive @Primitive
public int indexOf(Object e) { return l.indexOf(e); } public int indexOf(Object e) { return l.indexOf(e); }
@@ -368,6 +493,10 @@ public class LISTS
@Override @Override
public <K> K[] extractElements(int from, int to, Class<K> clz) { throw new UnsupportedOperationException(); } public <K> K[] extractElements(int from, int to, Class<K> clz) { throw new UnsupportedOperationException(); }
#endif
#if PRIMITIVES
public void fillBuffer(JAVA_BUFFER buffer) { l.fillBuffer(buffer); }
#endif #endif
@Override @Override
public LIST_ITERATOR KEY_GENERIC_TYPE listIterator() { public LIST_ITERATOR KEY_GENERIC_TYPE listIterator() {
@@ -381,11 +510,14 @@ public class LISTS
@Override @Override
public LIST KEY_GENERIC_TYPE subList(int from, int to) { public LIST KEY_GENERIC_TYPE subList(int from, int to) {
return unmodifiableList(l.subList(from, to)); return LISTS.unmodifiable(l.subList(from, to));
} }
@Override @Override
public void size(int size) { throw new UnsupportedOperationException(); } public void size(int size) { throw new UnsupportedOperationException(); }
@Override
public LIST KEY_GENERIC_TYPE copy() { return l.copy(); }
} }
private static class EmptyList KEY_GENERIC_TYPE extends COLLECTIONS.EmptyCollection KEY_GENERIC_TYPE implements LIST KEY_GENERIC_TYPE private static class EmptyList KEY_GENERIC_TYPE extends COLLECTIONS.EmptyCollection KEY_GENERIC_TYPE implements LIST KEY_GENERIC_TYPE
@@ -419,6 +551,12 @@ public class LISTS
@Override @Override
public KEY_TYPE REMOVE(int index) { throw new UnsupportedOperationException(); } public KEY_TYPE REMOVE(int index) { throw new UnsupportedOperationException(); }
@Override
public KEY_TYPE swapRemove(int index) { throw new UnsupportedOperationException(); }
@Override
public boolean REMOVE_SWAP(KEY_TYPE e) { throw new UnsupportedOperationException(); }
@Override @Override
public int indexOf(Object e) { return -1; } public int indexOf(Object e) { return -1; }
@@ -453,14 +591,14 @@ public class LISTS
#endif #endif
@Override @Override
public LIST_ITERATOR KEY_GENERIC_TYPE listIterator() { public LIST_ITERATOR KEY_GENERIC_TYPE listIterator() {
return ITERATORS.emptyIterator(); return ITERATORS.empty();
} }
@Override @Override
public LIST_ITERATOR KEY_GENERIC_TYPE listIterator(int index) { public LIST_ITERATOR KEY_GENERIC_TYPE listIterator(int index) {
if(index != 0) if(index != 0)
throw new IndexOutOfBoundsException(); throw new IndexOutOfBoundsException();
return ITERATORS.emptyIterator(); return ITERATORS.empty();
} }
@Override @Override
@@ -468,5 +606,8 @@ public class LISTS
@Override @Override
public void size(int size) { throw new UnsupportedOperationException(); } public void size(int size) { throw new UnsupportedOperationException(); }
@Override
public EmptyList KEY_GENERIC_TYPE copy() { return this; }
} }
} }
@@ -0,0 +1,169 @@
package speiger.src.collections.PACKAGE.utils;
#if TYPE_OBJECT
import java.util.Collection;
import java.util.Comparator;
import java.util.function.Consumer;
#endif
import speiger.src.collections.PACKAGE.collections.ITERATOR;
import speiger.src.collections.PACKAGE.collections.COLLECTION;
#if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.functions.COMPARATOR;
#endif
import speiger.src.collections.PACKAGE.queues.PRIORITY_DEQUEUE;
import speiger.src.collections.PACKAGE.queues.PRIORITY_QUEUE;
#if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.functions.CONSUMER;
#endif
import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER;
/**
* A Helper class for PriorityQueues
*/
public class PRIORITY_QUEUES
{
/**
* Returns a synchronized PriorityQueue instance based on the instance given.
* @param queue that should be synchronized
* @Type(T)
* @return a synchronized PriorityQueue wrapper.
*/
public static GENERIC_KEY_BRACES PRIORITY_QUEUE KEY_GENERIC_TYPE synchronize(PRIORITY_QUEUE KEY_GENERIC_TYPE queue) {
return queue instanceof SynchronizedPriorityQueue ? (SynchronizedPriorityQueue KEY_GENERIC_TYPE)queue : new SynchronizedPriorityQueueBRACES(queue);
}
/**
* Returns a synchronized PriorityQueue instance based on the instance given.
* @param queue that should be synchronized
* @param mutex is the controller of the synchronization block.
* @Type(T)
* @return a synchronized PriorityQueue wrapper.
*/
public static GENERIC_KEY_BRACES PRIORITY_QUEUE KEY_GENERIC_TYPE synchronize(PRIORITY_QUEUE KEY_GENERIC_TYPE queue, Object mutex) {
return queue instanceof SynchronizedPriorityQueue ? (SynchronizedPriorityQueue KEY_GENERIC_TYPE)queue : new SynchronizedPriorityQueueBRACES(queue, mutex);
}
/**
* Returns a synchronized PriorityDequeue instance based on the instance given.
* @param dequeue that should be synchronized
* @Type(T)
* @return a synchronized PriorityDequeue wrapper.
*/
public static GENERIC_KEY_BRACES PRIORITY_DEQUEUE KEY_GENERIC_TYPE synchronize(PRIORITY_DEQUEUE KEY_GENERIC_TYPE dequeue) {
return dequeue instanceof SynchronizedPriorityDequeue ? (SynchronizedPriorityDequeue KEY_GENERIC_TYPE)dequeue : new SynchronizedPriorityDequeueBRACES(dequeue);
}
/**
* Returns a synchronized PriorityDequeue instance based on the instance given.
* @param dequeue that should be synchronized
* @param mutex is the controller of the synchronization block.
* @Type(T)
* @return a synchronized PriorityDequeue wrapper.
*/
public static GENERIC_KEY_BRACES PRIORITY_DEQUEUE KEY_GENERIC_TYPE synchronize(PRIORITY_DEQUEUE KEY_GENERIC_TYPE dequeue, Object mutex) {
return dequeue instanceof SynchronizedPriorityDequeue ? (SynchronizedPriorityDequeue KEY_GENERIC_TYPE)dequeue : new SynchronizedPriorityDequeueBRACES(dequeue, mutex);
}
/**
* Wrapper class for synchronization
* @Type(T)
*/
public static class SynchronizedPriorityQueue KEY_GENERIC_TYPE implements PRIORITY_QUEUE KEY_GENERIC_TYPE
{
PRIORITY_QUEUE KEY_GENERIC_TYPE queue;
protected Object mutex;
protected SynchronizedPriorityQueue(PRIORITY_QUEUE KEY_GENERIC_TYPE queue) {
this.queue = queue;
mutex = this;
}
protected SynchronizedPriorityQueue(PRIORITY_QUEUE KEY_GENERIC_TYPE queue, Object mutex) {
this.queue = queue;
this.mutex = mutex;
}
@Override
public ITERATOR KEY_GENERIC_TYPE iterator() { return queue.iterator(); }
@Override
public int size() { synchronized(mutex) { return queue.size(); } }
@Override
public void clear() { synchronized(mutex) { queue.clear(); } }
@Override
public void enqueue(KEY_TYPE e) { synchronized(mutex) { queue.enqueue(e); } }
@Override
public void enqueueAll(KEY_TYPE[] e, int offset, int length) { synchronized(mutex) { queue.enqueueAll(e, offset, length); } }
@Override
public void enqueueAll(COLLECTION KEY_GENERIC_TYPE c) { synchronized(mutex) { queue.enqueueAll(c); } }
#if TYPE_OBJECT
@Override
public void enqueueAll(Collection<? extends CLASS_TYPE> c) { synchronized(mutex) { queue.enqueueAll(c); } }
#endif
@Override
public KEY_TYPE dequeue() { synchronized(mutex) { return queue.dequeue(); } }
@Override
public KEY_TYPE peek(int index) { synchronized(mutex) { return queue.peek(index); } }
@Override
public boolean removeFirst(KEY_TYPE e) { synchronized(mutex) { return queue.removeFirst(e); } }
@Override
public boolean removeLast(KEY_TYPE e) { synchronized(mutex) { return queue.removeLast(e); } }
@Override
public void onChanged() { synchronized(mutex) { queue.onChanged(); } }
@Override
public COMPARATOR KEY_SUPER_GENERIC_TYPE comparator() { synchronized(mutex) { return queue.comparator(); } }
@Override
public GENERIC_SPECIAL_KEY_BRACES<E> KEY_SPECIAL_TYPE[] TO_ARRAY(KEY_SPECIAL_TYPE[] input) { synchronized(mutex) { return queue.TO_ARRAY(input); } }
@Override
public PRIORITY_QUEUE KEY_GENERIC_TYPE copy() { synchronized(mutex) { return queue.copy(); } }
@Override
public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) { synchronized(mutex) { queue.forEach(action); } }
@Override
public <E> void forEach(E input, BI_FROM_OBJECT_CONSUMER KSK_GENERIC_TYPE<E> action) { synchronized(mutex) { queue.forEach(input, action); } }
@Override
public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) { synchronized(mutex) { return queue.matchesAny(filter); } }
@Override
public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) { synchronized(mutex) { return queue.matchesNone(filter); } }
@Override
public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) { synchronized(mutex) { return queue.matchesAll(filter); } }
@Override
public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) { synchronized(mutex) { return queue.findFirst(filter); } }
@Override
public int count(PREDICATE KEY_GENERIC_TYPE filter) { synchronized(mutex) { return queue.count(filter); } }
}
/**
* Wrapper class for synchronization
* @Type(T)
*/
public static class SynchronizedPriorityDequeue KEY_GENERIC_TYPE extends SynchronizedPriorityQueue KEY_GENERIC_TYPE implements PRIORITY_DEQUEUE KEY_GENERIC_TYPE
{
PRIORITY_DEQUEUE KEY_GENERIC_TYPE dequeue;
protected SynchronizedPriorityDequeue(PRIORITY_DEQUEUE KEY_GENERIC_TYPE queue) {
super(queue);
dequeue = queue;
}
protected SynchronizedPriorityDequeue(PRIORITY_DEQUEUE KEY_GENERIC_TYPE queue, Object mutex) {
super(queue, mutex);
dequeue = queue;
}
@Override
public void enqueueFirst(KEY_TYPE e) { synchronized(mutex) { dequeue.enqueueFirst(e); } }
@Override
public void enqueueAllFirst(KEY_TYPE[] e, int offset, int length) { synchronized(mutex) { dequeue.enqueueAllFirst(e, offset, length); } }
@Override
public void enqueueAllFirst(COLLECTION KEY_GENERIC_TYPE c) { synchronized(mutex) { dequeue.enqueueAllFirst(c); } }
#if TYPE_OBJECT
@Override
public void enqueueAllFirst(Collection<? extends CLASS_TYPE> c) { synchronized(mutex) { dequeue.enqueueAllFirst(c); } }
#endif
@Override
public KEY_TYPE dequeueLast() { synchronized(mutex) { return dequeue.dequeueLast(); } }
@Override
public PRIORITY_DEQUEUE KEY_GENERIC_TYPE copy() { synchronized(mutex) { return dequeue.copy(); } }
}
}
@@ -56,7 +56,7 @@ public class SETS
* @return a set that is synchronized * @return a set that is synchronized
* @note if the set is already synchronized then it will just self return it * @note if the set is already synchronized then it will just self return it
*/ */
public static GENERIC_KEY_BRACES SET KEY_GENERIC_TYPE synchronizedSet(SET KEY_GENERIC_TYPE s) { public static GENERIC_KEY_BRACES SET KEY_GENERIC_TYPE synchronize(SET KEY_GENERIC_TYPE s) {
return s instanceof SynchronizedSet ? s : (s instanceof ITrimmable ? new SynchronizedTrimSetBRACES(s) : new SynchronizedSetBRACES(s)); return s instanceof SynchronizedSet ? s : (s instanceof ITrimmable ? new SynchronizedTrimSetBRACES(s) : new SynchronizedSetBRACES(s));
} }
@@ -68,7 +68,7 @@ public class SETS
* @return a set that is synchronized * @return a set that is synchronized
* @note if the set is already synchronized then it will just self return it * @note if the set is already synchronized then it will just self return it
*/ */
public static GENERIC_KEY_BRACES SET KEY_GENERIC_TYPE synchronizedSet(SET KEY_GENERIC_TYPE s, Object mutex) { public static GENERIC_KEY_BRACES SET KEY_GENERIC_TYPE synchronize(SET KEY_GENERIC_TYPE s, Object mutex) {
return s instanceof SynchronizedSet ? s : (s instanceof ITrimmable ? new SynchronizedTrimSetBRACES(s, mutex) : new SynchronizedSetBRACES(s, mutex)); return s instanceof SynchronizedSet ? s : (s instanceof ITrimmable ? new SynchronizedTrimSetBRACES(s, mutex) : new SynchronizedSetBRACES(s, mutex));
} }
@@ -79,7 +79,7 @@ public class SETS
* @return a SortedSet that is synchronized * @return a SortedSet that is synchronized
* @note if the set is already synchronized then it will just self return it * @note if the set is already synchronized then it will just self return it
*/ */
public static GENERIC_KEY_BRACES SORTED_SET KEY_GENERIC_TYPE synchronizedSet(SORTED_SET KEY_GENERIC_TYPE s) { public static GENERIC_KEY_BRACES SORTED_SET KEY_GENERIC_TYPE synchronize(SORTED_SET KEY_GENERIC_TYPE s) {
return s instanceof SynchronizedSortedSet ? s : (s instanceof ITrimmable ? new SynchronizedSortedTrimSetBRACES(s) : new SynchronizedSortedSetBRACES(s)); return s instanceof SynchronizedSortedSet ? s : (s instanceof ITrimmable ? new SynchronizedSortedTrimSetBRACES(s) : new SynchronizedSortedSetBRACES(s));
} }
@@ -91,7 +91,7 @@ public class SETS
* @return a SortedSet that is synchronized * @return a SortedSet that is synchronized
* @note if the set is already synchronized then it will just self return it * @note if the set is already synchronized then it will just self return it
*/ */
public static GENERIC_KEY_BRACES SORTED_SET KEY_GENERIC_TYPE synchronizedSet(SORTED_SET KEY_GENERIC_TYPE s, Object mutex) { public static GENERIC_KEY_BRACES SORTED_SET KEY_GENERIC_TYPE synchronize(SORTED_SET KEY_GENERIC_TYPE s, Object mutex) {
return s instanceof SynchronizedSortedSet ? s : (s instanceof ITrimmable ? new SynchronizedSortedTrimSetBRACES(s, mutex) : new SynchronizedSortedSetBRACES(s, mutex)); return s instanceof SynchronizedSortedSet ? s : (s instanceof ITrimmable ? new SynchronizedSortedTrimSetBRACES(s, mutex) : new SynchronizedSortedSetBRACES(s, mutex));
} }
@@ -102,7 +102,7 @@ public class SETS
* @return a NavigableSet that is synchronized * @return a NavigableSet that is synchronized
* @note if the set is already synchronized then it will just self return it * @note if the set is already synchronized then it will just self return it
*/ */
public static GENERIC_KEY_BRACES NAVIGABLE_SET KEY_GENERIC_TYPE synchronizedSet(NAVIGABLE_SET KEY_GENERIC_TYPE s) { public static GENERIC_KEY_BRACES NAVIGABLE_SET KEY_GENERIC_TYPE synchronize(NAVIGABLE_SET KEY_GENERIC_TYPE s) {
return s instanceof SynchronizedNavigableSet ? s : (s instanceof ITrimmable ? new SynchronizedNavigableTrimSetBRACES(s) : new SynchronizedNavigableSetBRACES(s)); return s instanceof SynchronizedNavigableSet ? s : (s instanceof ITrimmable ? new SynchronizedNavigableTrimSetBRACES(s) : new SynchronizedNavigableSetBRACES(s));
} }
@@ -114,15 +114,15 @@ public class SETS
* @return a NavigableSet that is synchronized * @return a NavigableSet that is synchronized
* @note if the set is already synchronized then it will just self return it * @note if the set is already synchronized then it will just self return it
*/ */
public static GENERIC_KEY_BRACES NAVIGABLE_SET KEY_GENERIC_TYPE synchronizedSet(NAVIGABLE_SET KEY_GENERIC_TYPE s, Object mutex) { public static GENERIC_KEY_BRACES NAVIGABLE_SET KEY_GENERIC_TYPE synchronize(NAVIGABLE_SET KEY_GENERIC_TYPE s, Object mutex) {
return s instanceof SynchronizedNavigableSet ? s : (s instanceof ITrimmable ? new SynchronizedNavigableTrimSetBRACES(s, mutex) : new SynchronizedNavigableSetBRACES(s, mutex)); return s instanceof SynchronizedNavigableSet ? s : (s instanceof ITrimmable ? new SynchronizedNavigableTrimSetBRACES(s, mutex) : new SynchronizedNavigableSetBRACES(s, mutex));
} }
/** /**
* Creates Unmodifyable Set wrapper * Creates Unmodifyable Set wrapper
* @param s set that should be made unmodifyable * @param s set that should be made unmodifiable
* @Type(T) * @Type(T)
* @return a UnmodifyableSet, if the set is already unmodifyable then it returns itself * @return a UnmodifyableSet, if the set is already unmodifiable then it returns itself
*/ */
public static GENERIC_KEY_BRACES SET KEY_GENERIC_TYPE unmodifiable(SET KEY_GENERIC_TYPE s) { public static GENERIC_KEY_BRACES SET KEY_GENERIC_TYPE unmodifiable(SET KEY_GENERIC_TYPE s) {
return s instanceof UnmodifiableSet ? s : new UnmodifiableSetBRACES(s); return s instanceof UnmodifiableSet ? s : new UnmodifiableSetBRACES(s);
@@ -130,9 +130,9 @@ public class SETS
/** /**
* Creates Unmodifyable SortedSet wrapper * Creates Unmodifyable SortedSet wrapper
* @param s sortedSet that should be made unmodifyable * @param s sortedSet that should be made unmodifiable
* @Type(T) * @Type(T)
* @return a UnmodifyableSortedSet, if the set is already unmodifyable then it returns itself * @return a UnmodifyableSortedSet, if the set is already unmodifiable then it returns itself
*/ */
public static GENERIC_KEY_BRACES SORTED_SET KEY_GENERIC_TYPE unmodifiable(SORTED_SET KEY_GENERIC_TYPE s) { public static GENERIC_KEY_BRACES SORTED_SET KEY_GENERIC_TYPE unmodifiable(SORTED_SET KEY_GENERIC_TYPE s) {
return s instanceof UnmodifiableSortedSet ? s : new UnmodifiableSortedSetBRACES(s); return s instanceof UnmodifiableSortedSet ? s : new UnmodifiableSortedSetBRACES(s);
@@ -140,9 +140,9 @@ public class SETS
/** /**
* Creates Unmodifyable NavigableSet wrapper * Creates Unmodifyable NavigableSet wrapper
* @param s navigableSet that should be made unmodifyable * @param s navigableSet that should be made unmodifiable
* @Type(T) * @Type(T)
* @return a UnmodifyableNavigableSet, if the set is already unmodifyable then it returns itself * @return a UnmodifyableNavigableSet, if the set is already unmodifiable then it returns itself
*/ */
public static GENERIC_KEY_BRACES NAVIGABLE_SET KEY_GENERIC_TYPE unmodifiable(NAVIGABLE_SET KEY_GENERIC_TYPE s) { public static GENERIC_KEY_BRACES NAVIGABLE_SET KEY_GENERIC_TYPE unmodifiable(NAVIGABLE_SET KEY_GENERIC_TYPE s) {
return s instanceof UnmodifiableNavigableSet ? s : new UnmodifiableNavigableSetBRACES(s); return s instanceof UnmodifiableNavigableSet ? s : new UnmodifiableNavigableSetBRACES(s);
@@ -155,7 +155,7 @@ public class SETS
* @Type(T) * @Type(T)
* @return a singletonset of the given element * @return a singletonset of the given element
*/ */
public static GENERIC_KEY_BRACES SET KEY_GENERIC_TYPE singletonSet(KEY_TYPE element) { public static GENERIC_KEY_BRACES SET KEY_GENERIC_TYPE singleton(KEY_TYPE element) {
return new SingletonSetBRACES(element); return new SingletonSetBRACES(element);
} }
@@ -190,6 +190,9 @@ public class SETS
} }
@Override @Override
public int size() { return 1; } public int size() { return 1; }
@Override
public SingletonSet KEY_GENERIC_TYPE copy() { return new SingletonSetBRACES(element); }
} }
private static class EmptySet KEY_GENERIC_TYPE extends EmptyCollection KEY_GENERIC_TYPE implements SET KEY_GENERIC_TYPE private static class EmptySet KEY_GENERIC_TYPE extends EmptyCollection KEY_GENERIC_TYPE implements SET KEY_GENERIC_TYPE
@@ -198,6 +201,8 @@ public class SETS
@Override @Override
public boolean remove(KEY_TYPE o) { throw new UnsupportedOperationException(); } public boolean remove(KEY_TYPE o) { throw new UnsupportedOperationException(); }
#endif #endif
@Override
public EmptySet KEY_GENERIC_TYPE copy() { return this; }
} }
#if !TYPE_BOOLEAN #if !TYPE_BOOLEAN
@@ -246,28 +251,31 @@ public class SETS
#endif #endif
@Override @Override
public NAVIGABLE_SET KEY_GENERIC_TYPE subSet(KEY_TYPE fromElement, boolean fromInclusive, KEY_TYPE toElement, boolean toInclusive) { return unmodifiable(n.subSet(fromElement, fromInclusive, toElement, toInclusive)); } public NAVIGABLE_SET KEY_GENERIC_TYPE copy() { throw new UnsupportedOperationException(); }
@Override @Override
public NAVIGABLE_SET KEY_GENERIC_TYPE headSet(KEY_TYPE toElement, boolean inclusive) { return unmodifiable(n.headSet(toElement, inclusive)); } public NAVIGABLE_SET KEY_GENERIC_TYPE subSet(KEY_TYPE fromElement, boolean fromInclusive, KEY_TYPE toElement, boolean toInclusive) { return SETS.unmodifiable(n.subSet(fromElement, fromInclusive, toElement, toInclusive)); }
@Override @Override
public NAVIGABLE_SET KEY_GENERIC_TYPE tailSet(KEY_TYPE fromElement, boolean inclusive) { return unmodifiable(n.tailSet(fromElement, inclusive)); } public NAVIGABLE_SET KEY_GENERIC_TYPE headSet(KEY_TYPE toElement, boolean inclusive) { return SETS.unmodifiable(n.headSet(toElement, inclusive)); }
@Override
public NAVIGABLE_SET KEY_GENERIC_TYPE tailSet(KEY_TYPE fromElement, boolean inclusive) { return SETS.unmodifiable(n.tailSet(fromElement, inclusive)); }
@Override @Override
public BI_ITERATOR KEY_GENERIC_TYPE descendingIterator() { return ITERATORS.unmodifiable(n.descendingIterator()); } public BI_ITERATOR KEY_GENERIC_TYPE descendingIterator() { return ITERATORS.unmodifiable(n.descendingIterator()); }
@Override @Override
public NAVIGABLE_SET KEY_GENERIC_TYPE descendingSet() { return unmodifiable(n.descendingSet()); } public NAVIGABLE_SET KEY_GENERIC_TYPE descendingSet() { return SETS.unmodifiable(n.descendingSet()); }
@Override @Override
public NAVIGABLE_SET KEY_GENERIC_TYPE subSet(KEY_TYPE fromElement, KEY_TYPE toElement) { return unmodifiable(n.subSet(fromElement, toElement)); } public NAVIGABLE_SET KEY_GENERIC_TYPE subSet(KEY_TYPE fromElement, KEY_TYPE toElement) { return SETS.unmodifiable(n.subSet(fromElement, toElement)); }
@Override @Override
public NAVIGABLE_SET KEY_GENERIC_TYPE headSet(KEY_TYPE toElement) { return unmodifiable(n.headSet(toElement)); } public NAVIGABLE_SET KEY_GENERIC_TYPE headSet(KEY_TYPE toElement) { return SETS.unmodifiable(n.headSet(toElement)); }
@Override @Override
public NAVIGABLE_SET KEY_GENERIC_TYPE tailSet(KEY_TYPE fromElement) { return unmodifiable(n.tailSet(fromElement)); } public NAVIGABLE_SET KEY_GENERIC_TYPE tailSet(KEY_TYPE fromElement) { return SETS.unmodifiable(n.tailSet(fromElement)); }
} }
private static class UnmodifiableSortedSet KEY_GENERIC_TYPE extends UnmodifiableSet KEY_GENERIC_TYPE implements SORTED_SET KEY_GENERIC_TYPE private static class UnmodifiableSortedSet KEY_GENERIC_TYPE extends UnmodifiableSet KEY_GENERIC_TYPE implements SORTED_SET KEY_GENERIC_TYPE
@@ -301,13 +309,16 @@ public class SETS
public BI_ITERATOR KEY_GENERIC_TYPE iterator(KEY_TYPE fromElement) { return ITERATORS.unmodifiable(s.iterator(fromElement)); } public BI_ITERATOR KEY_GENERIC_TYPE iterator(KEY_TYPE fromElement) { return ITERATORS.unmodifiable(s.iterator(fromElement)); }
@Override @Override
public SORTED_SET KEY_GENERIC_TYPE subSet(KEY_TYPE fromElement, KEY_TYPE toElement) { return unmodifiable(s.subSet(fromElement, toElement)); } public SORTED_SET KEY_GENERIC_TYPE copy() { return s.copy(); }
@Override @Override
public SORTED_SET KEY_GENERIC_TYPE headSet(KEY_TYPE toElement) { return unmodifiable(s.headSet(toElement)); } public SORTED_SET KEY_GENERIC_TYPE subSet(KEY_TYPE fromElement, KEY_TYPE toElement) { return SETS.unmodifiable(s.subSet(fromElement, toElement)); }
@Override @Override
public SORTED_SET KEY_GENERIC_TYPE tailSet(KEY_TYPE fromElement) { return unmodifiable(s.tailSet(fromElement)); } public SORTED_SET KEY_GENERIC_TYPE headSet(KEY_TYPE toElement) { return SETS.unmodifiable(s.headSet(toElement)); }
@Override
public SORTED_SET KEY_GENERIC_TYPE tailSet(KEY_TYPE fromElement) { return SETS.unmodifiable(s.tailSet(fromElement)); }
@Override @Override
public KEY_TYPE FIRST_KEY() { return s.FIRST_KEY(); } public KEY_TYPE FIRST_KEY() { return s.FIRST_KEY(); }
@@ -336,6 +347,9 @@ public class SETS
s = c; s = c;
} }
@Override
public SET KEY_GENERIC_TYPE copy() { return s.copy(); }
#if !TYPE_OBJECT #if !TYPE_OBJECT
@Override @Override
public boolean remove(KEY_TYPE o) { throw new UnsupportedOperationException(); } public boolean remove(KEY_TYPE o) { throw new UnsupportedOperationException(); }
@@ -358,6 +372,9 @@ public class SETS
@Override @Override
public boolean trim(int size) { synchronized(mutex) { return trim.trim(size); } } public boolean trim(int size) { synchronized(mutex) { return trim.trim(size); } }
@Override
public void clearAndTrim(int size) { synchronized(mutex) { trim.clearAndTrim(size); } }
} }
private static class SynchronizedNavigableSet KEY_GENERIC_TYPE extends SynchronizedSortedSet KEY_GENERIC_TYPE implements NAVIGABLE_SET KEY_GENERIC_TYPE private static class SynchronizedNavigableSet KEY_GENERIC_TYPE extends SynchronizedSortedSet KEY_GENERIC_TYPE implements NAVIGABLE_SET KEY_GENERIC_TYPE
@@ -410,28 +427,31 @@ public class SETS
#endif #endif
@Override @Override
public NAVIGABLE_SET KEY_GENERIC_TYPE subSet(KEY_TYPE fromElement, boolean fromInclusive, KEY_TYPE toElement, boolean toInclusive) { synchronized(mutex) { return synchronizedSet(n.subSet(fromElement, fromInclusive, toElement, toInclusive), mutex); } } public NAVIGABLE_SET KEY_GENERIC_TYPE copy() { synchronized(mutex) { return n.copy(); } }
@Override @Override
public NAVIGABLE_SET KEY_GENERIC_TYPE headSet(KEY_TYPE toElement, boolean inclusive) { synchronized(mutex) { return synchronizedSet(n.headSet(toElement, inclusive), mutex); } } public NAVIGABLE_SET KEY_GENERIC_TYPE subSet(KEY_TYPE fromElement, boolean fromInclusive, KEY_TYPE toElement, boolean toInclusive) { synchronized(mutex) { return SETS.synchronize(n.subSet(fromElement, fromInclusive, toElement, toInclusive), mutex); } }
@Override @Override
public NAVIGABLE_SET KEY_GENERIC_TYPE tailSet(KEY_TYPE fromElement, boolean inclusive) { synchronized(mutex) { return synchronizedSet(n.tailSet(fromElement, inclusive), mutex); } } public NAVIGABLE_SET KEY_GENERIC_TYPE headSet(KEY_TYPE toElement, boolean inclusive) { synchronized(mutex) { return SETS.synchronize(n.headSet(toElement, inclusive), mutex); } }
@Override
public NAVIGABLE_SET KEY_GENERIC_TYPE tailSet(KEY_TYPE fromElement, boolean inclusive) { synchronized(mutex) { return SETS.synchronize(n.tailSet(fromElement, inclusive), mutex); } }
@Override @Override
public BI_ITERATOR KEY_GENERIC_TYPE descendingIterator() { synchronized(mutex) { return n.descendingIterator(); } } public BI_ITERATOR KEY_GENERIC_TYPE descendingIterator() { synchronized(mutex) { return n.descendingIterator(); } }
@Override @Override
public NAVIGABLE_SET KEY_GENERIC_TYPE descendingSet() { synchronized(mutex) { return synchronizedSet(n.descendingSet(), mutex); } } public NAVIGABLE_SET KEY_GENERIC_TYPE descendingSet() { synchronized(mutex) { return SETS.synchronize(n.descendingSet(), mutex); } }
@Override @Override
public NAVIGABLE_SET KEY_GENERIC_TYPE subSet(KEY_TYPE fromElement, KEY_TYPE toElement) { synchronized(mutex) { return synchronizedSet(n.subSet(fromElement, toElement), mutex); } } public NAVIGABLE_SET KEY_GENERIC_TYPE subSet(KEY_TYPE fromElement, KEY_TYPE toElement) { synchronized(mutex) { return SETS.synchronize(n.subSet(fromElement, toElement), mutex); } }
@Override @Override
public NAVIGABLE_SET KEY_GENERIC_TYPE headSet(KEY_TYPE toElement) { synchronized(mutex) { return synchronizedSet(n.headSet(toElement), mutex); } } public NAVIGABLE_SET KEY_GENERIC_TYPE headSet(KEY_TYPE toElement) { synchronized(mutex) { return SETS.synchronize(n.headSet(toElement), mutex); } }
@Override @Override
public NAVIGABLE_SET KEY_GENERIC_TYPE tailSet(KEY_TYPE fromElement) { synchronized(mutex) { return synchronizedSet(n.tailSet(fromElement), mutex); } } public NAVIGABLE_SET KEY_GENERIC_TYPE tailSet(KEY_TYPE fromElement) { synchronized(mutex) { return SETS.synchronize(n.tailSet(fromElement), mutex); } }
} }
private static class SynchronizedSortedTrimSet KEY_GENERIC_TYPE extends SynchronizedSortedSet KEY_GENERIC_TYPE implements ITrimmable private static class SynchronizedSortedTrimSet KEY_GENERIC_TYPE extends SynchronizedSortedSet KEY_GENERIC_TYPE implements ITrimmable
@@ -450,6 +470,9 @@ public class SETS
@Override @Override
public boolean trim(int size) { synchronized(mutex) { return trim.trim(size); } } public boolean trim(int size) { synchronized(mutex) { return trim.trim(size); } }
@Override
public void clearAndTrim(int size) { synchronized(mutex) { trim.clearAndTrim(size); } }
} }
private static class SynchronizedSortedSet KEY_GENERIC_TYPE extends SynchronizedSet KEY_GENERIC_TYPE implements SORTED_SET KEY_GENERIC_TYPE private static class SynchronizedSortedSet KEY_GENERIC_TYPE extends SynchronizedSet KEY_GENERIC_TYPE implements SORTED_SET KEY_GENERIC_TYPE
@@ -488,13 +511,16 @@ public class SETS
public BI_ITERATOR KEY_GENERIC_TYPE iterator(KEY_TYPE fromElement) { synchronized(mutex) { return s.iterator(fromElement); } } public BI_ITERATOR KEY_GENERIC_TYPE iterator(KEY_TYPE fromElement) { synchronized(mutex) { return s.iterator(fromElement); } }
@Override @Override
public SORTED_SET KEY_GENERIC_TYPE subSet(KEY_TYPE fromElement, KEY_TYPE toElement) { synchronized(mutex) { return synchronizedSet(s.subSet(fromElement, toElement), mutex); } } public SORTED_SET KEY_GENERIC_TYPE copy() { synchronized(mutex) { return s.copy(); } }
@Override @Override
public SORTED_SET KEY_GENERIC_TYPE headSet(KEY_TYPE toElement) { synchronized(mutex) { return synchronizedSet(s.headSet(toElement), mutex); } } public SORTED_SET KEY_GENERIC_TYPE subSet(KEY_TYPE fromElement, KEY_TYPE toElement) { synchronized(mutex) { return SETS.synchronize(s.subSet(fromElement, toElement), mutex); } }
@Override @Override
public SORTED_SET KEY_GENERIC_TYPE tailSet(KEY_TYPE fromElement) { synchronized(mutex) { return synchronizedSet(s.tailSet(fromElement), mutex); } } public SORTED_SET KEY_GENERIC_TYPE headSet(KEY_TYPE toElement) { synchronized(mutex) { return SETS.synchronize(s.headSet(toElement), mutex); } }
@Override
public SORTED_SET KEY_GENERIC_TYPE tailSet(KEY_TYPE fromElement) { synchronized(mutex) { return SETS.synchronize(s.tailSet(fromElement), mutex); } }
@Override @Override
public KEY_TYPE FIRST_KEY() { synchronized(mutex) { return s.FIRST_KEY(); } } public KEY_TYPE FIRST_KEY() { synchronized(mutex) { return s.FIRST_KEY(); } }
@@ -525,28 +551,28 @@ public class SETS
@Override @Override
public boolean trim(int size) { synchronized(mutex) { return trim.trim(size); } } public boolean trim(int size) { synchronized(mutex) { return trim.trim(size); } }
@Override
public void clearAndTrim(int size) { synchronized(mutex) { trim.clearAndTrim(size); } }
} }
private static class SynchronizedSet KEY_GENERIC_TYPE extends SynchronizedCollection KEY_GENERIC_TYPE implements SET KEY_GENERIC_TYPE private static class SynchronizedSet KEY_GENERIC_TYPE extends SynchronizedCollection KEY_GENERIC_TYPE implements SET KEY_GENERIC_TYPE
{ {
#if !TYPE_OBJECT
SET KEY_GENERIC_TYPE s; SET KEY_GENERIC_TYPE s;
#endif
SynchronizedSet(SET KEY_GENERIC_TYPE c) { SynchronizedSet(SET KEY_GENERIC_TYPE c) {
super(c); super(c);
#if !TYPE_OBJECT
s = c; s = c;
#endif
} }
SynchronizedSet(SET KEY_GENERIC_TYPE c, Object mutex) { SynchronizedSet(SET KEY_GENERIC_TYPE c, Object mutex) {
super(c, mutex); super(c, mutex);
#if !TYPE_OBJECT
s = c; s = c;
#endif
} }
@Override
public SET KEY_GENERIC_TYPE copy() { synchronized(mutex) { return s.copy(); } }
#if !TYPE_OBJECT #if !TYPE_OBJECT
@Override @Override
public boolean remove(KEY_TYPE o) { synchronized(mutex) { return s.remove(o); } } public boolean remove(KEY_TYPE o) { synchronized(mutex) { return s.remove(o); } }
@@ -335,146 +335,146 @@ public class SPLIT_ITERATORS
} }
#if PRIMITIVES #if PRIMITIVES
static class IteratorSpliterator KEY_GENERIC_TYPE implements JAVA_SPLIT_ITERATOR KEY_GENERIC_TYPE { static class IteratorSpliterator KEY_GENERIC_TYPE implements JAVA_SPLIT_ITERATOR KEY_GENERIC_TYPE {
static final int BATCH_UNIT = 1 << 10; static final int BATCH_UNIT = 1 << 10;
static final int MAX_BATCH = 1 << 25; static final int MAX_BATCH = 1 << 25;
private final COLLECTION KEY_GENERIC_TYPE collection; private final COLLECTION KEY_GENERIC_TYPE collection;
private ITERATOR KEY_GENERIC_TYPE it; private ITERATOR KEY_GENERIC_TYPE it;
private final int characteristics; private final int characteristics;
private long est; private long est;
private int batch; private int batch;
IteratorSpliterator(COLLECTION KEY_GENERIC_TYPE collection, int characteristics) { IteratorSpliterator(COLLECTION KEY_GENERIC_TYPE collection, int characteristics) {
this.collection = collection; this.collection = collection;
it = null; it = null;
this.characteristics = (characteristics & Spliterator.CONCURRENT) == 0 this.characteristics = (characteristics & Spliterator.CONCURRENT) == 0
? characteristics | Spliterator.SIZED | Spliterator.SUBSIZED ? characteristics | Spliterator.SIZED | Spliterator.SUBSIZED
: characteristics; : characteristics;
} }
IteratorSpliterator(ITERATOR KEY_GENERIC_TYPE iterator, long size, int characteristics) { IteratorSpliterator(ITERATOR KEY_GENERIC_TYPE iterator, long size, int characteristics) {
collection = null; collection = null;
it = iterator; it = iterator;
est = size; est = size;
this.characteristics = (characteristics & Spliterator.CONCURRENT) == 0 this.characteristics = (characteristics & Spliterator.CONCURRENT) == 0
? characteristics | Spliterator.SIZED | Spliterator.SUBSIZED ? characteristics | Spliterator.SIZED | Spliterator.SUBSIZED
: characteristics; : characteristics;
} }
IteratorSpliterator(ITERATOR KEY_GENERIC_TYPE iterator, int characteristics) { IteratorSpliterator(ITERATOR KEY_GENERIC_TYPE iterator, int characteristics) {
collection = null; collection = null;
it = iterator; it = iterator;
est = Long.MAX_VALUE; est = Long.MAX_VALUE;
this.characteristics = characteristics & ~(Spliterator.SIZED | Spliterator.SUBSIZED); this.characteristics = characteristics & ~(Spliterator.SIZED | Spliterator.SUBSIZED);
} }
private ITERATOR KEY_GENERIC_TYPE iterator() private ITERATOR KEY_GENERIC_TYPE iterator()
{ {
if (it == null) { if (it == null) {
it = collection.iterator(); it = collection.iterator();
est = collection.size(); est = collection.size();
} }
return it; return it;
} }
@Override @Override
public JAVA_SPLIT_ITERATOR KEY_GENERIC_TYPE trySplit() { public JAVA_SPLIT_ITERATOR KEY_GENERIC_TYPE trySplit() {
ITERATOR KEY_GENERIC_TYPE i = iterator(); ITERATOR KEY_GENERIC_TYPE i = iterator();
if (est > 1 && i.hasNext()) { if (est > 1 && i.hasNext()) {
int n = Math.min(batch + BATCH_UNIT, Math.min((int)est, MAX_BATCH)); int n = Math.min(batch + BATCH_UNIT, Math.min((int)est, MAX_BATCH));
KEY_TYPE[] a = NEW_KEY_ARRAY(n); KEY_TYPE[] a = NEW_KEY_ARRAY(n);
int j = 0; int j = 0;
do { a[j] = i.NEXT(); } while (++j < n && i.hasNext()); do { a[j] = i.NEXT(); } while (++j < n && i.hasNext());
batch = j; batch = j;
if (est != Long.MAX_VALUE) if (est != Long.MAX_VALUE)
est -= j; est -= j;
return new ArraySplitIteratorBRACES(a, 0, j, characteristics); return new ArraySplitIteratorBRACES(a, 0, j, characteristics);
} }
return null; return null;
} }
@Override @Override
public void forEachRemaining(JAVA_CONSUMER action) { public void forEachRemaining(JAVA_CONSUMER action) {
if (action == null) throw new NullPointerException(); if (action == null) throw new NullPointerException();
iterator().forEachRemaining(T -> action.accept(T)); iterator().forEachRemaining(T -> action.accept(T));
} }
@Override @Override
public boolean tryAdvance(JAVA_CONSUMER action) { public boolean tryAdvance(JAVA_CONSUMER action) {
if (action == null) throw new NullPointerException(); if (action == null) throw new NullPointerException();
ITERATOR KEY_GENERIC_TYPE iter = iterator(); ITERATOR KEY_GENERIC_TYPE iter = iterator();
if (iter.hasNext()) { if (iter.hasNext()) {
action.accept(iter.NEXT()); action.accept(iter.NEXT());
return true; return true;
} }
return false; return false;
} }
@Override @Override
public long estimateSize() { public long estimateSize() {
iterator(); iterator();
return est; return est;
} }
@Override @Override
public int characteristics() { return characteristics; } public int characteristics() { return characteristics; }
@Override @Override
public Comparator<? super JAVA_CLASS> getComparator() { public Comparator<? super JAVA_CLASS> getComparator() {
if (hasCharacteristics(4)) //Sorted
return null;
throw new IllegalStateException();
}
}
static final class ArraySplitIterator KEY_GENERIC_TYPE implements JAVA_SPLIT_ITERATOR KEY_GENERIC_TYPE {
private final KEY_TYPE[] array;
private int index;
private final int fence;
private final int characteristics;
public ArraySplitIterator(KEY_TYPE[] array, int origin, int fence, int additionalCharacteristics) {
this.array = array;
index = origin;
this.fence = fence;
characteristics = additionalCharacteristics | Spliterator.SIZED | Spliterator.SUBSIZED;
}
@Override
public JAVA_SPLIT_ITERATOR KEY_GENERIC_TYPE trySplit() {
int lo = index, mid = (lo + fence) >>> 1;
return (lo >= mid) ? null : new ArraySplitIteratorBRACES(array, lo, index = mid, characteristics);
}
@Override
public void forEachRemaining(JAVA_CONSUMER action) {
if (action == null) throw new NullPointerException();
KEY_TYPE[] a; int i, hi;
if ((a = array).length >= (hi = fence) && (i = index) >= 0 && i < (index = hi)) {
do { action.accept(a[i]); } while (++i < hi);
}
}
@Override
public boolean tryAdvance(JAVA_CONSUMER action) {
if (action == null) throw new NullPointerException();
if (index >= 0 && index < fence) {
action.accept(array[index++]);
return true;
}
return false;
}
@Override
public long estimateSize() { return fence - index; }
@Override
public int characteristics() { return characteristics; }
@Override
public Comparator<? super JAVA_CLASS> getComparator() {
if (hasCharacteristics(4)) //Sorted if (hasCharacteristics(4)) //Sorted
return null; return null;
throw new IllegalStateException(); throw new IllegalStateException();
} }
}
static final class ArraySplitIterator KEY_GENERIC_TYPE implements JAVA_SPLIT_ITERATOR KEY_GENERIC_TYPE {
private final KEY_TYPE[] array;
private int index;
private final int fence;
private final int characteristics;
public ArraySplitIterator(KEY_TYPE[] array, int origin, int fence, int additionalCharacteristics) {
this.array = array;
index = origin;
this.fence = fence;
characteristics = additionalCharacteristics | Spliterator.SIZED | Spliterator.SUBSIZED;
}
@Override
public JAVA_SPLIT_ITERATOR KEY_GENERIC_TYPE trySplit() {
int lo = index, mid = (lo + fence) >>> 1;
return (lo >= mid) ? null : new ArraySplitIteratorBRACES(array, lo, index = mid, characteristics);
}
@Override
public void forEachRemaining(JAVA_CONSUMER action) {
if (action == null) throw new NullPointerException();
KEY_TYPE[] a; int i, hi;
if ((a = array).length >= (hi = fence) && (i = index) >= 0 && i < (index = hi)) {
do { action.accept(a[i]); } while (++i < hi);
}
}
@Override
public boolean tryAdvance(JAVA_CONSUMER action) {
if (action == null) throw new NullPointerException();
if (index >= 0 && index < fence) {
action.accept(array[index++]);
return true;
}
return false;
}
@Override
public long estimateSize() { return fence - index; }
@Override
public int characteristics() { return characteristics; }
@Override
public Comparator<? super JAVA_CLASS> getComparator() {
if (hasCharacteristics(4)) //Sorted
return null;
throw new IllegalStateException();
}
} }
#endif #endif
} }
@@ -6,6 +6,19 @@ package speiger.src.collections.PACKAGE.utils;
*/ */
public interface STRATEGY KEY_GENERIC_TYPE public interface STRATEGY KEY_GENERIC_TYPE
{ {
#if TYPE_OBJECT
/**
* Identity Strategy
*/
public static final STRATEGY NO_GENERIC_TYPE IDENTITY = new IdentityStrategyBRACES();
/**
* @Type(T)
* @return a IdentityStrategy that allows to emulate a IdentityHashMap
*/
public static GENERIC_KEY_BRACES STRATEGY KEY_GENERIC_TYPE identityStrategy() { return (STRATEGY<KEY_TYPE>)IDENTITY; }
#endif
/** /**
* Type Specific HashCode function * Type Specific HashCode function
* @param o the element that the hashcode is requested for (if object may be null) * @param o the element that the hashcode is requested for (if object may be null)
@@ -20,4 +33,19 @@ public interface STRATEGY KEY_GENERIC_TYPE
* @return if the elements match * @return if the elements match
*/ */
public boolean equals(KEY_TYPE key, KEY_TYPE value); public boolean equals(KEY_TYPE key, KEY_TYPE value);
#if TYPE_OBJECT
/**
* A Strategy that uses Identity HashCode instead of the normal hashing function.
* This simulates a IdentityHashMap without having the need to actually implement it.
* @Type(T)
*/
public static class IdentityStrategy KEY_GENERIC_TYPE implements STRATEGY KEY_GENERIC_TYPE
{
@Override
public int hashCode(KEY_TYPE o) { return System.identityHashCode(o); }
@Override
public boolean equals(KEY_TYPE key, KEY_TYPE value) { return key == value; }
}
#endif
} }
@@ -45,7 +45,6 @@ import speiger.src.collections.VALUE_PACKAGE.utils.VALUE_COLLECTIONS;
#if !SAME_TYPE && !VALUE_OBJECT #if !SAME_TYPE && !VALUE_OBJECT
import speiger.src.collections.VALUE_PACKAGE.utils.VALUE_SETS; import speiger.src.collections.VALUE_PACKAGE.utils.VALUE_SETS;
#endif #endif
#endif #endif
/** /**
@@ -110,7 +109,7 @@ public class MAPS
* @ValueType(V) * @ValueType(V)
* @return empty map of desired type * @return empty map of desired type
*/ */
public static GENERIC_KEY_VALUE_BRACES MAP KEY_VALUE_GENERIC_TYPE emptyMap() { public static GENERIC_KEY_VALUE_BRACES MAP KEY_VALUE_GENERIC_TYPE empty() {
#if TYPE_OBJECT || VALUE_OBJECT #if TYPE_OBJECT || VALUE_OBJECT
return (MAP KEY_VALUE_GENERIC_TYPE)EMPTY; return (MAP KEY_VALUE_GENERIC_TYPE)EMPTY;
#else #else
@@ -127,7 +126,7 @@ public class MAPS
* @note if the inputted map is already synchronized then it will just return it instead * @note if the inputted map is already synchronized then it will just return it instead
* @note iterators do not support synchronization * @note iterators do not support synchronization
*/ */
public static GENERIC_KEY_VALUE_BRACES MAP KEY_VALUE_GENERIC_TYPE synchronizeMap(MAP KEY_VALUE_GENERIC_TYPE map) { return map instanceof SynchronizedMap ? map : new SynchronizedMapKV_BRACES(map); } public static GENERIC_KEY_VALUE_BRACES MAP KEY_VALUE_GENERIC_TYPE synchronize(MAP KEY_VALUE_GENERIC_TYPE map) { return map instanceof SynchronizedMap ? map : new SynchronizedMapKV_BRACES(map); }
/** /**
* Helper function that creates a Helper wrapper to synchronize access with custom access control into the map. * Helper function that creates a Helper wrapper to synchronize access with custom access control into the map.
* @param map the map that should be synchronized * @param map the map that should be synchronized
@@ -138,7 +137,7 @@ public class MAPS
* @note if the inputted map is already synchronized then it will just return it instead * @note if the inputted map is already synchronized then it will just return it instead
* @note iterators do not support synchronization * @note iterators do not support synchronization
*/ */
public static GENERIC_KEY_VALUE_BRACES MAP KEY_VALUE_GENERIC_TYPE synchronizeMap(MAP KEY_VALUE_GENERIC_TYPE map, Object mutex) { return map instanceof SynchronizedMap ? map : new SynchronizedMapKV_BRACES(map, mutex); } public static GENERIC_KEY_VALUE_BRACES MAP KEY_VALUE_GENERIC_TYPE synchronize(MAP KEY_VALUE_GENERIC_TYPE map, Object mutex) { return map instanceof SynchronizedMap ? map : new SynchronizedMapKV_BRACES(map, mutex); }
/** /**
* Helper function that creates a Helper wrapper to synchronize access into the SortedMap. * Helper function that creates a Helper wrapper to synchronize access into the SortedMap.
@@ -149,7 +148,7 @@ public class MAPS
* @note if the inputted map is already synchronized then it will just return it instead * @note if the inputted map is already synchronized then it will just return it instead
* @note iterators do not support synchronization * @note iterators do not support synchronization
*/ */
public static GENERIC_KEY_VALUE_BRACES SORTED_MAP KEY_VALUE_GENERIC_TYPE synchronizeMap(SORTED_MAP KEY_VALUE_GENERIC_TYPE map) { return map instanceof SynchronizedSortedMap ? map : new SynchronizedSortedMapKV_BRACES(map); } public static GENERIC_KEY_VALUE_BRACES SORTED_MAP KEY_VALUE_GENERIC_TYPE synchronize(SORTED_MAP KEY_VALUE_GENERIC_TYPE map) { return map instanceof SynchronizedSortedMap ? map : new SynchronizedSortedMapKV_BRACES(map); }
/** /**
* Helper function that creates a Helper wrapper to synchronize access with custom access control into the SortedMap. * Helper function that creates a Helper wrapper to synchronize access with custom access control into the SortedMap.
* @param map the SortedMap that should be synchronized * @param map the SortedMap that should be synchronized
@@ -160,7 +159,7 @@ public class MAPS
* @note if the inputted map is already synchronized then it will just return it instead * @note if the inputted map is already synchronized then it will just return it instead
* @note iterators do not support synchronization * @note iterators do not support synchronization
*/ */
public static GENERIC_KEY_VALUE_BRACES SORTED_MAP KEY_VALUE_GENERIC_TYPE synchronizeMap(SORTED_MAP KEY_VALUE_GENERIC_TYPE map, Object mutex) { return map instanceof SynchronizedSortedMap ? map : new SynchronizedSortedMapKV_BRACES(map, mutex); } public static GENERIC_KEY_VALUE_BRACES SORTED_MAP KEY_VALUE_GENERIC_TYPE synchronize(SORTED_MAP KEY_VALUE_GENERIC_TYPE map, Object mutex) { return map instanceof SynchronizedSortedMap ? map : new SynchronizedSortedMapKV_BRACES(map, mutex); }
/** /**
* Helper function that creates a Helper wrapper to synchronize access into the NavigableMap. * Helper function that creates a Helper wrapper to synchronize access into the NavigableMap.
@@ -171,7 +170,7 @@ public class MAPS
* @note if the inputted map is already synchronized then it will just return it instead * @note if the inputted map is already synchronized then it will just return it instead
* @note iterators do not support synchronization * @note iterators do not support synchronization
*/ */
public static GENERIC_KEY_VALUE_BRACES NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE synchronizeMap(NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE map) { return map instanceof SynchronizedNavigableMap ? map : new SynchronizedNavigableMapKV_BRACES(map); } public static GENERIC_KEY_VALUE_BRACES NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE synchronize(NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE map) { return map instanceof SynchronizedNavigableMap ? map : new SynchronizedNavigableMapKV_BRACES(map); }
/** /**
* Helper function that creates a Helper wrapper to synchronize access with custom access control into the NavigableMap. * Helper function that creates a Helper wrapper to synchronize access with custom access control into the NavigableMap.
* @param map the NavigableMap that should be synchronized * @param map the NavigableMap that should be synchronized
@@ -182,7 +181,7 @@ public class MAPS
* @note if the inputted map is already synchronized then it will just return it instead * @note if the inputted map is already synchronized then it will just return it instead
* @note iterators do not support synchronization * @note iterators do not support synchronization
*/ */
public static GENERIC_KEY_VALUE_BRACES NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE synchronizeMap(NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE map, Object mutex) { return map instanceof SynchronizedNavigableMap ? map : new SynchronizedNavigableMapKV_BRACES(map, mutex); } public static GENERIC_KEY_VALUE_BRACES NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE synchronize(NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE map, Object mutex) { return map instanceof SynchronizedNavigableMap ? map : new SynchronizedNavigableMapKV_BRACES(map, mutex); }
/** /**
* A Helper function that creates a Helper wrapper to only allow Read Access into the Map * A Helper function that creates a Helper wrapper to only allow Read Access into the Map
@@ -192,7 +191,7 @@ public class MAPS
* @return a unmodifiable Map * @return a unmodifiable Map
* @note if the inputted map is already unmodifiable then it will just return it instead * @note if the inputted map is already unmodifiable then it will just return it instead
*/ */
public static GENERIC_KEY_VALUE_BRACES MAP KEY_VALUE_GENERIC_TYPE unmodifyableMap(MAP KEY_VALUE_GENERIC_TYPE map) { return map instanceof UnmodifyableMap ? map : new UnmodifyableMapKV_BRACES(map); } public static GENERIC_KEY_VALUE_BRACES MAP KEY_VALUE_GENERIC_TYPE unmodifiable(MAP KEY_VALUE_GENERIC_TYPE map) { return map instanceof UnmodifyableMap ? map : new UnmodifyableMapKV_BRACES(map); }
/** /**
* A Helper function that creates a Helper wrapper to only allow Read Access into the SortedMap * A Helper function that creates a Helper wrapper to only allow Read Access into the SortedMap
* @param map the SortedMap that should be made Unmodifiable * @param map the SortedMap that should be made Unmodifiable
@@ -201,7 +200,7 @@ public class MAPS
* @return a unmodifiable SortedMap * @return a unmodifiable SortedMap
* @note if the inputted SortedMap is already unmodifiable then it will just return it instead * @note if the inputted SortedMap is already unmodifiable then it will just return it instead
*/ */
public static GENERIC_KEY_VALUE_BRACES SORTED_MAP KEY_VALUE_GENERIC_TYPE unmodifyableMap(SORTED_MAP KEY_VALUE_GENERIC_TYPE map) { return map instanceof UnmodifyableSortedMap ? map : new UnmodifyableSortedMapKV_BRACES(map); } public static GENERIC_KEY_VALUE_BRACES SORTED_MAP KEY_VALUE_GENERIC_TYPE unmodifiable(SORTED_MAP KEY_VALUE_GENERIC_TYPE map) { return map instanceof UnmodifyableSortedMap ? map : new UnmodifyableSortedMapKV_BRACES(map); }
/** /**
* A Helper function that creates a Helper wrapper to only allow Read Access into NavigableMap Map * A Helper function that creates a Helper wrapper to only allow Read Access into NavigableMap Map
* @param map the NavigableMap that should be made Unmodifiable * @param map the NavigableMap that should be made Unmodifiable
@@ -210,23 +209,23 @@ public class MAPS
* @return a unmodifiable NavigableMap * @return a unmodifiable NavigableMap
* @note if the inputted NavigableMap is already unmodifiable then it will just return it instead * @note if the inputted NavigableMap is already unmodifiable then it will just return it instead
*/ */
public static GENERIC_KEY_VALUE_BRACES NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE unmodifyableMap(NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE map) { return map instanceof UnmodifyableNavigableMap ? map : new UnmodifyableNavigableMapKV_BRACES(map); } public static GENERIC_KEY_VALUE_BRACES NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE unmodifiable(NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE map) { return map instanceof UnmodifyableNavigableMap ? map : new UnmodifyableNavigableMapKV_BRACES(map); }
/** /**
* A Helper function that creates a Unmodifyable Entry * A Helper function that creates a Unmodifyable Entry
* @param entry the Entry that should be made unmodifyable * @param entry the Entry that should be made unmodifiable
* @Type(T) * @Type(T)
* @ValueType(V) * @ValueType(V)
* @return a Unmodifyable Entry * @return a Unmodifyable Entry
*/ */
public static GENERIC_KEY_VALUE_BRACES MAP.Entry KEY_VALUE_GENERIC_TYPE unmodifyableEntry(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { return entry instanceof UnmodifyableEntry ? entry : new UnmodifyableEntryKV_BRACES(entry); } public static GENERIC_KEY_VALUE_BRACES MAP.Entry KEY_VALUE_GENERIC_TYPE unmodifiable(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { return entry instanceof UnmodifyableEntry ? entry : new UnmodifyableEntryKV_BRACES(entry); }
/** /**
* A Helper function that creates a Unmodifyable Entry * A Helper function that creates a Unmodifyable Entry
* @param entry the Entry that should be made unmodifyable * @param entry the Entry that should be made unmodifiable
* @Type(T) * @Type(T)
* @ValueType(V) * @ValueType(V)
* @return a Unmodifyable Entry * @return a Unmodifyable Entry
*/ */
public static GENERIC_KEY_VALUE_BRACES MAP.Entry KEY_VALUE_GENERIC_TYPE unmodifyableEntry(Map.Entry<CLASS_TYPE, CLASS_VALUE_TYPE> entry) { return entry instanceof UnmodifyableEntry ? (UnmodifyableEntry KEY_VALUE_GENERIC_TYPE)entry : new UnmodifyableEntryKV_BRACES(entry); } public static GENERIC_KEY_VALUE_BRACES MAP.Entry KEY_VALUE_GENERIC_TYPE unmodifiable(Map.Entry<CLASS_TYPE, CLASS_VALUE_TYPE> entry) { return entry instanceof UnmodifyableEntry ? (UnmodifyableEntry KEY_VALUE_GENERIC_TYPE)entry : new UnmodifyableEntryKV_BRACES(entry); }
/** /**
* Creates a Singleton map from the provided values. * Creates a Singleton map from the provided values.
@@ -235,9 +234,9 @@ public class MAPS
* @param value the value that should be turned into a singleton * @param value the value that should be turned into a singleton
* @Type(T) * @Type(T)
* @ValueType(V) * @ValueType(V)
* @return a unmodifyable Singleton map. * @return a unmodifiable Singleton map.
*/ */
public static GENERIC_KEY_VALUE_BRACES MAP KEY_VALUE_GENERIC_TYPE singletonMap(KEY_TYPE key, VALUE_TYPE value) { return new SingletonMapKV_BRACES(key, value); } public static GENERIC_KEY_VALUE_BRACES MAP KEY_VALUE_GENERIC_TYPE singleton(KEY_TYPE key, VALUE_TYPE value) { return new SingletonMapKV_BRACES(key, value); }
/** /**
* Singleton Map instance that is used in the helper method * Singleton Map instance that is used in the helper method
@@ -265,7 +264,9 @@ public class MAPS
public VALUE_TYPE addTo(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); } public VALUE_TYPE addTo(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); }
#endif #endif
@Override @Override
public VALUE_TYPE REMOVE_KEY(KEY_TYPE key) { throw new UnsupportedOperationException(); } public VALUE_TYPE REMOVE_VALUE(KEY_TYPE key) { throw new UnsupportedOperationException(); }
@Override
public VALUE_TYPE REMOVE_VALUEOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { throw new UnsupportedOperationException(); }
#if !TYPE_OBJECT || !VALUE_OBJECT #if !TYPE_OBJECT || !VALUE_OBJECT
@Override @Override
public boolean remove(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); } public boolean remove(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); }
@@ -276,20 +277,22 @@ public class MAPS
@Override @Override
public VALUE_TYPE getOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { return EQUALS_KEY_TYPE(key, this.key) ? value : defaultValue; } public VALUE_TYPE getOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { return EQUALS_KEY_TYPE(key, this.key) ? value : defaultValue; }
#endif #endif
@Override
public SingletonMap KEY_VALUE_GENERIC_TYPE copy() { return new SingletonMapKV_BRACES(key, value); }
@Override @Override
public SET KEY_GENERIC_TYPE keySet() { public SET KEY_GENERIC_TYPE keySet() {
if(keySet == null) keySet = SETS.singletonSet(key); if(keySet == null) keySet = SETS.singleton(key);
return keySet; return keySet;
} }
@Override @Override
public VALUE_COLLECTION VALUE_GENERIC_TYPE values() { public VALUE_COLLECTION VALUE_GENERIC_TYPE values() {
if(values == null) values = VALUE_SETS.singletonSet(value); if(values == null) values = VALUE_SETS.singleton(value);
return values; return values;
} }
@Override @Override
public ObjectSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> ENTRY_SET() { public ObjectSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> ENTRY_SET() {
if(entrySet == null) entrySet = ObjectSets.singletonSet(new ABSTRACT_MAP.BasicEntryKV_BRACES(key, value)); if(entrySet == null) entrySet = ObjectSets.singleton(new ABSTRACT_MAP.BasicEntryKV_BRACES(key, value));
return entrySet; return entrySet;
} }
} }
@@ -309,7 +312,9 @@ public class MAPS
public VALUE_TYPE addTo(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); } public VALUE_TYPE addTo(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); }
#endif #endif
@Override @Override
public VALUE_TYPE REMOVE_KEY(KEY_TYPE key) { throw new UnsupportedOperationException(); } public VALUE_TYPE REMOVE_VALUE(KEY_TYPE key) { throw new UnsupportedOperationException(); }
@Override
public VALUE_TYPE REMOVE_VALUEOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { throw new UnsupportedOperationException(); }
#if !TYPE_OBJECT || !VALUE_OBJECT #if !TYPE_OBJECT || !VALUE_OBJECT
@Override @Override
public boolean remove(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); } public boolean remove(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); }
@@ -323,9 +328,11 @@ public class MAPS
@Override @Override
public SET KEY_GENERIC_TYPE keySet() { return SETS.empty(); } public SET KEY_GENERIC_TYPE keySet() { return SETS.empty(); }
@Override @Override
public VALUE_COLLECTION VALUE_GENERIC_TYPE values() { return VALUE_COLLECTIONS.emptyCollection(); } public VALUE_COLLECTION VALUE_GENERIC_TYPE values() { return VALUE_COLLECTIONS.empty(); }
@Override @Override
public ObjectSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> ENTRY_SET() { return ObjectSets.empty(); } public ObjectSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> ENTRY_SET() { return ObjectSets.empty(); }
@Override
public EmptyMap KEY_VALUE_GENERIC_TYPE copy() { return this; }
} }
/** /**
@@ -361,31 +368,31 @@ public class MAPS
} }
@Override @Override
public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE descendingMap() { return unmodifyableMap(map.descendingMap()); } public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE descendingMap() { return MAPS.synchronize(map.descendingMap()); }
@Override @Override
public NAVIGABLE_SET KEY_GENERIC_TYPE navigableKeySet() { return SETS.unmodifiable(map.navigableKeySet()); } public NAVIGABLE_SET KEY_GENERIC_TYPE navigableKeySet() { return SETS.unmodifiable(map.navigableKeySet()); }
@Override @Override
public NAVIGABLE_SET KEY_GENERIC_TYPE descendingKeySet() { return SETS.unmodifiable(map.descendingKeySet()); } public NAVIGABLE_SET KEY_GENERIC_TYPE descendingKeySet() { return SETS.unmodifiable(map.descendingKeySet()); }
@Override @Override
public MAP.Entry KEY_VALUE_GENERIC_TYPE firstEntry() { return unmodifyableEntry(map.firstEntry()); } public MAP.Entry KEY_VALUE_GENERIC_TYPE firstEntry() { return MAPS.unmodifiable(map.firstEntry()); }
@Override @Override
public MAP.Entry KEY_VALUE_GENERIC_TYPE lastEntry() { return unmodifyableEntry(map.lastEntry()); } public MAP.Entry KEY_VALUE_GENERIC_TYPE lastEntry() { return MAPS.unmodifiable(map.lastEntry()); }
@Override @Override
public MAP.Entry KEY_VALUE_GENERIC_TYPE pollFirstEntry() { throw new UnsupportedOperationException(); } public MAP.Entry KEY_VALUE_GENERIC_TYPE pollFirstEntry() { throw new UnsupportedOperationException(); }
@Override @Override
public MAP.Entry KEY_VALUE_GENERIC_TYPE pollLastEntry() { throw new UnsupportedOperationException(); } public MAP.Entry KEY_VALUE_GENERIC_TYPE pollLastEntry() { throw new UnsupportedOperationException(); }
@Override @Override
public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE subMap(KEY_TYPE fromKey, boolean fromInclusive, KEY_TYPE toKey, boolean toInclusive) { return unmodifyableMap(map.subMap(fromKey, fromInclusive, toKey, toInclusive)); } public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE subMap(KEY_TYPE fromKey, boolean fromInclusive, KEY_TYPE toKey, boolean toInclusive) { return MAPS.unmodifiable(map.subMap(fromKey, fromInclusive, toKey, toInclusive)); }
@Override @Override
public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE headMap(KEY_TYPE toKey, boolean inclusive) { return unmodifyableMap(map.headMap(toKey, inclusive)); } public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE headMap(KEY_TYPE toKey, boolean inclusive) { return MAPS.unmodifiable(map.headMap(toKey, inclusive)); }
@Override @Override
public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE tailMap(KEY_TYPE fromKey, boolean inclusive) { return unmodifyableMap(map.tailMap(fromKey, inclusive)); } public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE tailMap(KEY_TYPE fromKey, boolean inclusive) { return MAPS.unmodifiable(map.tailMap(fromKey, inclusive)); }
@Override @Override
public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE subMap(KEY_TYPE fromKey, KEY_TYPE toKey) { return unmodifyableMap(map.subMap(fromKey, toKey)); } public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE subMap(KEY_TYPE fromKey, KEY_TYPE toKey) { return MAPS.unmodifiable(map.subMap(fromKey, toKey)); }
@Override @Override
public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE headMap(KEY_TYPE toKey) { return unmodifyableMap(map.headMap(toKey)); } public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE headMap(KEY_TYPE toKey) { return MAPS.unmodifiable(map.headMap(toKey)); }
@Override @Override
public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE tailMap(KEY_TYPE fromKey) { return unmodifyableMap(map.tailMap(fromKey)); } public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE tailMap(KEY_TYPE fromKey) { return MAPS.unmodifiable(map.tailMap(fromKey)); }
#if !TYPE_OBJECT #if !TYPE_OBJECT
@Override @Override
public void setDefaultMaxValue(KEY_TYPE e) { throw new UnsupportedOperationException(); } public void setDefaultMaxValue(KEY_TYPE e) { throw new UnsupportedOperationException(); }
@@ -405,13 +412,15 @@ public class MAPS
@Override @Override
public KEY_TYPE ceilingKey(KEY_TYPE key) { return map.ceilingKey(key); } public KEY_TYPE ceilingKey(KEY_TYPE key) { return map.ceilingKey(key); }
@Override @Override
public MAP.Entry KEY_VALUE_GENERIC_TYPE lowerEntry(KEY_TYPE key) { return unmodifyableEntry(map.lowerEntry(key)); } public MAP.Entry KEY_VALUE_GENERIC_TYPE lowerEntry(KEY_TYPE key) { return MAPS.unmodifiable(map.lowerEntry(key)); }
@Override @Override
public MAP.Entry KEY_VALUE_GENERIC_TYPE higherEntry(KEY_TYPE key) { return unmodifyableEntry(map.higherEntry(key)); } public MAP.Entry KEY_VALUE_GENERIC_TYPE higherEntry(KEY_TYPE key) { return MAPS.unmodifiable(map.higherEntry(key)); }
@Override @Override
public MAP.Entry KEY_VALUE_GENERIC_TYPE floorEntry(KEY_TYPE key) { return unmodifyableEntry(map.floorEntry(key)); } public MAP.Entry KEY_VALUE_GENERIC_TYPE floorEntry(KEY_TYPE key) { return MAPS.unmodifiable(map.floorEntry(key)); }
@Override @Override
public MAP.Entry KEY_VALUE_GENERIC_TYPE ceilingEntry(KEY_TYPE key) { return unmodifyableEntry(map.ceilingEntry(key)); } public MAP.Entry KEY_VALUE_GENERIC_TYPE ceilingEntry(KEY_TYPE key) { return MAPS.unmodifiable(map.ceilingEntry(key)); }
@Override
public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE copy() { throw new UnsupportedOperationException(); }
} }
/** /**
@@ -442,11 +451,11 @@ public class MAPS
@Override @Override
public COMPARATOR KEY_GENERIC_TYPE comparator() { return map.comparator(); } public COMPARATOR KEY_GENERIC_TYPE comparator() { return map.comparator(); }
@Override @Override
public SORTED_MAP KEY_VALUE_GENERIC_TYPE subMap(KEY_TYPE fromKey, KEY_TYPE toKey) { return unmodifyableMap(map.subMap(fromKey, toKey)); } public SORTED_MAP KEY_VALUE_GENERIC_TYPE subMap(KEY_TYPE fromKey, KEY_TYPE toKey) { return MAPS.unmodifiable(map.subMap(fromKey, toKey)); }
@Override @Override
public SORTED_MAP KEY_VALUE_GENERIC_TYPE headMap(KEY_TYPE toKey) { return unmodifyableMap(map.headMap(toKey)); } public SORTED_MAP KEY_VALUE_GENERIC_TYPE headMap(KEY_TYPE toKey) { return MAPS.unmodifiable(map.headMap(toKey)); }
@Override @Override
public SORTED_MAP KEY_VALUE_GENERIC_TYPE tailMap(KEY_TYPE fromKey) { return unmodifyableMap(map.tailMap(fromKey)); } public SORTED_MAP KEY_VALUE_GENERIC_TYPE tailMap(KEY_TYPE fromKey) { return MAPS.unmodifiable(map.tailMap(fromKey)); }
@Override @Override
public KEY_TYPE FIRST_ENTRY_KEY() { return map.FIRST_ENTRY_KEY(); } public KEY_TYPE FIRST_ENTRY_KEY() { return map.FIRST_ENTRY_KEY(); }
@Override @Override
@@ -459,6 +468,8 @@ public class MAPS
public VALUE_TYPE FIRST_ENTRY_VALUE() { return map.FIRST_ENTRY_VALUE(); } public VALUE_TYPE FIRST_ENTRY_VALUE() { return map.FIRST_ENTRY_VALUE(); }
@Override @Override
public VALUE_TYPE LAST_ENTRY_VALUE() { return map.LAST_ENTRY_VALUE(); } public VALUE_TYPE LAST_ENTRY_VALUE() { return map.LAST_ENTRY_VALUE(); }
@Override
public SORTED_MAP KEY_VALUE_GENERIC_TYPE copy() { throw new UnsupportedOperationException(); }
} }
/** /**
@@ -485,7 +496,9 @@ public class MAPS
public VALUE_TYPE addTo(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); } public VALUE_TYPE addTo(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); }
#endif #endif
@Override @Override
public VALUE_TYPE REMOVE_KEY(KEY_TYPE key) { throw new UnsupportedOperationException(); } public VALUE_TYPE REMOVE_VALUE(KEY_TYPE key) { throw new UnsupportedOperationException(); }
@Override
public VALUE_TYPE REMOVE_VALUEOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { throw new UnsupportedOperationException(); }
#if !TYPE_OBJECT || !VALUE_OBJECT #if !TYPE_OBJECT || !VALUE_OBJECT
@Override @Override
public boolean remove(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); } public boolean remove(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); }
@@ -496,6 +509,8 @@ public class MAPS
@Override @Override
public VALUE_TYPE getOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { return map.getOrDefault(key, defaultValue); } public VALUE_TYPE getOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { return map.getOrDefault(key, defaultValue); }
#endif #endif
@Override
public MAP KEY_VALUE_GENERIC_TYPE copy() { throw new UnsupportedOperationException(); }
@Override @Override
public SET KEY_GENERIC_TYPE keySet() { public SET KEY_GENERIC_TYPE keySet() {
@@ -505,7 +520,7 @@ public class MAPS
@Override @Override
public VALUE_COLLECTION VALUE_GENERIC_TYPE values() { public VALUE_COLLECTION VALUE_GENERIC_TYPE values() {
if(values == null) values = VALUE_COLLECTIONS.unmodifiableCollection(map.values()); if(values == null) values = VALUE_COLLECTIONS.unmodifiable(map.values());
return values; return values;
} }
@@ -533,7 +548,7 @@ public class MAPS
@Override @Override
public void forEach(Consumer<? super MAP.Entry KEY_VALUE_GENERIC_TYPE> action) { public void forEach(Consumer<? super MAP.Entry KEY_VALUE_GENERIC_TYPE> action) {
s.forEach(T -> action.accept(unmodifyableEntry(T))); s.forEach(T -> action.accept(MAPS.unmodifiable(T)));
} }
@Override @Override
@@ -543,7 +558,7 @@ public class MAPS
@Override @Override
public boolean hasNext() { return iter.hasNext(); } public boolean hasNext() { return iter.hasNext(); }
@Override @Override
public MAP.Entry KEY_VALUE_GENERIC_TYPE next() { return unmodifyableEntry(iter.next()); } public MAP.Entry KEY_VALUE_GENERIC_TYPE next() { return MAPS.unmodifiable(iter.next()); }
}; };
} }
@@ -568,11 +583,11 @@ public class MAPS
} }
@Override @Override
public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE descendingMap() { synchronized(mutex) { return synchronizeMap(map.descendingMap(), mutex); } } public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE descendingMap() { synchronized(mutex) { return MAPS.synchronize(map.descendingMap(), mutex); } }
@Override @Override
public NAVIGABLE_SET KEY_GENERIC_TYPE navigableKeySet() { synchronized(mutex) { return SETS.synchronizedSet(map.navigableKeySet(), mutex); } } public NAVIGABLE_SET KEY_GENERIC_TYPE navigableKeySet() { synchronized(mutex) { return SETS.synchronize(map.navigableKeySet(), mutex); } }
@Override @Override
public NAVIGABLE_SET KEY_GENERIC_TYPE descendingKeySet() { synchronized(mutex) { return SETS.synchronizedSet(map.descendingKeySet(), mutex); } } public NAVIGABLE_SET KEY_GENERIC_TYPE descendingKeySet() { synchronized(mutex) { return SETS.synchronize(map.descendingKeySet(), mutex); } }
@Override @Override
public MAP.Entry KEY_VALUE_GENERIC_TYPE firstEntry() { synchronized(mutex) { return map.firstEntry(); } } public MAP.Entry KEY_VALUE_GENERIC_TYPE firstEntry() { synchronized(mutex) { return map.firstEntry(); } }
@Override @Override
@@ -582,17 +597,17 @@ public class MAPS
@Override @Override
public MAP.Entry KEY_VALUE_GENERIC_TYPE pollLastEntry() { synchronized(mutex) { return map.pollLastEntry(); } } public MAP.Entry KEY_VALUE_GENERIC_TYPE pollLastEntry() { synchronized(mutex) { return map.pollLastEntry(); } }
@Override @Override
public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE subMap(KEY_TYPE fromKey, boolean fromInclusive, KEY_TYPE toKey, boolean toInclusive) { synchronized(mutex) { return synchronizeMap(map.subMap(fromKey, fromInclusive, toKey, toInclusive), mutex); } } public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE subMap(KEY_TYPE fromKey, boolean fromInclusive, KEY_TYPE toKey, boolean toInclusive) { synchronized(mutex) { return MAPS.synchronize(map.subMap(fromKey, fromInclusive, toKey, toInclusive), mutex); } }
@Override @Override
public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE headMap(KEY_TYPE toKey, boolean inclusive) { synchronized(mutex) { return synchronizeMap(map.headMap(toKey, inclusive), mutex); } } public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE headMap(KEY_TYPE toKey, boolean inclusive) { synchronized(mutex) { return MAPS.synchronize(map.headMap(toKey, inclusive), mutex); } }
@Override @Override
public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE tailMap(KEY_TYPE fromKey, boolean inclusive) { synchronized(mutex) { return synchronizeMap(map.tailMap(fromKey, inclusive), mutex); } } public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE tailMap(KEY_TYPE fromKey, boolean inclusive) { synchronized(mutex) { return MAPS.synchronize(map.tailMap(fromKey, inclusive), mutex); } }
@Override @Override
public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE subMap(KEY_TYPE fromKey, KEY_TYPE toKey) { synchronized(mutex) { return synchronizeMap(map.subMap(fromKey, toKey), mutex); } } public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE subMap(KEY_TYPE fromKey, KEY_TYPE toKey) { synchronized(mutex) { return MAPS.synchronize(map.subMap(fromKey, toKey), mutex); } }
@Override @Override
public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE headMap(KEY_TYPE toKey) { synchronized(mutex) { return synchronizeMap(map.headMap(toKey), mutex); } } public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE headMap(KEY_TYPE toKey) { synchronized(mutex) { return MAPS.synchronize(map.headMap(toKey), mutex); } }
@Override @Override
public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE tailMap(KEY_TYPE fromKey) { synchronized(mutex) { return synchronizeMap(map.tailMap(fromKey), mutex); } } public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE tailMap(KEY_TYPE fromKey) { synchronized(mutex) { return MAPS.synchronize(map.tailMap(fromKey), mutex); } }
@Override @Override
public KEY_TYPE lowerKey(KEY_TYPE key) { synchronized(mutex) { return map.lowerKey(key); } } public KEY_TYPE lowerKey(KEY_TYPE key) { synchronized(mutex) { return map.lowerKey(key); } }
@Override @Override
@@ -609,25 +624,27 @@ public class MAPS
public MAP.Entry KEY_VALUE_GENERIC_TYPE floorEntry(KEY_TYPE key) { synchronized(mutex) { return map.floorEntry(key); } } public MAP.Entry KEY_VALUE_GENERIC_TYPE floorEntry(KEY_TYPE key) { synchronized(mutex) { return map.floorEntry(key); } }
@Override @Override
public MAP.Entry KEY_VALUE_GENERIC_TYPE ceilingEntry(KEY_TYPE key) { synchronized(mutex) { return map.ceilingEntry(key); } } public MAP.Entry KEY_VALUE_GENERIC_TYPE ceilingEntry(KEY_TYPE key) { synchronized(mutex) { return map.ceilingEntry(key); } }
#if !TYPE_OBJECT @Override
public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE copy() { throw new UnsupportedOperationException(); }
#if !TYPE_OBJECT
@Override @Override
@Deprecated @Deprecated
public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE subMap(CLASS_TYPE fromKey, boolean fromInclusive, CLASS_TYPE toKey, boolean toInclusive) { synchronized(mutex) { return synchronizeMap(map.subMap(fromKey, fromInclusive, toKey, toInclusive), mutex); } } public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE subMap(CLASS_TYPE fromKey, boolean fromInclusive, CLASS_TYPE toKey, boolean toInclusive) { synchronized(mutex) { return MAPS.synchronize(map.subMap(fromKey, fromInclusive, toKey, toInclusive), mutex); } }
@Override @Override
@Deprecated @Deprecated
public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE headMap(CLASS_TYPE toKey, boolean inclusive) { synchronized(mutex) { return synchronizeMap(map.headMap(toKey, inclusive), mutex); } } public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE headMap(CLASS_TYPE toKey, boolean inclusive) { synchronized(mutex) { return MAPS.synchronize(map.headMap(toKey, inclusive), mutex); } }
@Override @Override
@Deprecated @Deprecated
public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE tailMap(CLASS_TYPE fromKey, boolean inclusive) { synchronized(mutex) { return synchronizeMap(map.tailMap(fromKey, inclusive), mutex); } } public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE tailMap(CLASS_TYPE fromKey, boolean inclusive) { synchronized(mutex) { return MAPS.synchronize(map.tailMap(fromKey, inclusive), mutex); } }
@Override @Override
@Deprecated @Deprecated
public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE subMap(CLASS_TYPE fromKey, CLASS_TYPE toKey) { synchronized(mutex) { return synchronizeMap(map.subMap(fromKey, toKey), mutex); } } public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE subMap(CLASS_TYPE fromKey, CLASS_TYPE toKey) { synchronized(mutex) { return MAPS.synchronize(map.subMap(fromKey, toKey), mutex); } }
@Override @Override
@Deprecated @Deprecated
public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE headMap(CLASS_TYPE toKey) { synchronized(mutex) { return synchronizeMap(map.headMap(toKey), mutex); } } public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE headMap(CLASS_TYPE toKey) { synchronized(mutex) { return MAPS.synchronize(map.headMap(toKey), mutex); } }
@Override @Override
@Deprecated @Deprecated
public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE tailMap(CLASS_TYPE fromKey) { synchronized(mutex) { return synchronizeMap(map.tailMap(fromKey), mutex); } } public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE tailMap(CLASS_TYPE fromKey) { synchronized(mutex) { return MAPS.synchronize(map.tailMap(fromKey), mutex); } }
@Override @Override
public void setDefaultMaxValue(KEY_TYPE e) { synchronized(mutex) { map.setDefaultMaxValue(e); } } public void setDefaultMaxValue(KEY_TYPE e) { synchronized(mutex) { map.setDefaultMaxValue(e); } }
@Override @Override
@@ -696,11 +713,11 @@ public class MAPS
@Override @Override
public COMPARATOR KEY_GENERIC_TYPE comparator() { synchronized(mutex) { return map.comparator(); } } public COMPARATOR KEY_GENERIC_TYPE comparator() { synchronized(mutex) { return map.comparator(); } }
@Override @Override
public SORTED_MAP KEY_VALUE_GENERIC_TYPE subMap(KEY_TYPE fromKey, KEY_TYPE toKey) { synchronized(mutex) { return synchronizeMap(map.subMap(fromKey, toKey), mutex); } } public SORTED_MAP KEY_VALUE_GENERIC_TYPE subMap(KEY_TYPE fromKey, KEY_TYPE toKey) { synchronized(mutex) { return MAPS.synchronize(map.subMap(fromKey, toKey), mutex); } }
@Override @Override
public SORTED_MAP KEY_VALUE_GENERIC_TYPE headMap(KEY_TYPE toKey) { synchronized(mutex) { return synchronizeMap(map.headMap(toKey), mutex); } } public SORTED_MAP KEY_VALUE_GENERIC_TYPE headMap(KEY_TYPE toKey) { synchronized(mutex) { return MAPS.synchronize(map.headMap(toKey), mutex); } }
@Override @Override
public SORTED_MAP KEY_VALUE_GENERIC_TYPE tailMap(KEY_TYPE fromKey) { synchronized(mutex) { return synchronizeMap(map.tailMap(fromKey), mutex); } } public SORTED_MAP KEY_VALUE_GENERIC_TYPE tailMap(KEY_TYPE fromKey) { synchronized(mutex) { return MAPS.synchronize(map.tailMap(fromKey), mutex); } }
@Override @Override
public KEY_TYPE FIRST_ENTRY_KEY() { synchronized(mutex) { return map.FIRST_ENTRY_KEY(); } } public KEY_TYPE FIRST_ENTRY_KEY() { synchronized(mutex) { return map.FIRST_ENTRY_KEY(); } }
@Override @Override
@@ -713,6 +730,8 @@ public class MAPS
public VALUE_TYPE FIRST_ENTRY_VALUE() { synchronized(mutex) { return map.FIRST_ENTRY_VALUE(); } } public VALUE_TYPE FIRST_ENTRY_VALUE() { synchronized(mutex) { return map.FIRST_ENTRY_VALUE(); } }
@Override @Override
public VALUE_TYPE LAST_ENTRY_VALUE() { synchronized(mutex) { return map.LAST_ENTRY_VALUE(); } } public VALUE_TYPE LAST_ENTRY_VALUE() { synchronized(mutex) { return map.LAST_ENTRY_VALUE(); } }
@Override
public SORTED_MAP KEY_VALUE_GENERIC_TYPE copy() { throw new UnsupportedOperationException(); }
#if !TYPE_OBJECT #if !TYPE_OBJECT
@Override @Override
@Deprecated @Deprecated
@@ -722,13 +741,13 @@ public class MAPS
public CLASS_TYPE lastKey() { synchronized(mutex) { return map.lastKey(); } } public CLASS_TYPE lastKey() { synchronized(mutex) { return map.lastKey(); } }
@Override @Override
@Deprecated @Deprecated
public SORTED_MAP KEY_VALUE_GENERIC_TYPE subMap(CLASS_TYPE fromKey, CLASS_TYPE toKey) { synchronized(mutex) { return synchronizeMap(map.subMap(fromKey, toKey), mutex); } } public SORTED_MAP KEY_VALUE_GENERIC_TYPE subMap(CLASS_TYPE fromKey, CLASS_TYPE toKey) { synchronized(mutex) { return MAPS.synchronize(map.subMap(fromKey, toKey), mutex); } }
@Override @Override
@Deprecated @Deprecated
public SORTED_MAP KEY_VALUE_GENERIC_TYPE headMap(CLASS_TYPE toKey) { synchronized(mutex) { return synchronizeMap(map.headMap(toKey), mutex); } } public SORTED_MAP KEY_VALUE_GENERIC_TYPE headMap(CLASS_TYPE toKey) { synchronized(mutex) { return MAPS.synchronize(map.headMap(toKey), mutex); } }
@Override @Override
@Deprecated @Deprecated
public SORTED_MAP KEY_VALUE_GENERIC_TYPE tailMap(CLASS_TYPE fromKey) { synchronized(mutex) { return synchronizeMap(map.tailMap(fromKey), mutex); } } public SORTED_MAP KEY_VALUE_GENERIC_TYPE tailMap(CLASS_TYPE fromKey) { synchronized(mutex) { return MAPS.synchronize(map.tailMap(fromKey), mutex); } }
#endif #endif
} }
@@ -768,14 +787,19 @@ public class MAPS
public VALUE_TYPE put(KEY_TYPE key, VALUE_TYPE value) { synchronized(mutex) { return map.put(key, value); } } public VALUE_TYPE put(KEY_TYPE key, VALUE_TYPE value) { synchronized(mutex) { return map.put(key, value); } }
@Override @Override
public VALUE_TYPE putIfAbsent(KEY_TYPE key, VALUE_TYPE value) { synchronized(mutex) { return map.putIfAbsent(key, value); } } public VALUE_TYPE putIfAbsent(KEY_TYPE key, VALUE_TYPE value) { synchronized(mutex) { return map.putIfAbsent(key, value); } }
public void putAllIfAbsent(MAP KEY_VALUE_GENERIC_TYPE m) { synchronized(mutex) { map.putAllIfAbsent(m); } }
#if VALUE_PRIMITIVES #if VALUE_PRIMITIVES
@Override @Override
public VALUE_TYPE addTo(KEY_TYPE key, VALUE_TYPE value) { synchronized(mutex) { return map.addTo(key, value); } } public VALUE_TYPE addTo(KEY_TYPE key, VALUE_TYPE value) { synchronized(mutex) { return map.addTo(key, value); } }
public void addToAll(MAP KEY_VALUE_GENERIC_TYPE m) { synchronized(mutex) { map.addToAll(m); } }
#endif #endif
@Override @Override
public void putAll(MAP KEY_VALUE_GENERIC_TYPE m) { synchronized(mutex) { map.putAll(m); } } public void putAll(MAP KEY_VALUE_GENERIC_TYPE m) { synchronized(mutex) { map.putAll(m); } }
@Override @Override
public void putAll(Map<? extends CLASS_TYPE, ? extends CLASS_VALUE_TYPE> m) { synchronized(mutex) { map.putAll(m); } } public void putAll(Map<? extends CLASS_TYPE, ? extends CLASS_VALUE_TYPE> m) { synchronized(mutex) { map.putAll(m); } }
@Override
public void putAll(KEY_TYPE[] keys, VALUE_TYPE[] values, int offset, int size) { synchronized(mutex) { map.putAll(keys, values, offset, size); } }
#if !TYPE_OBJECT #if !TYPE_OBJECT
@Override @Override
public boolean containsKey(KEY_TYPE key) { synchronized(mutex) { return map.containsKey(key); } } public boolean containsKey(KEY_TYPE key) { synchronized(mutex) { return map.containsKey(key); } }
@@ -787,7 +811,9 @@ public class MAPS
@Override @Override
public VALUE_TYPE GET_VALUE(KEY_TYPE key) { synchronized(mutex) { return map.GET_VALUE(key); } } public VALUE_TYPE GET_VALUE(KEY_TYPE key) { synchronized(mutex) { return map.GET_VALUE(key); } }
@Override @Override
public VALUE_TYPE REMOVE_KEY(KEY_TYPE key) { synchronized(mutex) { return map.REMOVE_KEY(key); } } public VALUE_TYPE REMOVE_VALUE(KEY_TYPE key) { synchronized(mutex) { return map.REMOVE_VALUE(key); } }
@Override
public VALUE_TYPE REMOVE_VALUEOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { synchronized(mutex) { return map.REMOVE_VALUEOrDefault(key, defaultValue); } }
#if !TYPE_OBJECT || !VALUE_OBJECT #if !TYPE_OBJECT || !VALUE_OBJECT
@Override @Override
public boolean remove(KEY_TYPE key, VALUE_TYPE value) { synchronized(mutex) { return map.remove(key, value); } } public boolean remove(KEY_TYPE key, VALUE_TYPE value) { synchronized(mutex) { return map.remove(key, value); } }
@@ -797,6 +823,8 @@ public class MAPS
@Override @Override
public VALUE_TYPE replace(KEY_TYPE key, VALUE_TYPE value) { synchronized(mutex) { return map.replace(key, value); } } public VALUE_TYPE replace(KEY_TYPE key, VALUE_TYPE value) { synchronized(mutex) { return map.replace(key, value); } }
@Override @Override
public void REPLACE_VALUES(MAP KEY_VALUE_GENERIC_TYPE m) { synchronized(mutex) { map.REPLACE_VALUES(m); } }
@Override
public void REPLACE_VALUES(UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { synchronized(mutex) { map.REPLACE_VALUES(mappingFunction); } } public void REPLACE_VALUES(UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { synchronized(mutex) { map.REPLACE_VALUES(mappingFunction); } }
@Override @Override
public VALUE_TYPE COMPUTE(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { synchronized(mutex) { return map.COMPUTE(key, mappingFunction); } } public VALUE_TYPE COMPUTE(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { synchronized(mutex) { return map.COMPUTE(key, mappingFunction); } }
@@ -806,6 +834,8 @@ public class MAPS
public VALUE_TYPE COMPUTE_IF_PRESENT(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { synchronized(mutex) { return map.COMPUTE_IF_PRESENT(key, mappingFunction); } } public VALUE_TYPE COMPUTE_IF_PRESENT(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { synchronized(mutex) { return map.COMPUTE_IF_PRESENT(key, mappingFunction); } }
@Override @Override
public VALUE_TYPE MERGE(KEY_TYPE key, VALUE_TYPE value, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) { synchronized(mutex) { return map.MERGE(key, value, mappingFunction); } } public VALUE_TYPE MERGE(KEY_TYPE key, VALUE_TYPE value, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) { synchronized(mutex) { return map.MERGE(key, value, mappingFunction); } }
@Override
public void BULK_MERGE(MAP KEY_VALUE_GENERIC_TYPE m, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) { synchronized(mutex) { map.BULK_MERGE(m, mappingFunction); } }
#if !TYPE_OBJECT || !VALUE_OBJECT #if !TYPE_OBJECT || !VALUE_OBJECT
@Override @Override
public VALUE_TYPE getOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { synchronized(mutex) { return map.getOrDefault(key, defaultValue); } } public VALUE_TYPE getOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { synchronized(mutex) { return map.getOrDefault(key, defaultValue); } }
@@ -815,20 +845,22 @@ public class MAPS
@Override @Override
public int size() { synchronized(mutex) { return super.size(); } } public int size() { synchronized(mutex) { return super.size(); } }
@Override @Override
public MAP KEY_VALUE_GENERIC_TYPE copy() { throw new UnsupportedOperationException(); }
@Override
public SET KEY_GENERIC_TYPE keySet() { public SET KEY_GENERIC_TYPE keySet() {
if(keys == null) keys = SETS.synchronizedSet(map.keySet(), mutex); if(keys == null) keys = SETS.synchronize(map.keySet(), mutex);
return keys; return keys;
} }
@Override @Override
public VALUE_COLLECTION VALUE_GENERIC_TYPE values() { public VALUE_COLLECTION VALUE_GENERIC_TYPE values() {
if(values == null) values = VALUE_COLLECTIONS.synchronizedCollection(map.values(), mutex); if(values == null) values = VALUE_COLLECTIONS.synchronize(map.values(), mutex);
return values; return values;
} }
@Override @Override
public ObjectSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> ENTRY_SET() { public ObjectSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> ENTRY_SET() {
if(entrySet == null) entrySet = ObjectSets.synchronizedSet(map.ENTRY_SET(), mutex); if(entrySet == null) entrySet = ObjectSets.synchronize(map.ENTRY_SET(), mutex);
return entrySet; return entrySet;
} }
@@ -79,6 +79,26 @@ public class HashUtil
return x + 1L; return x + 1L;
} }
/**
* Function that finds out how many bits are required to store the number Provided
* @param value to get the required bits to store.
* @return the required bits to store that number
* @note Really useful for compression. Reducing data that is inserted into a GZIP algorithm.
*/
public static int getRequiredBits(int value) {
return Integer.bitCount(nextPowerOfTwo(value+1)-1);
}
/**
* Function that finds out how many bits are required to store the number Provided
* @param value to get the required bits to store.
* @return the required bits to store that number
* @note Really useful for compression. Reducing data that is inserted into a GZIP algorithm.
*/
public static int getRequiredBits(long value) {
return Long.bitCount(nextPowerOfTwo(value+1L)-1L);
}
/** /**
* Helper function that creates the ideal array size for HashMap * Helper function that creates the ideal array size for HashMap
* @param size the original array size * @param size the original array size
@@ -20,4 +20,18 @@ public interface ITrimmable
* @return if the internal array has been trimmed. * @return if the internal array has been trimmed.
*/ */
public boolean trim(int size); public boolean trim(int size);
/**
* Trims the collection down to the original size and clears all present elements with it.
*/
public default void clearAndTrim() {
clearAndTrim(0);
}
/**
* Trims the collection down to the requested size and clears all elements while doing so
* @param size the amount of elements that should be allowed
* @note this will enforce minimum size of the collection itself
*/
public void clearAndTrim(int size);
} }
@@ -72,8 +72,8 @@ public class SanityChecks
* @throws IllegalStateException if offset or accessSize is negative or the range goes out of the array-size * @throws IllegalStateException if offset or accessSize is negative or the range goes out of the array-size
*/ */
public static void checkArrayCapacity(int arraySize, int offset, int accessSize) { public static void checkArrayCapacity(int arraySize, int offset, int accessSize) {
if(offset < 0) throw new IllegalStateException("Offset is negative ("+offset+")"); if(offset < 0) throw new IndexOutOfBoundsException("Offset is negative ("+offset+")");
else if(accessSize < 0) throw new IllegalStateException("Size is negative ("+accessSize+")"); else if(accessSize < 0) throw new IllegalArgumentException("Size is negative ("+accessSize+")");
else if(arraySize < offset + accessSize) throw new IndexOutOfBoundsException("Index (" + (offset + accessSize) + ") is not in size (" + arraySize + ")"); else if(arraySize < offset + accessSize) throw new IndexOutOfBoundsException("Index (" + (offset + accessSize) + ") is not in size (" + arraySize + ")");
} }
@@ -29,6 +29,14 @@ public interface Stack<T>
*/ */
public int size(); public int size();
/**
* @return if the stack is empty
*/
public default boolean isEmpty() {
return size() == 0;
}
/** /**
* Clears the stack * Clears the stack
*/ */
@@ -33,7 +33,7 @@ public abstract class BaseInt2IntMapTest
Assert.assertEquals(1, putMap.put(513, 2)); Assert.assertEquals(1, putMap.put(513, 2));
Assert.assertEquals(PUT_ARRAY.length + 1, putMap.size()); Assert.assertEquals(PUT_ARRAY.length + 1, putMap.size());
Assert.assertEquals(512, putMap.addTo(0, 1)); Assert.assertEquals(512, putMap.addTo(0, 1));
Assert.assertEquals(513, putMap.getInt(0)); Assert.assertEquals(513, putMap.get(0));
} }
@Test @Test
@@ -70,13 +70,13 @@ public abstract class BaseInt2IntMapTest
if(!getValidMapTests().contains(MapTests.REPLACE)) return; if(!getValidMapTests().contains(MapTests.REPLACE)) return;
Int2IntMap map = createMap(TEST_ARRAY, TEST_ARRAY); Int2IntMap map = createMap(TEST_ARRAY, TEST_ARRAY);
Assert.assertEquals(0, map.replace(0, 512)); Assert.assertEquals(0, map.replace(0, 512));
Assert.assertEquals(512, map.getInt(0)); Assert.assertEquals(512, map.get(0));
Assert.assertTrue(map.replace(0, 512, 0)); Assert.assertTrue(map.replace(0, 512, 0));
Assert.assertFalse(map.replace(0, 512, 0)); Assert.assertFalse(map.replace(0, 512, 0));
map = createMap(TEST_ARRAY, TEST_ARRAY); map = createMap(TEST_ARRAY, TEST_ARRAY);
map.replaceInts((K, V) -> 99 - V); map.replaceInts((K, V) -> 99 - V);
Assert.assertEquals(99, map.getInt(0)); Assert.assertEquals(99, map.get(0));
Assert.assertEquals(0, map.getInt(99)); Assert.assertEquals(0, map.get(99));
} }
@Test @Test
@@ -85,7 +85,7 @@ public abstract class BaseInt2IntMapTest
if(!getValidMapTests().contains(MapTests.COMPUTE)) return; if(!getValidMapTests().contains(MapTests.COMPUTE)) return;
Int2IntMap map = createMap(TEST_ARRAY, TEST_ARRAY); Int2IntMap map = createMap(TEST_ARRAY, TEST_ARRAY);
Assert.assertEquals(512, map.computeInt(0, (K, V) -> 512)); Assert.assertEquals(512, map.computeInt(0, (K, V) -> 512));
Assert.assertEquals(512, map.getInt(0)); Assert.assertEquals(512, map.get(0));
Assert.assertEquals(512, map.computeIntIfAbsent(0, T -> 0)); Assert.assertEquals(512, map.computeIntIfAbsent(0, T -> 0));
Assert.assertEquals(0, map.computeIntIfPresent(0, (T, V) -> 0)); Assert.assertEquals(0, map.computeIntIfPresent(0, (T, V) -> 0));
Assert.assertEquals(0, map.computeIntIfAbsent(-10, T -> 0)); Assert.assertEquals(0, map.computeIntIfAbsent(-10, T -> 0));
@@ -107,7 +107,7 @@ public abstract class BaseInt2IntMapTest
Int2IntMap map = createMap(TEST_ARRAY, TEST_ARRAY); Int2IntMap map = createMap(TEST_ARRAY, TEST_ARRAY);
for(int i = 0;i<TEST_ARRAY.length;i++) for(int i = 0;i<TEST_ARRAY.length;i++)
{ {
Assert.assertEquals(i, map.getInt(i)); Assert.assertEquals(i, map.get(i));
} }
} }
@@ -131,10 +131,20 @@ public abstract class BaseInt2IntMapTest
{ {
if(!getValidMapTests().contains(MapTests.REMOVE)) return; if(!getValidMapTests().contains(MapTests.REMOVE)) return;
Int2IntMap map = createMap(PUT_VALUE_ARRAY, PUT_ARRAY); Int2IntMap map = createMap(PUT_VALUE_ARRAY, PUT_ARRAY);
Assert.assertEquals(PUT_ARRAY[50], map.remInt(PUT_VALUE_ARRAY[50])); Assert.assertEquals(PUT_ARRAY[50], map.remove(PUT_VALUE_ARRAY[50]));
Assert.assertTrue(map.remove(PUT_VALUE_ARRAY[51], PUT_ARRAY[51])); Assert.assertTrue(map.remove(PUT_VALUE_ARRAY[51], PUT_ARRAY[51]));
} }
@Test
public void testSort()
{
if(!getValidMapTests().contains(MapTests.COPY)) return;
Int2IntMap map = createMap(TEST_ARRAY, TEST_ARRAY);
Int2IntMap copy = map.copy();
Assert.assertFalse(map == copy);
Assert.assertEquals(map, copy);
}
public static class Strategy implements IntStrategy public static class Strategy implements IntStrategy
{ {
@Override @Override
@@ -62,11 +62,7 @@ public abstract class BaseInt2IntSortedMapTest extends BaseInt2IntMapTest
{ {
if(!getValidSortedMapTests().contains(SortedMapTests.FIRST)) return; if(!getValidSortedMapTests().contains(SortedMapTests.FIRST)) return;
Int2IntSortedMap map = createMap(TEST_ARRAY, TEST_ARRAY); Int2IntSortedMap map = createMap(TEST_ARRAY, TEST_ARRAY);
for(int i = 0;i<TEST_ARRAY.length;i++) Assert.assertEquals(map.pollFirstIntKey(), 0);
{
Assert.assertEquals(TEST_ARRAY[i], map.pollFirstIntKey());
}
Assert.assertEquals(0, map.size());
} }
@Test @Test
@@ -74,11 +70,7 @@ public abstract class BaseInt2IntSortedMapTest extends BaseInt2IntMapTest
{ {
if(!getValidSortedMapTests().contains(SortedMapTests.LAST)) return; if(!getValidSortedMapTests().contains(SortedMapTests.LAST)) return;
Int2IntSortedMap map = createMap(TEST_ARRAY, TEST_ARRAY); Int2IntSortedMap map = createMap(TEST_ARRAY, TEST_ARRAY);
for(int i = TEST_ARRAY.length-1;i>=0;i--) Assert.assertEquals(map.pollLastIntKey(), 99);
{
Assert.assertEquals(TEST_ARRAY[i], map.pollLastIntKey());
}
Assert.assertEquals(0, map.size());
} }
@Test @Test
@@ -87,8 +79,8 @@ public abstract class BaseInt2IntSortedMapTest extends BaseInt2IntMapTest
if(!getValidSortedMapTests().contains(SortedMapTests.SUB_MAP)) return; if(!getValidSortedMapTests().contains(SortedMapTests.SUB_MAP)) return;
Int2IntSortedMap map = createMap(TEST_ARRAY, TEST_ARRAY); Int2IntSortedMap map = createMap(TEST_ARRAY, TEST_ARRAY);
Int2IntSortedMap subMap = map.subMap(25, 75); Int2IntSortedMap subMap = map.subMap(25, 75);
Assert.assertEquals(50, subMap.remInt(50)); Assert.assertEquals(50, subMap.remove(50));
Assert.assertNotEquals(50, subMap.remInt(50)); Assert.assertNotEquals(50, subMap.remove(50));
Assert.assertFalse(subMap.containsKey(20)); Assert.assertFalse(subMap.containsKey(20));
Assert.assertFalse(subMap.containsKey(80)); Assert.assertFalse(subMap.containsKey(80));
} }
@@ -99,8 +91,8 @@ public abstract class BaseInt2IntSortedMapTest extends BaseInt2IntMapTest
if(!getValidSortedMapTests().contains(SortedMapTests.HEAD_MAP)) return; if(!getValidSortedMapTests().contains(SortedMapTests.HEAD_MAP)) return;
Int2IntSortedMap map = createMap(TEST_ARRAY, TEST_ARRAY); Int2IntSortedMap map = createMap(TEST_ARRAY, TEST_ARRAY);
Int2IntSortedMap subMap = map.headMap(75); Int2IntSortedMap subMap = map.headMap(75);
Assert.assertEquals(50, subMap.remInt(50)); Assert.assertEquals(50, subMap.remove(50));
Assert.assertNotEquals(50, subMap.remInt(50)); Assert.assertNotEquals(50, subMap.remove(50));
Assert.assertFalse(subMap.containsKey(80)); Assert.assertFalse(subMap.containsKey(80));
} }
@@ -110,8 +102,8 @@ public abstract class BaseInt2IntSortedMapTest extends BaseInt2IntMapTest
if(!getValidSortedMapTests().contains(SortedMapTests.TAIL_MAP)) return; if(!getValidSortedMapTests().contains(SortedMapTests.TAIL_MAP)) return;
Int2IntSortedMap map = createMap(TEST_ARRAY, TEST_ARRAY); Int2IntSortedMap map = createMap(TEST_ARRAY, TEST_ARRAY);
Int2IntSortedMap subMap = map.tailMap(25); Int2IntSortedMap subMap = map.tailMap(25);
Assert.assertEquals(50, subMap.remInt(50)); Assert.assertEquals(50, subMap.remove(50));
Assert.assertNotEquals(50, subMap.remInt(50)); Assert.assertNotEquals(50, subMap.remove(50));
Assert.assertFalse(subMap.containsKey(20)); Assert.assertFalse(subMap.containsKey(20));
} }
} }
@@ -2,6 +2,7 @@ package speiger.src.collections.ints.base;
import java.util.Arrays; import java.util.Arrays;
import java.util.EnumSet; import java.util.EnumSet;
import java.util.List;
import java.util.stream.IntStream; import java.util.stream.IntStream;
import org.junit.Assert; import org.junit.Assert;
@@ -12,6 +13,7 @@ import speiger.src.collections.ints.utils.IntArrays;
import speiger.src.collections.ints.utils.IntCollections; import speiger.src.collections.ints.utils.IntCollections;
import speiger.src.collections.ints.utils.IntCollections.SynchronizedCollection; import speiger.src.collections.ints.utils.IntCollections.SynchronizedCollection;
import speiger.src.collections.ints.utils.IntCollections.UnmodifiableCollection; import speiger.src.collections.ints.utils.IntCollections.UnmodifiableCollection;
import speiger.src.collections.objects.lists.ObjectArrayList;
import speiger.src.collections.tests.CollectionTest; import speiger.src.collections.tests.CollectionTest;
@SuppressWarnings("javadoc") @SuppressWarnings("javadoc")
@@ -47,6 +49,9 @@ public abstract class BaseIntCollectionTest extends BaseIntIterableTest
Assert.assertEquals(TEST_ARRAY.length, collection.size()); Assert.assertEquals(TEST_ARRAY.length, collection.size());
collection.addAll(create(BULK_ADD_ARRAY)); collection.addAll(create(BULK_ADD_ARRAY));
Assert.assertEquals(TEST_ARRAY.length + BULK_ADD_ARRAY.length, collection.size()); Assert.assertEquals(TEST_ARRAY.length + BULK_ADD_ARRAY.length, collection.size());
// Testing if adding via non Type Specific work like they should
List<Integer> wrapper = new ObjectArrayList<>(create(ADD_ARRAY));
Assert.assertNotNull(create(ADD_ARRAY).addAll(wrapper));
} }
@Test @Test
@@ -113,6 +118,14 @@ public abstract class BaseIntCollectionTest extends BaseIntIterableTest
Assert.assertTrue(collection.removeAll(Arrays.asList(IntArrays.wrap(CONTAINS_ARRAY)))); Assert.assertTrue(collection.removeAll(Arrays.asList(IntArrays.wrap(CONTAINS_ARRAY))));
} }
@Test
public void testRemoveAllListener() {
if(!getValidCollectionTests().contains(CollectionTest.REMOVE_ALL_LISTENER)) return;
IntCollection collection = create(TEST_ARRAY);
Assert.assertTrue(collection.removeAll(create(CONTAINS_ARRAY), T -> {}));
Assert.assertFalse(collection.removeAll(create(CONTAINS_ARRAY), T -> Assert.assertTrue(false)));
}
@Test @Test
public void testRetainAll() { public void testRetainAll() {
if(!getValidCollectionTests().contains(CollectionTest.RETAIN_ALL)) return; if(!getValidCollectionTests().contains(CollectionTest.RETAIN_ALL)) return;
@@ -130,6 +143,23 @@ public abstract class BaseIntCollectionTest extends BaseIntIterableTest
Assert.assertTrue(collection.isEmpty()); Assert.assertTrue(collection.isEmpty());
} }
@Test
public void testRetainAllListener() {
if(!getValidCollectionTests().contains(CollectionTest.RETAIN_ALL_LISTENER)) return;
IntCollection collection = create(TEST_ARRAY);
IntCollection retained = create(CONTAINS_ARRAY);
Assert.assertTrue(collection.retainAll(retained, T -> {}));
Assert.assertFalse(collection.retainAll(retained, T -> Assert.assertTrue(false)));
Assert.assertEquals(CONTAINS_ARRAY.length, collection.size());
int[] retainedArray = retained.toIntArray();
int[] collectionArray = collection.toIntArray();
IntArrays.stableSort(retainedArray);
IntArrays.stableSort(collectionArray);
Assert.assertArrayEquals(retainedArray, collectionArray);
collection.retainAll(IntCollections.EMPTY, T -> {});
Assert.assertTrue(collection.isEmpty());
}
@Test @Test
public void testToArray() { public void testToArray() {
if(!getValidCollectionTests().contains(CollectionTest.TO_ARRAY)) return; if(!getValidCollectionTests().contains(CollectionTest.TO_ARRAY)) return;
@@ -158,9 +188,28 @@ public abstract class BaseIntCollectionTest extends BaseIntIterableTest
public void testWrapper() { public void testWrapper() {
if(!getValidCollectionTests().contains(CollectionTest.WRAPPER)) return; if(!getValidCollectionTests().contains(CollectionTest.WRAPPER)) return;
IntCollection collection = create(TEST_ARRAY); IntCollection collection = create(TEST_ARRAY);
collection = IntCollections.synchronizedCollection(collection); collection = IntCollections.synchronize(collection);
Assert.assertTrue(collection instanceof SynchronizedCollection); Assert.assertTrue(collection instanceof SynchronizedCollection);
collection = IntCollections.unmodifiableCollection(collection); collection = IntCollections.unmodifiable(collection);
Assert.assertTrue(collection instanceof UnmodifiableCollection); Assert.assertTrue(collection instanceof UnmodifiableCollection);
} }
@Test
public void testToString() {
if(!getValidCollectionTests().contains(CollectionTest.TO_STRING)) return;
String base = Arrays.toString(BULK_ADD_ARRAY);
IntCollection collection = create(BULK_ADD_ARRAY);
Assert.assertEquals(base, collection.toString());
Assert.assertEquals(base, IntCollections.synchronize(collection).toString());
Assert.assertEquals(base, IntCollections.unmodifiable(collection).toString());
}
@Test
public void testCopy() {
if(!getValidCollectionTests().contains(CollectionTest.COPY)) return;
IntCollection collection = create(BULK_ADD_ARRAY);
IntCollection copy = collection.copy();
Assert.assertFalse(collection == copy);
Assert.assertEquals(collection, copy);
}
} }
@@ -1,5 +1,6 @@
package speiger.src.collections.ints.base; package speiger.src.collections.ints.base;
import java.util.Arrays;
import java.util.EnumSet; import java.util.EnumSet;
import java.util.stream.IntStream; import java.util.stream.IntStream;
@@ -8,6 +9,11 @@ import org.junit.Test;
import speiger.src.collections.ints.collections.IntIterable; import speiger.src.collections.ints.collections.IntIterable;
import speiger.src.collections.ints.collections.IntIterator; import speiger.src.collections.ints.collections.IntIterator;
import speiger.src.collections.ints.lists.IntArrayList;
import speiger.src.collections.ints.utils.IntArrays;
import speiger.src.collections.ints.utils.IntIterators;
import speiger.src.collections.objects.utils.ObjectArrays;
import speiger.src.collections.objects.utils.ObjectIterators;
import speiger.src.collections.tests.IterableTest; import speiger.src.collections.tests.IterableTest;
@SuppressWarnings("javadoc") @SuppressWarnings("javadoc")
@@ -15,6 +21,7 @@ public abstract class BaseIntIterableTest
{ {
protected static final int[] EMPTY_ARRAY = new int[0]; protected static final int[] EMPTY_ARRAY = new int[0];
protected static final int[] TEST_ARRAY = IntStream.range(0, 100).toArray(); protected static final int[] TEST_ARRAY = IntStream.range(0, 100).toArray();
protected static final int[] DISTINCT_ARRAY = IntStream.range(0, 100).flatMap(T -> Arrays.stream(new int[]{T, T})).toArray();
protected abstract IntIterable create(int[] data); protected abstract IntIterable create(int[] data);
@@ -65,4 +72,103 @@ public abstract class BaseIntIterableTest
} }
} }
} }
@Test
public void testStreamCount() {
if(getValidIterableTests().contains(IterableTest.STREAM_COUNT)) {
long expected = IntStream.of(TEST_ARRAY).filter(T -> T % 2 == 0).count();
int size = create(TEST_ARRAY).count(T -> T % 2 == 0);
Assert.assertEquals(expected, size);
}
}
@Test
public void testStreamFilter() {
if(getValidIterableTests().contains(IterableTest.STREAM_FILTER)) {
int[] expected = IntStream.of(TEST_ARRAY).filter(T -> T % 2 == 0).toArray();
int[] actual = IntIterators.pour(create(TEST_ARRAY).filter(T -> T % 2 == 0).iterator()).toIntArray();
IntArrays.stableSort(actual);
Assert.assertArrayEquals(expected, actual);
}
}
@Test
public void testStreamFindFirst() {
if(getValidIterableTests().contains(IterableTest.STREAM_FIND_FIRST)) {
int expected = IntStream.of(TEST_ARRAY).filter(T -> T / 50 > 0).findFirst().getAsInt();
int actual = create(TEST_ARRAY).findFirst(T -> T / 50 > 0);
Assert.assertEquals(expected, actual);
}
}
@Test
public void teastStreamDistinct() {
if(getValidIterableTests().contains(IterableTest.STREAM_DISTINCT)) {
int[] expected = IntStream.of(DISTINCT_ARRAY).distinct().toArray();
int[] actual = IntIterators.pour(create(DISTINCT_ARRAY).distinct().iterator()).toIntArray();
IntArrays.stableSort(actual);
Assert.assertArrayEquals(expected, actual);
}
}
@Test
public void testStreamLimit() {
if(getValidIterableTests().contains(IterableTest.STREAM_LIMIT)) {
int[] expected = IntStream.of(TEST_ARRAY).limit(25).toArray();
int[] actual = IntIterators.pour(create(TEST_ARRAY).limit(25).iterator()).toIntArray();
Assert.assertEquals(expected.length, actual.length);
}
}
@Test
public void testStreamMap() {
if(getValidIterableTests().contains(IterableTest.STREAM_MAP)) {
Integer[] expected = IntStream.of(TEST_ARRAY).mapToObj(Integer::new).toArray(Integer[]::new);
Integer[] actual = ObjectIterators.pour(create(TEST_ARRAY).map(Integer::new).iterator()).toArray(Integer[]::new);
ObjectArrays.stableSort(actual);
Assert.assertArrayEquals(expected, actual);
}
}
@Test
public void testStreamMatches() {
if(getValidIterableTests().contains(IterableTest.STREAM_MATCHES)) {
IntIterable iterable = create(TEST_ARRAY);
Assert.assertTrue(iterable.matchesAll(T -> T >= 0));
Assert.assertFalse(iterable.matchesAll(T -> T < 0));
Assert.assertTrue(iterable.matchesAny(T -> T % 2 != 0));
Assert.assertFalse(iterable.matchesAny(T -> T % 2 >= 2));
Assert.assertTrue(iterable.matchesNone(T -> T % 2 >= 2));
Assert.assertFalse(iterable.matchesNone(T -> T % 2 != 0));
}
}
@Test
public void testStreamPeek() {
if(getValidIterableTests().contains(IterableTest.STREAM_PEEK)) {
int[] peekCount = new int[2];
create(TEST_ARRAY).peek(T -> peekCount[0]++).forEach(T -> peekCount[1]++);
Assert.assertEquals(TEST_ARRAY.length, peekCount[0]);
Assert.assertEquals(TEST_ARRAY.length, peekCount[1]);
}
}
@Test
public void testStreamPour() {
if(getValidIterableTests().contains(IterableTest.STREAM_POUR)) {
int[] expected = TEST_ARRAY;
int[] actual = create(TEST_ARRAY).pour(new IntArrayList()).toIntArray();
IntArrays.stableSort(actual);
Assert.assertArrayEquals(expected, actual);
}
}
@Test
public void testStreamReduce() {
if(getValidIterableTests().contains(IterableTest.STREAM_REDUCE)) {
int expected = IntStream.of(TEST_ARRAY).reduce(0, Integer::sum);
int actual = create(TEST_ARRAY).reduce(0, Integer::sum);
Assert.assertEquals(expected, actual);
}
}
} }
@@ -42,7 +42,7 @@ public abstract class BaseIntListTest extends BaseIntCollectionTest
if(getValidListTests().contains(ListTest.ADD_INDEX_COLLECTION)) return; if(getValidListTests().contains(ListTest.ADD_INDEX_COLLECTION)) return;
IntList list = create(TEST_ARRAY); IntList list = create(TEST_ARRAY);
IntList adding = create(ADD_ARRAY); IntList adding = create(ADD_ARRAY);
list.addAll(0, IntCollections.unmodifiableCollection(adding)); list.addAll(0, IntCollections.unmodifiable(adding));
for(int i = 0;i<ADD_ARRAY.length;i++) Assert.assertEquals(ADD_ARRAY[i], list.getInt(i)); for(int i = 0;i<ADD_ARRAY.length;i++) Assert.assertEquals(ADD_ARRAY[i], list.getInt(i));
} }
@@ -64,6 +64,16 @@ public abstract class BaseIntListTest extends BaseIntCollectionTest
for(int i = 0;i<ADD_ARRAY.length;i++) Assert.assertEquals(ADD_ARRAY[i], list.getInt(i)); for(int i = 0;i<ADD_ARRAY.length;i++) Assert.assertEquals(ADD_ARRAY[i], list.getInt(i));
} }
@Test
public void testSpecialAdd() {
if(getValidListTests().contains(ListTest.ADD_SPECIAL)) return;
IntList list = create(TEST_ARRAY);
Assert.assertFalse(list.addIfAbsent(50));
Assert.assertTrue(list.addIfPresent(50));
Assert.assertTrue(list.addIfAbsent(150));
Assert.assertFalse(list.addIfAbsent(150));
}
@Test @Test
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public void testIndex() { public void testIndex() {
@@ -173,6 +183,17 @@ public abstract class BaseIntListTest extends BaseIntCollectionTest
} }
} }
@Test
public void testSwapRemove() {
if(getValidListTests().contains(ListTest.REMOVE_SWAP)) return;
IntList list = create(TEST_ARRAY);
Assert.assertEquals(TEST_ARRAY[50], list.swapRemove(50));
Assert.assertEquals(TEST_ARRAY[TEST_ARRAY.length-1], list.getInt(50));
list = create(TEST_ARRAY);
Assert.assertTrue(list.swapRemoveInt(50));
Assert.assertFalse(list.swapRemoveInt(50));
}
@Test @Test
public void testListIterator() { public void testListIterator() {
if(getValidListTests().contains(ListTest.LIST_ITERATOR)) return; if(getValidListTests().contains(ListTest.LIST_ITERATOR)) return;
@@ -26,14 +26,14 @@ public abstract class BaseIntPriorityQueueTest extends BaseIntIterableTest
if(getValidPriorityQueueTests().contains(PriorityQueueTest.IN_OUT)) { if(getValidPriorityQueueTests().contains(PriorityQueueTest.IN_OUT)) {
IntPriorityQueue queue = create(EMPTY_ARRAY); IntPriorityQueue queue = create(EMPTY_ARRAY);
for(int i = 0;i<100;i++) { for(int i = 0;i<100;i++) {
queue.enqueueInt(i); queue.enqueue(i);
} }
for(int i = 0;i<100;i++) { for(int i = 0;i<100;i++) {
Assert.assertEquals(i, queue.dequeueInt()); Assert.assertEquals(i, queue.dequeue());
} }
queue = create(TEST_ARRAY); queue = create(TEST_ARRAY);
for(int i = 0;i<100;i++) { for(int i = 0;i<100;i++) {
Assert.assertEquals(i, queue.dequeueInt()); Assert.assertEquals(i, queue.dequeue());
} }
} }
} }
@@ -43,17 +43,17 @@ public abstract class BaseIntPriorityQueueTest extends BaseIntIterableTest
if(getValidPriorityQueueTests().contains(PriorityQueueTest.PEEK)) { if(getValidPriorityQueueTests().contains(PriorityQueueTest.PEEK)) {
IntPriorityQueue queue = create(EMPTY_ARRAY); IntPriorityQueue queue = create(EMPTY_ARRAY);
for(int i = 0;i<100;i++) { for(int i = 0;i<100;i++) {
queue.enqueueInt(i); queue.enqueue(i);
} }
if(isUnsortedRead()) { if(isUnsortedRead()) {
for(int i = 0;i<100;i++) { for(int i = 0;i<100;i++) {
int value = queue.peekInt(i); int value = queue.peek(i);
Assert.assertTrue(value >= 0 && value < 100); Assert.assertTrue(value >= 0 && value < 100);
} }
} }
else { else {
for(int i = 0;i<100;i++) { for(int i = 0;i<100;i++) {
Assert.assertEquals(i, queue.peekInt(i)); Assert.assertEquals(i, queue.peek(i));
} }
} }
} }
@@ -64,20 +64,20 @@ public abstract class BaseIntPriorityQueueTest extends BaseIntIterableTest
if(getValidPriorityQueueTests().contains(PriorityQueueTest.REMOVE)) { if(getValidPriorityQueueTests().contains(PriorityQueueTest.REMOVE)) {
IntPriorityQueue queue = create(EMPTY_ARRAY); IntPriorityQueue queue = create(EMPTY_ARRAY);
for(int i = 0;i<100;i++) { for(int i = 0;i<100;i++) {
queue.enqueueInt(i); queue.enqueue(i);
} }
queue.removeInt(40); queue.removeFirst(40);
for(int i = 0;i<99;i++) { for(int i = 0;i<99;i++) {
if(i >= 40) Assert.assertEquals(i + 1, queue.dequeueInt()); if(i >= 40) Assert.assertEquals(i + 1, queue.dequeue());
else Assert.assertEquals(i, queue.dequeueInt()); else Assert.assertEquals(i, queue.dequeue());
} }
for(int i = 0;i<100;i++) { for(int i = 0;i<100;i++) {
queue.enqueueInt(i); queue.enqueue(i);
} }
queue.removeLastInt(40); queue.removeLast(40);
for(int i = 0;i<99;i++) { for(int i = 0;i<99;i++) {
if(i >= 40) Assert.assertEquals(i + 1, queue.dequeueInt()); if(i >= 40) Assert.assertEquals(i + 1, queue.dequeue());
else Assert.assertEquals(i, queue.dequeueInt()); else Assert.assertEquals(i, queue.dequeue());
} }
} }
} }
@@ -89,7 +89,7 @@ public abstract class BaseIntPriorityQueueTest extends BaseIntIterableTest
IntPriorityQueue queue = create(EMPTY_ARRAY); IntPriorityQueue queue = create(EMPTY_ARRAY);
if(isUnsortedRead()) { if(isUnsortedRead()) {
for(int i = 0;i<100;i++) { for(int i = 0;i<100;i++) {
queue.enqueueInt(i); queue.enqueue(i);
} }
int[] array = queue.toIntArray(); int[] array = queue.toIntArray();
IntArrays.stableSort(array); IntArrays.stableSort(array);
@@ -102,29 +102,31 @@ public abstract class BaseIntPriorityQueueTest extends BaseIntIterableTest
Assert.assertArrayEquals(array, nonData); Assert.assertArrayEquals(array, nonData);
} }
else { else {
Integer[] ref = IntArrays.wrap(TEST_ARRAY);
Integer[] shiftArray = new Integer[100];
int[] shiftPrimArray = new int[100]; int[] shiftPrimArray = new int[100];
for(int i = 0; i < 100; i++) { for(int i = 0; i < 100; i++) {
queue.enqueue(i); queue.enqueue(i);
shiftPrimArray[(i+80) % 100] = i; shiftPrimArray[(i+80) % 100] = i;
shiftArray[(i+80) % 100] = Integer.valueOf(i);
} }
Assert.assertArrayEquals(ref, queue.toArray());
Assert.assertArrayEquals(ref, queue.toArray(new Integer[100]));
Assert.assertArrayEquals(ref, queue.toArray(null));
Assert.assertArrayEquals(TEST_ARRAY, queue.toIntArray()); Assert.assertArrayEquals(TEST_ARRAY, queue.toIntArray());
Assert.assertArrayEquals(TEST_ARRAY, queue.toIntArray(new int[100])); Assert.assertArrayEquals(TEST_ARRAY, queue.toIntArray(new int[100]));
Assert.assertArrayEquals(TEST_ARRAY, queue.toIntArray(null)); Assert.assertArrayEquals(TEST_ARRAY, queue.toIntArray(null));
IntPriorityQueue other = create(queue.toIntArray()); IntPriorityQueue other = create(queue.toIntArray());
for(int i = 0;i<20;i++) { for(int i = 0;i<20;i++) {
other.dequeueInt(); other.dequeue();
other.enqueue(i); other.enqueue(i);
} }
Assert.assertArrayEquals(shiftPrimArray, other.toIntArray()); Assert.assertArrayEquals(shiftPrimArray, other.toIntArray());
Assert.assertArrayEquals(shiftPrimArray, other.toIntArray(new int[100])); Assert.assertArrayEquals(shiftPrimArray, other.toIntArray(new int[100]));
Assert.assertArrayEquals(shiftArray, other.toArray());
} }
} }
} }
@Test
public void testCopy() {
if(!getValidPriorityQueueTests().contains(PriorityQueueTest.COPY)) return;
IntPriorityQueue queue = create(TEST_ARRAY);
IntPriorityQueue copy = queue.copy();
Assert.assertFalse(queue == copy);
Assert.assertEquals(queue, copy);
}
} }
@@ -49,9 +49,15 @@ public abstract class BaseIntSortedSetTest extends BaseIntCollectionTest
public void pollTest() { public void pollTest() {
if(getValidSortedSetTests().contains(SortedSetTest.POLL)) { if(getValidSortedSetTests().contains(SortedSetTest.POLL)) {
IntSortedSet set = create(TEST_ARRAY); IntSortedSet set = create(TEST_ARRAY);
Assert.assertEquals(set.pollFirstInt(), 0); for(int i = 0;i<100;i++)
Assert.assertEquals(set.pollLastInt(), 99); {
Assert.assertEquals(i, set.pollFirstInt());
}
set = create(TEST_ARRAY);
for(int i = 99;i>=0;i--)
{
Assert.assertEquals(i, set.pollLastInt());
}
} }
} }
@@ -18,13 +18,13 @@ public interface IIntStackTests
public default void testPush() public default void testPush()
{ {
IntStack stacks = create(TEST_ARRAY); IntStack stacks = create(TEST_ARRAY);
stacks.pushInt(500); stacks.push(500);
Assert.assertEquals(500, stacks.topInt()); Assert.assertEquals(500, stacks.top());
} }
@Test @Test
public default void testPop() public default void testPop()
{ {
Assert.assertEquals(99, create(TEST_ARRAY).topInt()); Assert.assertEquals(99, create(TEST_ARRAY).top());
} }
} }
@@ -0,0 +1,44 @@
package speiger.src.collections.ints.lists;
import org.junit.Test;
import speiger.src.collections.ints.base.BaseIntListTest;
import speiger.src.collections.ints.base.BaseIntPriorityQueueTest;
import speiger.src.collections.ints.base.IIntStackTests;
import speiger.src.collections.ints.queues.IntPriorityQueue;
/**
* @author Speiger
*
*/
public class IntLinkedListTest extends BaseIntListTest implements IIntStackTests
{
@Override
public IntLinkedList create(int[] data) {
return new IntLinkedList(data);
}
@Test
@Override
public void testPush() {
IIntStackTests.super.testPush();
}
@Test
@Override
public void testPop() {
IIntStackTests.super.testPop();
}
/**
* @author Speiger
*/
public static class IntLinkedListQueueTest extends BaseIntPriorityQueueTest {
@Override
protected IntPriorityQueue create(int[] data) {
return new IntLinkedList(data);
}
}
}
@@ -6,6 +6,7 @@ import speiger.src.collections.ints.base.BaseIntCollectionTest;
import speiger.src.collections.ints.base.BaseIntSortedSetTest; import speiger.src.collections.ints.base.BaseIntSortedSetTest;
import speiger.src.collections.ints.collections.IntCollection; import speiger.src.collections.ints.collections.IntCollection;
import speiger.src.collections.ints.utils.IntStrategy; import speiger.src.collections.ints.utils.IntStrategy;
import speiger.src.collections.tests.CollectionTest;
import speiger.src.collections.tests.SortedSetTest; import speiger.src.collections.tests.SortedSetTest;
@SuppressWarnings("javadoc") @SuppressWarnings("javadoc")
@@ -21,6 +22,14 @@ public class IntHashSetTests
{ {
@Override @Override
protected IntCollection create(int[] data) { return new IntOpenHashSet(data); } protected IntCollection create(int[] data) { return new IntOpenHashSet(data); }
@Override
protected EnumSet<CollectionTest> getValidCollectionTests()
{
EnumSet<CollectionTest> tests = super.getValidCollectionTests();
tests.remove(CollectionTest.TO_STRING);
return tests;
}
} }
public static class IntLinkedOpenHashSetTests extends BaseIntOpenHashSetTests public static class IntLinkedOpenHashSetTests extends BaseIntOpenHashSetTests
@@ -33,6 +42,14 @@ public class IntHashSetTests
{ {
@Override @Override
protected IntCollection create(int[] data) { return new IntOpenCustomHashSet(data, new DefaultStrategy()); } protected IntCollection create(int[] data) { return new IntOpenCustomHashSet(data, new DefaultStrategy()); }
@Override
protected EnumSet<CollectionTest> getValidCollectionTests()
{
EnumSet<CollectionTest> tests = super.getValidCollectionTests();
tests.remove(CollectionTest.TO_STRING);
return tests;
}
} }
public static class IntLinkedOpenCustomHashSetTests extends BaseIntOpenHashSetTests public static class IntLinkedOpenCustomHashSetTests extends BaseIntOpenHashSetTests
@@ -22,6 +22,13 @@ public class ObjectArrayListTest
testCastable(ObjectArrayList.wrap("Test", "Testing", "Testing stuff"), true); testCastable(ObjectArrayList.wrap("Test", "Testing", "Testing stuff"), true);
} }
@Test
public void testEmptyCreation()
{
ObjectArrayList<String> test = ObjectArrayList.of(String.class);
Assert.assertTrue(test.isCastable());
}
public <T> void testCastable(IObjectArray<T> castable, boolean result) public <T> void testCastable(IObjectArray<T> castable, boolean result)
{ {
Assert.assertTrue(castable.isCastable() == result); Assert.assertTrue(castable.isCastable() == result);
@@ -0,0 +1,46 @@
package speiger.src.collections.objects.list;
import java.util.List;
import java.util.function.Function;
import com.google.common.collect.testing.ListTestSuiteBuilder;
import com.google.common.collect.testing.TestStringListGenerator;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.ListFeature;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import speiger.src.collections.objects.lists.ImmutableObjectList;
import speiger.src.collections.objects.lists.ObjectArrayList;
import speiger.src.collections.objects.lists.ObjectLinkedList;
@SuppressWarnings("javadoc")
public class ObjectListTests extends TestCase
{
public static Test suite()
{
TestSuite suite = new TestSuite("Lists");
suite.addTest(suite("ArrayList", T -> new ObjectArrayList<>(T)));
suite.addTest(suite("LinkedList", T -> new ObjectLinkedList<>(T)));
suite.addTest(immutableSuite("ImmutableList", T -> new ImmutableObjectList<>(T)));
return suite;
}
public static Test suite(String name, Function<String[], List<String>> factory)
{
return ListTestSuiteBuilder.using(new TestStringListGenerator() {
@Override
protected List<String> create(String[] elements) { return factory.apply(elements); }
}).named(name).withFeatures(ListFeature.GENERAL_PURPOSE, CollectionFeature.ALLOWS_NULL_VALUES, CollectionSize.ANY).createTestSuite();
}
public static Test immutableSuite(String name, Function<String[], List<String>> factory)
{
return ListTestSuiteBuilder.using(new TestStringListGenerator() {
@Override
protected List<String> create(String[] elements) { return factory.apply(elements); }
}).named(name).withFeatures(CollectionFeature.ALLOWS_NULL_VALUES, CollectionSize.ANY).createTestSuite();
}
}
@@ -0,0 +1,115 @@
package speiger.src.collections.objects.map;
import java.util.Comparator;
import java.util.Map;
import java.util.Objects;
import java.util.function.BiFunction;
import java.util.function.Supplier;
import com.google.common.collect.testing.AnEnum;
import com.google.common.collect.testing.MapTestSuiteBuilder;
import com.google.common.collect.testing.TestEnumMapGenerator;
import com.google.common.collect.testing.TestStringMapGenerator;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import speiger.src.collections.objects.maps.impl.customHash.Object2ObjectLinkedOpenCustomHashMap;
import speiger.src.collections.objects.maps.impl.customHash.Object2ObjectOpenCustomHashMap;
import speiger.src.collections.objects.maps.impl.hash.Object2ObjectLinkedOpenHashMap;
import speiger.src.collections.objects.maps.impl.hash.Object2ObjectOpenHashMap;
import speiger.src.collections.objects.maps.impl.immutable.ImmutableObject2ObjectOpenHashMap;
import speiger.src.collections.objects.maps.impl.misc.Enum2ObjectMap;
import speiger.src.collections.objects.maps.impl.misc.LinkedEnum2ObjectMap;
import speiger.src.collections.objects.maps.impl.misc.Object2ObjectArrayMap;
import speiger.src.collections.objects.maps.impl.tree.Object2ObjectAVLTreeMap;
import speiger.src.collections.objects.maps.impl.tree.Object2ObjectRBTreeMap;
import speiger.src.collections.objects.utils.ObjectStrategy;
@SuppressWarnings("javadoc")
public class ObjectMapTests extends TestCase
{
public static Test suite()
{
TestSuite suite = new TestSuite("Maps");
suite.addTest(suite("HashMap", Object2ObjectOpenHashMap::new, true));
suite.addTest(suite("LinkedHashMap", Object2ObjectLinkedOpenHashMap::new, true));
suite.addTest(suite("CustomHashMap", () -> new Object2ObjectOpenCustomHashMap<>(Strategy.INSTANCE), true));
suite.addTest(suite("LinkedCustomHashMap", () -> new Object2ObjectLinkedOpenCustomHashMap<>(Strategy.INSTANCE), true));
suite.addTest(suite("RBTreeMap_NonNull", Object2ObjectRBTreeMap::new, false));
suite.addTest(suite("AVLTreeMap_NonNull", Object2ObjectAVLTreeMap::new, false));
suite.addTest(suite("RBTreeMap_Null", () -> new Object2ObjectRBTreeMap<String, String>(Comparator.nullsFirst(Comparator.naturalOrder())), true));
suite.addTest(suite("AVLTreeMap_Null", () -> new Object2ObjectAVLTreeMap<String, String>(Comparator.nullsFirst(Comparator.naturalOrder())), true));
suite.addTest(immutableSuit("ImmutableMap", ImmutableObject2ObjectOpenHashMap::new));
suite.addTest(suite("ArrayMap", Object2ObjectArrayMap::new, true));
suite.addTest(enumSuite("EnumMap", () -> new Enum2ObjectMap<>(AnEnum.class)));
suite.addTest(enumSuite("LinkedEnumMap", () -> new LinkedEnum2ObjectMap<>(AnEnum.class)));
return suite;
}
public static Test suite(String name, Supplier<Map<String, String>> factory, boolean allowNull)
{
MapTestSuiteBuilder<String, String> builder = MapTestSuiteBuilder.using(new TestStringMapGenerator() {
@Override
protected Map<String, String> create(Map.Entry<String, String>[] entries) {
Map<String, String> map = factory.get();
for(Map.Entry<String, String> entry : entries) {
map.put(entry.getKey(), entry.getValue());
}
return map;
}
}).named(name).withFeatures(CollectionSize.ANY, MapFeature.GENERAL_PURPOSE, MapFeature.ALLOWS_NULL_VALUES, CollectionFeature.SUPPORTS_ITERATOR_REMOVE);
if(allowNull) builder.withFeatures(MapFeature.ALLOWS_NULL_KEYS, MapFeature.ALLOWS_ANY_NULL_QUERIES);
return builder.createTestSuite();
}
public static Test immutableSuit(String name, BiFunction<String[], String[], Map<String, String>> factory) {
MapTestSuiteBuilder<String, String> builder = MapTestSuiteBuilder.using(new TestStringMapGenerator() {
@Override
protected Map<String, String> create(Map.Entry<String, String>[] entries) {
String[] keys = new String[entries.length];
String[] values = new String[entries.length];
for(int i = 0;i<entries.length;i++) {
keys[i] = entries[i].getKey();
values[i] = entries[i].getValue();
}
return factory.apply(keys, values);
}
}).named(name).withFeatures(CollectionSize.ANY, MapFeature.ALLOWS_NULL_KEYS, MapFeature.ALLOWS_NULL_VALUES, MapFeature.ALLOWS_ANY_NULL_QUERIES);
return builder.createTestSuite();
}
public static Test enumSuite(String name, Supplier<Map<AnEnum, String>> factory)
{
MapTestSuiteBuilder<AnEnum, String> builder = MapTestSuiteBuilder.using(new TestEnumMapGenerator() {
@Override
protected Map<AnEnum, String> create(Map.Entry<AnEnum, String>[] entries) {
Map<AnEnum, String> map = factory.get();
for(Map.Entry<AnEnum, String> entry : entries) {
map.put(entry.getKey(), entry.getValue());
}
return map;
}
}).named(name).withFeatures(CollectionSize.ANY, MapFeature.GENERAL_PURPOSE, MapFeature.ALLOWS_NULL_VALUES, CollectionFeature.SUPPORTS_ITERATOR_REMOVE);
return builder.createTestSuite();
}
private static class Strategy implements ObjectStrategy<String>
{
static final Strategy INSTANCE = new Strategy();
@Override
public int hashCode(String o) {
return Objects.hashCode(o);
}
@Override
public boolean equals(String key, String value) {
return Objects.equals(key, value);
}
}
}
@@ -0,0 +1,80 @@
package speiger.src.collections.objects.set;
import java.util.Comparator;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import com.google.common.collect.testing.SetTestSuiteBuilder;
import com.google.common.collect.testing.TestStringSetGenerator;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.SetFeature;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import speiger.src.collections.objects.sets.ImmutableObjectOpenHashSet;
import speiger.src.collections.objects.sets.ObjectAVLTreeSet;
import speiger.src.collections.objects.sets.ObjectArraySet;
import speiger.src.collections.objects.sets.ObjectLinkedOpenCustomHashSet;
import speiger.src.collections.objects.sets.ObjectLinkedOpenHashSet;
import speiger.src.collections.objects.sets.ObjectOpenCustomHashSet;
import speiger.src.collections.objects.sets.ObjectOpenHashSet;
import speiger.src.collections.objects.sets.ObjectRBTreeSet;
import speiger.src.collections.objects.utils.ObjectStrategy;
@SuppressWarnings("javadoc")
public class ObjectSetTests extends TestCase
{
public static Test suite()
{
TestSuite suite = new TestSuite("Sets");
suite.addTest(suite("HashSet", ObjectOpenHashSet::new, true));
suite.addTest(suite("LinkedHashSet", ObjectLinkedOpenHashSet::new, true));
suite.addTest(suite("CustomHashSet", T -> new ObjectOpenCustomHashSet<>(T, Strategy.INSTANCE), true));
suite.addTest(suite("LinkedCustomHashSet", T -> new ObjectLinkedOpenCustomHashSet<>(T, Strategy.INSTANCE), true));
suite.addTest(immutableSuite("ImmutableHashSet", ImmutableObjectOpenHashSet::new));
suite.addTest(suite("ArraySet", ObjectArraySet::new, true));
suite.addTest(suite("RBTreeSet_NonNull", ObjectRBTreeSet::new, false));
suite.addTest(suite("AVLTreeSet_NonNull", ObjectAVLTreeSet::new, false));
suite.addTest(suite("RBTreeSet_Null", T -> new ObjectRBTreeSet<>(T, Comparator.nullsFirst(Comparator.naturalOrder())), true));
suite.addTest(suite("AVLTreeSet_Null", T -> new ObjectAVLTreeSet<>(T, Comparator.nullsFirst(Comparator.naturalOrder())), true));
return suite;
}
public static Test suite(String name, Function<String[], Set<String>> factory, boolean allowNull)
{
SetTestSuiteBuilder<String> generator = SetTestSuiteBuilder.using(new TestStringSetGenerator() {
@Override
protected Set<String> create(String[] elements) { return factory.apply(elements); }
}).named(name).withFeatures(CollectionSize.ANY, SetFeature.GENERAL_PURPOSE);
if(allowNull) generator.withFeatures(CollectionFeature.ALLOWS_NULL_VALUES);
return generator.createTestSuite();
}
public static Test immutableSuite(String name, Function<String[], Set<String>> factory)
{
return SetTestSuiteBuilder.using(new TestStringSetGenerator() {
@Override
protected Set<String> create(String[] elements) { return factory.apply(elements); }
}).named(name).withFeatures(CollectionSize.ANY, CollectionFeature.ALLOWS_NULL_VALUES).createTestSuite();
}
private static class Strategy implements ObjectStrategy<String>
{
static final Strategy INSTANCE = new Strategy();
@Override
public int hashCode(String o) {
return Objects.hashCode(o);
}
@Override
public boolean equals(String key, String value) {
return Objects.equals(key, value);
}
}
}
@@ -0,0 +1,134 @@
package speiger.src.collections.objects.utils;
import java.io.BufferedReader;
import java.io.File;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import speiger.src.collections.objects.lists.ObjectArrayList;
import speiger.src.collections.objects.lists.ObjectLinkedList;
import speiger.src.collections.objects.lists.ObjectList;
@SuppressWarnings("javadoc")
public class StringSortTest
{
public static final String[] NAMES = loadNames();
private static final String[] loadNames()
{
List<String> list = new ArrayList<>();
try(BufferedReader reader = Files.newBufferedReader(new File("src/test/resources/testAssets/strings/names.txt").toPath()))
{
reader.lines().forEach(list::add);
}
catch(Exception e)
{
e.printStackTrace();
}
list.sort(null);
return list.toArray(new String[list.size()]);
}
@Test
public void testArrayListSort() {
ObjectList<String> list = new ObjectArrayList<>(NAMES.clone());
ObjectLists.shuffle(list);
Assert.assertFalse(Arrays.equals(list.toArray(new String[list.size()]), NAMES));
list.sort(String::compareTo);
Assert.assertTrue(Arrays.equals(list.toArray(new String[list.size()]), NAMES));
ObjectLists.shuffle(list);
Assert.assertFalse(Arrays.equals(list.toArray(new String[list.size()]), NAMES));
list.sort(null);
Assert.assertTrue(Arrays.equals(list.toArray(new String[list.size()]), NAMES));
}
@Test
public void testLinkedListSort() {
ObjectList<String> list = new ObjectLinkedList<>(NAMES.clone());
ObjectLists.shuffle(list);
Assert.assertFalse(Arrays.equals(list.toArray(new String[list.size()]), NAMES));
list.sort(String::compareTo);
Assert.assertTrue(Arrays.equals(list.toArray(new String[list.size()]), NAMES));
ObjectLists.shuffle(list);
Assert.assertFalse(Arrays.equals(list.toArray(new String[list.size()]), NAMES));
list.sort(null);
Assert.assertTrue(Arrays.equals(list.toArray(new String[list.size()]), NAMES));
}
@Test
public void testInsertionSort() {
String[] array = ObjectArrays.shuffle(NAMES.clone());
Assert.assertFalse(Arrays.equals(array, NAMES));
ObjectArrays.insertionSort(array);
Assert.assertArrayEquals(NAMES, array);
ObjectArrays.shuffle(array);
Assert.assertFalse(Arrays.equals(array, NAMES));
ObjectArrays.insertionSort(array, String::compareTo);
Assert.assertArrayEquals(NAMES, array);
}
@Test
public void testMergeSort() {
String[] array = ObjectArrays.shuffle(NAMES.clone());
Assert.assertFalse(Arrays.equals(array, NAMES));
ObjectArrays.mergeSort(array);
Assert.assertArrayEquals(NAMES, array);
ObjectArrays.shuffle(array);
Assert.assertFalse(Arrays.equals(array, NAMES));
ObjectArrays.mergeSort(array, String::compareTo);
Assert.assertArrayEquals(NAMES, array);
}
@Test
public void testSelectionSortSort() {
String[] array = ObjectArrays.shuffle(NAMES.clone());
Assert.assertFalse(Arrays.equals(array, NAMES));
ObjectArrays.selectionSort(array);
Assert.assertArrayEquals(NAMES, array);
ObjectArrays.shuffle(array);
Assert.assertFalse(Arrays.equals(array, NAMES));
ObjectArrays.selectionSort(array, String::compareTo);
Assert.assertArrayEquals(NAMES, array);
}
@Test
public void testQuickSortSort() {
String[] array = ObjectArrays.shuffle(NAMES.clone());
Assert.assertFalse(Arrays.equals(array, NAMES));
ObjectArrays.quickSort(array);
Assert.assertArrayEquals(NAMES, array);
ObjectArrays.shuffle(array);
Assert.assertFalse(Arrays.equals(array, NAMES));
ObjectArrays.quickSort(array, String::compareTo);
Assert.assertArrayEquals(NAMES, array);
}
@Test
public void testParallelMergeSort() {
String[] array = ObjectArrays.shuffle(NAMES.clone());
Assert.assertFalse(Arrays.equals(array, NAMES));
ObjectArrays.parallelMergeSort(array);
Assert.assertArrayEquals(NAMES, array);
ObjectArrays.shuffle(array);
Assert.assertFalse(Arrays.equals(array, NAMES));
ObjectArrays.parallelMergeSort(array, String::compareTo);
Assert.assertArrayEquals(NAMES, array);
}
@Test
public void testParallelQuickSort() {
String[] array = ObjectArrays.shuffle(NAMES.clone());
Assert.assertFalse(Arrays.equals(array, NAMES));
ObjectArrays.parallelQuickSort(array);
Assert.assertArrayEquals(NAMES, array);
ObjectArrays.shuffle(array);
Assert.assertFalse(Arrays.equals(array, NAMES));
ObjectArrays.parallelQuickSort(array, String::compareTo);
Assert.assertArrayEquals(NAMES, array);
}
}
@@ -11,8 +11,12 @@ public enum CollectionTest
REMOVE, REMOVE,
REMOVE_IF, REMOVE_IF,
REMOVE_ALL, REMOVE_ALL,
REMOVE_ALL_LISTENER,
RETAIN_ALL, RETAIN_ALL,
RETAIN_ALL_LISTENER,
TO_ARRAY, TO_ARRAY,
CLEAR, CLEAR,
WRAPPER; WRAPPER,
TO_STRING,
COPY;
} }
@@ -7,5 +7,15 @@ public enum IterableTest
ITERATOR_FOR_EACH, ITERATOR_FOR_EACH,
ITERATOR_LOOP, ITERATOR_LOOP,
ITERATOR_REMOVAL, ITERATOR_REMOVAL,
ITERATOR_SKIP; ITERATOR_SKIP,
STREAM_COUNT,
STREAM_FILTER,
STREAM_FIND_FIRST,
STREAM_DISTINCT,
STREAM_LIMIT,
STREAM_MAP,
STREAM_MATCHES,
STREAM_PEEK,
STREAM_POUR,
STREAM_REDUCE;
} }
@@ -8,6 +8,7 @@ public enum ListTest
ADD_INDEX_COLLECTION, ADD_INDEX_COLLECTION,
ADD_INDEX_LIST, ADD_INDEX_LIST,
ADD_ELEMENTS, ADD_ELEMENTS,
ADD_SPECIAL,
INDEX, INDEX,
LAST_INDEX, LAST_INDEX,
GET, GET,
@@ -17,6 +18,7 @@ public enum ListTest
SORT, SORT,
REPLACE, REPLACE,
REMOVE, REMOVE,
REMOVE_SWAP,
REMOVE_ELEMENTS, REMOVE_ELEMENTS,
EXTRACT_ELEMENTS, EXTRACT_ELEMENTS,
LIST_ITERATOR, LIST_ITERATOR,
@@ -11,5 +11,6 @@ public enum MapTests
MERGE, MERGE,
GET, GET,
ITERATORS, ITERATORS,
REMOVE; REMOVE,
COPY;
} }
@@ -7,4 +7,5 @@ public enum PriorityQueueTest
PEEK, PEEK,
REMOVE, REMOVE,
TO_ARRAY, TO_ARRAY,
COPY;
} }
File diff suppressed because it is too large Load Diff