190 Commits
Author SHA1 Message Date
Speiger 26b9d6706d Fixed Classification 2022-04-14 09:34:16 +02:00
Speiger a21d4a9eb6 Fixing Jitpack Publishing 2022-04-14 09:24:13 +02:00
Speiger 212d614ebd Trying switching Jitpack Java version. 2022-04-14 09:19:27 +02:00
Speiger bcba3ccde0 Another try 2022-04-14 09:13:53 +02:00
Speiger b42ad76372 Jitpack Test 2022-04-14 09:12:03 +02:00
Speiger f95565771a 0.6.0 Release Commit 2022-04-14 07:56:39 +02:00
Speiger 3d6cbf5ac1 Finishing touches for the 0.6.0 release. 2022-04-14 07:29:32 +02:00
Speiger fc5d43e14b Updated Changelog. 2022-04-14 06:06:35 +02:00
Speiger b3264748cd Added Author to module Info. 2022-04-14 05:47:19 +02:00
Speiger ede40f06d0 Small fixes.
-Fixed: Some imports.
-Fixed: containsValue for OpenHashMap was not checking nullEntry properly
2022-04-14 05:37:41 +02:00
Speiger e69c675f82 Fixed bug with linux & cleanup of the java version detector 2022-04-13 02:58:35 +02:00
Speiger 17c1c90957 Added Module-Info support 2022-04-13 02:54:03 +02:00
Speiger c6f2f71f6c Switching to a new lock to make read operations actually concurrent. 2022-04-13 02:00:52 +02:00
Speiger d2c7c151bc Implemented tests.
-Added: ConcurrentHashMap test suite
-Fixed: Bugs found in ConcurrentHashMaps with the iterator and clear function.
2022-04-12 08:08:17 +02:00
Speiger 4448eca787 Finishing ConcurrentHashMap implementation, next tests 2022-04-12 06:06:18 +02:00
Speiger 0350a77dff Finishing the ConcurrentMap implementation
This though isn't finishing the rest because the interface still needs
to be implemented.
-Added: Rest of the ConcurrentMap implementation
-Fixed: LinkedOpenHashMap Count method was returning prematurely.
2022-04-11 03:20:28 +02:00
Speiger 4f98c599df New Features.
-Added: ArrayList.of(CLASS, size) function that allows to preallocate
the size of the generic list.
-Updated: ListTests suppressors only suprres what they need to.
-Added: Start of the ConcurrentHashMap implementation (based on Guavas
implementation)

Note that the ConcurrentHashMap implementation is just started not
finished and still needs a lot of work, but the base code - any
subclasses is technically finished.
The implementation is also using linkedMaps to have faster iteration
performance.
2022-04-10 15:49:16 +02:00
Speiger 103b2407d2 Updated Changelog 2022-04-09 04:23:57 +02:00
Speiger 059da9be12 New Features
-Added: CopyOnWriteArrayList
-Added: UnitTests for CopyOnWriteArrayLists
2022-04-09 03:56:54 +02:00
Speiger 3cac3a997e And hopefully the last javaDoc fixes 2022-04-08 00:24:37 +02:00
Speiger 3ffb001c73 More fixes
-Fixed: More javadoc fixes
-Fixed: BaseIntIterableTest no longer uses a deprecated function
2022-04-08 00:13:51 +02:00
Speiger 2810a6f952 Small fixes
-Fixed: JavaDoc
-Changed: callback is now called onCompletion
2022-04-08 00:00:45 +02:00
Speiger 166362334b Added gradle now uses the java version it runs on. 2022-04-07 20:26:53 +02:00
Speiger d3f9103ebf Adding Logger for testings 2022-04-07 20:19:47 +02:00
Speiger 1c5507d4a5 Switching to local properties 2022-04-07 20:16:59 +02:00
Speiger 5e3cd9f484 Trying out something with github actions 2022-04-07 20:14:23 +02:00
Speiger f27b884b6a Moving to a more up to date system.
-Changed: Moved to gradle 7.3 for java17 support of the project.
-Changed: Moved to maven-publish plugin and added a bit more info to the poms.
2022-04-07 16:00:58 +02:00
Speiger 769a9d8ea5 Upgraded gradle version to 6.3 for a test 2022-04-07 13:32:04 +02:00
Speiger 9499a7f0e0 Setup matrix so multiple java versions are tested. 2022-04-07 13:27:12 +02:00
Speiger ca38583f96 Fixed Java11 Incompat 2022-04-07 00:14:09 +02:00
Speiger 9557a0cfb5 Merge branch 'master' of git@github.com:Speiger/Primitive-Collections.git 2022-04-07 00:08:05 +02:00
Speiger c61e8bb7fc New Features
- Added: addOrGet for sets.
- Added: Async API which allows to easily execute Iterables/Collections
offthread without the complexity.
2022-04-07 00:06:49 +02:00
SpeigerandSpeiger 4fbcaa47f8 Update README.md 2022-04-07 00:06:19 +02:00
Speiger 6f31fc5abb New Features
- Added: addOrGet for sets.
- Added: Async API which allows to easily execute Iterables/Collections
offthread without the complexity.
2022-04-07 00:04:52 +02:00
SpeigerandGitHub 10ec0e35d0 Update README.md 2021-12-27 21:29:51 +01:00
Speiger 29c4d253cf Disabling badge 2021-12-27 21:28:07 +01:00
Speiger 55c870d392 Adding Build Passing badge 2021-12-27 21:22:57 +01:00
SpeigerandGitHub cda6ec066d Adding Build Validation
Create gradle.yml
2021-12-27 20:38:55 +01:00
Speiger c8b89e6847 Renaming file for what the action did. 2021-12-27 20:34:15 +01:00
Speiger b46a739008 Finishing Build Action 2021-12-27 20:28:45 +01:00
Speiger af62394651 Testing for secrets to be present 2021-12-27 20:04:50 +01:00
SpeigerandGitHub bc75a5cd97 Merge pull request #8 from Speiger/master
Moving Credentials Away from this file because now i need it
2021-12-27 20:00:58 +01:00
Speiger 7d8af3af08 Moving Credentials Away from this file because now i need it 2021-12-27 19:59:19 +01:00
SpeigerandGitHub ef8197b275 Update gradle.yml 2021-12-27 19:24:16 +01:00
SpeigerandGitHub 58d9ac7fdd Update gradle.yml 2021-12-27 19:21:59 +01:00
SpeigerandGitHub 86a893916d Update gradle.yml 2021-12-27 19:20:06 +01:00
SpeigerandGitHub e7a6292fe9 Update gradle.yml 2021-12-27 19:10:09 +01:00
SpeigerandGitHub 81209b0cf8 Update gradle.yml 2021-12-27 19:07:05 +01:00
SpeigerandGitHub 77b8147f9b Update gradle.yml 2021-12-27 19:05:33 +01:00
SpeigerandGitHub 32abd7e14e Update gradle.yml 2021-12-27 19:04:33 +01:00
SpeigerandGitHub 8a582f0b08 Create gradle.yml 2021-12-27 19:01:45 +01:00
SpeigerandGitHub 01be6f7d43 Delete gradle.yml 2021-12-27 18:56:49 +01:00
SpeigerandGitHub 9011700879 testing build only 2021-12-27 18:55:51 +01:00
SpeigerandGitHub 12cd4e5e5f Update gradle.yml 2021-12-27 18:50:24 +01:00
SpeigerandGitHub 10201bcadb hopefully this works 2021-12-27 18:44:47 +01:00
SpeigerandGitHub 3b4fcc0069 Merge pull request #6 from Speiger/actions
Update gradle.yml
2021-12-27 18:32:51 +01:00
SpeigerandGitHub 31a1ef74fb Update gradle.yml 2021-12-27 18:32:23 +01:00
SpeigerandGitHub 9be3a1475f another build try 2021-12-27 18:29:54 +01:00
SpeigerandGitHub 7591f396fd getting into github actions
Adding a build test
2021-12-27 18:18:24 +01:00
Speiger 517b84042f Version Bump 2021-12-26 01:58:22 +01:00
Speiger dbfae33074 Fixed Bug with FIFOQueue performance 2021-12-26 00:08:19 +01:00
Speiger ead34009c6 Added pourAsList and pourAsSet 2021-12-25 20:27:33 +01:00
Speiger 7a4a0f05d1 Added subFrom (which is the inverse of addTo) 2021-12-25 20:07:37 +01:00
Speiger 8f32b2d887 Merge remote-tracking branch 'Github/master' 2021-12-25 03:49:45 +01:00
Speiger e6c9600b40 Refactoring and Deprecating SortedMap/Sets
- Added: OrderedMap/Set
- Added: All Relevant functions into Ordered interface
- Changed: Marked all Relevant SortedMap/Set functions Deprecated until
0.6.0
- Fixed: All code that was relevant to this
2021-12-25 03:46:51 +01:00
SpeigerandGitHub d5f2acb9ab Update LICENSE 2021-12-19 21:19:28 +01:00
Speiger 3274e96355 Added Benchmark links 2021-12-16 14:03:39 +01:00
Speiger 78dfa286b0 New Version
- Fixed: Bugs with Queues starting with the wrong size
- Fixed: ArrayGrowth for Queues was +1 instead of +50%
- Added: Benchmarks with java and FastUtil
2021-12-16 13:46:55 +01:00
Speiger f32624d131 Build Release..
-Fixed: Doc error on gradle build.
-Fixed: SubSet.iterator had a ambiguity.
2021-12-14 09:05:25 +01:00
Speiger 59a417056c Added Missing method & fixed potential issue with TreeSetBiIterators 2021-12-13 13:56:28 +01:00
Speiger 18f6704ed7 Expanded Unit tests to IntLists/Sets
Maps are sadly not possible. It will require writing templates for
permutations effectively copying guavas Test library.
So this will take a lot longer
2021-12-13 13:45:35 +01:00
Speiger caf2f22e9f Finished the Basic Unit test frame work to ensure stablity.
-Added: 150k Unit tests.
-Fixed: Reworked the NavigableSet/Map implementations of RBTree/AVLTree/Array Sets/Maps
2021-12-13 10:41:20 +01:00
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
125 changed files with 32730 additions and 5714 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>
+38
View File
@@ -0,0 +1,38 @@
# This workflow uses actions that are not certified by GitHub.
# They are provided by a third-party and are governed by
# separate terms of service, privacy policy, and support
# documentation.
# This workflow will build a Java project with Gradle and cache/restore any dependencies to improve the workflow execution time
# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-gradle
name: Latest Build
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
jobs:
build:
strategy:
fail-fast: false
matrix:
jdk: [8, 11, 14, 16, 17]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up JDK ${{ matrix.jdk }}
uses: actions/setup-java@v1
with:
java-version: ${{ matrix.jdk }}
- name: Validate Gradle wrapper
uses: gradle/wrapper-validation-action@e6e38bacfdf1a337459f332974bb2327a31aaf4b
- name: Make gradlew executable
run: chmod +x ./gradlew
- name: Generate SourceCode with Gradle
run: ./gradlew generateGithubSource
- name: Build with Gradle
run: ./gradlew build
-4
View File
@@ -5,9 +5,6 @@
# 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 +13,6 @@ gradle-app.setting
.classpath .classpath
.project .project
gradle-wrapper.jar
---> Custom ---> Custom
!/libs/ !/libs/
+175
View File
@@ -0,0 +1,175 @@
# Changelog of versions
### Version 0.6.0
- Added: addOrGet for sets.
- Added: Async API which allows to easily execute Iterables/Collections offthread without the complexity.
- Added: CopyOnWriteArrayList and tests for it
- Added: Support up to Java17.
- Added: Build System now adds module-info if the Running JVM is 9 or higher
- Added: ArrayList.of(Class, size) that allows you to allocate a size right at the creation of the List without having to create a wrapper array.
- Added: A ConcurrentHashMap implementation.
- Fixed: containsValue in the HashMap wouldn't check the nullKey
- Removed: Deprecated functions from SortedMaps/Sets
### Version 0.5.3
- Added: OrderedMap/Set
- Added: Deprecation to Functions that are specific to Ordered interfaces in the SortedMap/Set
- Added: subFrom to Maps which is the counterpart of the addTo method
- Added: pourAsList and pourAsSet (booleans excluded for sets) to Iterable
- Fixed: ArrayList.grow had a small bug where it would trigger to early causing performance problems with exact sized collections.
- Fixed: FIFOQueue size constructor had a small bug where it would trigger a array enlargement when all elements were inserted.
### Version 0.5.2
- Fixed: Bugs with Queues starting with the wrong size
- Fixed: ArrayGrowth for Queues was +1 instead of +50%
- Added: Benchmarks with java and FastUtil
### Version 0.5.1
- Fixed: Reworked the NavigableSet/Map implementations of RBTree/AVLTree/Array Sets/Maps so they are now deemed stable.
- Added: Another 150k Unit tests.
- Added: List and Set Unit tests for Integer (or Primitives in this case) to ensure basic stability there. (Now covering all sets and lists)
- Fixed: Bugs with null values for primitive collections.
- Removed: ArraySet/Map subSet/subMap implementation was removed.
### 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
+168 -175
View File
@@ -1,208 +1,201 @@
Apache License Apache License
Version 2.0, December 2021
http://www.apache.org/licenses/
Version 2.0, January 2021 TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION,
AND DISTRIBUTION
1. Definitions. 1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"License" shall mean the terms and conditions for use, reproduction, and distribution "Legal Entity" shall mean the union of the acting entity and all
as defined by Sections 1 through 9 of this document. other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Licensor" shall mean the copyright owner or entity authorized by the copyright "Object" form shall mean any form resulting from mechanical
owner that is granting the License. transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Legal Entity" shall mean the union of the acting entity and all other entities "Contribution" shall mean any work of authorship, including
that control, are controlled by, or are under common control with that entity. the original version of the Work and any modifications or additions
For the purposes of this definition, "control" means (i) the power, direct to that Work or Derivative Works thereof, that is intentionally
or indirect, to cause the direction or management of such entity, whether submitted to Licensor for inclusion in the Work by the copyright owner
by contract or otherwise, or (ii) ownership of fifty percent (50%) or more or by an individual or Legal Entity authorized to submit on behalf of
of the outstanding shares, or (iii) beneficial ownership of such entity. the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions 3. Grant of Patent License. Subject to the terms and conditions of
granted by this License. this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
"Source" form shall mean the preferred form for making modifications, including (b) You must cause any modified files to carry prominent notices
but not limited to software source code, documentation source, and configuration stating that You changed the files; and
files.
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
"Object" form shall mean any form resulting from mechanical transformation You may add Your own copyright statement to Your modifications and
or translation of a Source form, including but not limited to compiled object may provide additional or different license terms and conditions
code, generated documentation, and conversions to other media types. for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
"Work" shall mean the work of authorship, whether in Source or Object form, 7. Disclaimer of Warranty. Unless required by applicable law or
made available under the License, as indicated by a copyright notice that agreed to in writing, Licensor provides the Work (and each
is included in or attached to the work (an example is provided in the Appendix Contributor provides its Contributions) on an "AS IS" BASIS,
below). WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
"Derivative Works" shall mean any work, whether in Source or Object form, END OF TERMS AND CONDITIONS
that is based on (or derived from) the Work and for which the editorial revisions,
annotations, elaborations, or other modifications represent, as a whole, an
original work of authorship. For the purposes of this License, Derivative
Works shall not include works that remain separable from, or merely link (or
bind by name) to the interfaces of, the Work and Derivative Works thereof.
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
"Contribution" shall mean any work of authorship, including the original version Copyright 2021 Speiger
of the Work and any modifications or additions to that Work or Derivative
Works thereof, that is intentionally submitted to Licensor for inclusion in
the Work by the copyright owner or by an individual or Legal Entity authorized
to submit on behalf of the copyright owner. For the purposes of this definition,
"submitted" means any form of electronic, verbal, or written communication
sent to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems, and
issue tracking systems that are managed by, or on behalf of, the Licensor
for the purpose of discussing and improving the Work, but excluding communication
that is conspicuously marked or otherwise designated in writing by the copyright
owner as "Not a Contribution."
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf Unless required by applicable law or agreed to in writing, software
of whom a Contribution has been received by Licensor and subsequently incorporated distributed under the License is distributed on an "AS IS" BASIS,
within the Work. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
2. Grant of Copyright License. Subject to the terms and conditions of this limitations under the License.
License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive,
no-charge, royalty-free, irrevocable copyright license to reproduce, prepare
Derivative Works of, publicly display, publicly perform, sublicense, and distribute
the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License,
each Contributor hereby grants to You a perpetual, worldwide, non-exclusive,
no-charge, royalty-free, irrevocable (except as stated in this section) patent
license to make, have made, use, offer to sell, sell, import, and otherwise
transfer the Work, where such license applies only to those patent claims
licensable by such Contributor that are necessarily infringed by their Contribution(s)
alone or by combination of their Contribution(s) with the Work to which such
Contribution(s) was submitted. If You institute patent litigation against
any entity (including a cross-claim or counterclaim in a lawsuit) alleging
that the Work or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses granted to You
under this License for that Work shall terminate as of the date such litigation
is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or
Derivative Works thereof in any medium, with or without modifications, and
in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy
of this License; and
(b) You must cause any modified files to carry prominent notices stating that
You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute,
all copyright, patent, trademark, and attribution notices from the Source
form of the Work, excluding those notices that do not pertain to any part
of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution,
then any Derivative Works that You distribute must include a readable copy
of the attribution notices contained within such NOTICE file, excluding those
notices that do not pertain to any part of the Derivative Works, in at least
one of the following places: within a NOTICE text file distributed as part
of the Derivative Works; within the Source form or documentation, if provided
along with the Derivative Works; or, within a display generated by the Derivative
Works, if and wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and do not modify the
License. You may add Your own attribution notices within Derivative Works
that You distribute, alongside or as an addendum to the NOTICE text from the
Work, provided that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and may provide
additional or different license terms and conditions for use, reproduction,
or distribution of Your modifications, or for any such Derivative Works as
a whole, provided Your use, reproduction, and distribution of the Work otherwise
complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any
Contribution intentionally submitted for inclusion in the Work by You to the
Licensor shall be under the terms and conditions of this License, without
any additional terms or conditions. Notwithstanding the above, nothing herein
shall supersede or modify the terms of any separate license agreement you
may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names,
trademarks, service marks, or product names of the Licensor, except as required
for reasonable and customary use in describing the origin of the Work and
reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to
in writing, Licensor provides the Work (and each Contributor provides its
Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied, including, without limitation, any warranties
or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR
A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness
of using or redistributing the Work and assume any risks associated with Your
exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether
in tort (including negligence), contract, or otherwise, unless required by
applicable law (such as deliberate and grossly negligent acts) or agreed to
in writing, shall any Contributor be liable to You for damages, including
any direct, indirect, special, incidental, or consequential damages of any
character arising as a result of this License or out of the use or inability
to use the Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all other commercial
damages or losses), even if such Contributor has been advised of the possibility
of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work
or Derivative Works thereof, You may choose to offer, and charge a fee for,
acceptance of support, warranty, indemnity, or other liability obligations
and/or rights consistent with this License. However, in accepting such obligations,
You may act only on Your own behalf and on Your sole responsibility, not on
behalf of any other Contributor, and only if You agree to indemnify, defend,
and hold each Contributor harmless for any liability incurred by, or claims
asserted against, such Contributor by reason of your accepting any such warranty
or additional liability. END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate
notice, with the fields enclosed by brackets "[]" replaced with your own identifying
information. (Don't include the brackets!) The text should be enclosed in
the appropriate comment syntax for the file format. We also recommend that
a file or class name and description of purpose be included on the same "printed
page" as the copyright notice for easier identification within third-party
archives.
Copyright 2021 Speiger
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+127 -7
View File
@@ -1,22 +1,142 @@
# Primitive-Collections (To be Renamed) ![build](https://github.com/Speiger/Primitive-Collections/actions/workflows/build_validator.yml/badge.svg)
# 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 / CopyOnWriteLists
- HashSets/Maps (Linked & HashControl)
- TreeSets/Maps (RB & AVL)
- EnumMaps
- Immutable Maps/Lists/Sets
- ConcurrentHashMaps
- Priority Queues
- Streams & Functional Queries
- SplitIterators
- Iterators
- Pairs
- Unary/Functions
- Suppliers
- Bi/Consumers
- AsyncBuilders
## 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 160k unit 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.
### Benchmarks
Benchmarks can be found here: [Click Me](https://github.com/Speiger/Primitive-Collections-Benchmarks/tree/master)
## 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:
- addAll: addAll array version
- 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)
- subFrom (Only Primitive Values): allows to subtract from the value of a given key. If value reached getDefaultReturnValue() element will be removed.
- 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.
# Guide # 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)
The SourceCode can be already generated via: 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.6.0'
}
```
Direct:
| Version | Jar | Sources | Java Doc |
|--------- |------------------------------------------------------------------------------------------------------------------------------ |-------------------------------------------------------------------------------------------------------------------------------------- |-------------------------------------------------------------------------------------------------------------------------------------- |
| 0.6.0 | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.6.0/Primitive-Collections-0.6.0.jar) | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.6.0/Primitive-Collections-0.6.0-sources.jar) | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.6.0/Primitive-Collections-0.6.0-javadoc.jar) |
| 0.5.3 | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.5.3/Primitive-Collections-0.5.3.jar) | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.5.3/Primitive-Collections-0.5.3-sources.jar) | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.5.3/Primitive-Collections-0.5.3-javadoc.jar) |
| 0.5.2 | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.5.2/Primitive-Collections-0.5.2.jar) | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.5.2/Primitive-Collections-0.5.2-sources.jar) | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.5.2/Primitive-Collections-0.5.2-javadoc.jar) |
| 0.5.1 | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.5.1/Primitive-Collections-0.5.1.jar) | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.5.1/Primitive-Collections-0.5.1-sources.jar) | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.5.1/Primitive-Collections-0.5.1-javadoc.jar) |
| 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
- 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.
+76 -19
View File
@@ -8,18 +8,21 @@ tasks.withType(JavaCompile) {
apply plugin: 'java' apply plugin: 'java'
apply plugin: 'eclipse' apply plugin: 'eclipse'
apply plugin: 'maven-publish'
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.6.0';
sourceCompatibility = targetCompatibility = compileJava.sourceCompatibility = compileJava.targetCompatibility = '1.8' sourceCompatibility = targetCompatibility = compileJava.sourceCompatibility = compileJava.targetCompatibility = JavaVersion.current();
System.out.println("Java Version: "+compileJava.sourceCompatibility)
javadoc { javadoc {
options.tags = [ "implSpec", "note" ] options.tags = [ "implSpec", "note" ]
@@ -29,19 +32,7 @@ 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 {
@@ -53,8 +44,9 @@ configurations {
} }
dependencies { dependencies {
compile 'SimpleCodeGenerator:Simple Code Generator:1.0.1' builderImplementation 'de.speiger:Simple-Code-Generator:1.0.7'
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,22 @@ task generateSource(type: JavaExec) {
main = 'speiger.src.builder.PrimitiveCollectionsBuilder' main = 'speiger.src.builder.PrimitiveCollectionsBuilder'
} }
task generateGithubSource(type: JavaExec) {
group = 'internal'
description = 'Builds the sourcecode for Github Actions'
classpath = sourceSets.builder.runtimeClasspath
main = 'speiger.src.builder.PrimitiveCollectionsBuilder'
args = ['false', 'true']
}
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 +84,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 +94,53 @@ artifacts {
test { test {
useJUnit() useJUnit()
} }
publishing {
Properties props = new Properties()
if(file("$buildDir/credentials.properties").exists()) {
props.load(new FileInputStream("$buildDir/credentials.properties"))
}
publications {
mavenJava(MavenPublication) {
pom {
name = 'Primitive Collections'
description = 'A Primitive Collection library that reduces memory usage and improves performance'
url = 'https://github.com/Speiger/Primitive-Collections'
version = project.version
artifactId = project.archivesBaseName.replace(" ", "-")
groupId = 'de.speiger'
from components.java
artifact tasks.srcJar
artifact tasks.javadocJar
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'
}
}
scm {
url = 'https://github.com/Speiger/Primitive-Collections'
}
issueManagement {
system = 'github'
url = 'https://github.com/Speiger/Primitive-Collections/issues'
}
}
}
}
repositories {
maven {
url version.endsWith('SNAPSHOT') ? "https://maven.speiger.com/repository/debug" : "https://maven.speiger.com/repository/main"
credentials(PasswordCredentials) {
username props.mavenUser
password props.mavenPassword
}
}
}
}
+1
View File
@@ -0,0 +1 @@
org.gradle.jvmargs=-Xmx3G
Binary file not shown.
+1 -1
View File
@@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.0-bin.zip distributionUrl=https\://services.gradle.org/distributions/gradle-7.3-bin.zip
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists zipStorePath=wrapper/dists
+7
View File
@@ -0,0 +1,7 @@
jdk:
- openjdk9
install:
- chmod +x ./gradlew
- ./gradlew generateGithubSource
- ./gradlew build publishToMavenLocal
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,84 +148,114 @@ 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");
addAbstractMapper("COPY_ON_WRITE_LIST", "CopyOnWrite%sArrayList");
addClassMapper("ASYNC_BUILDER", "AsyncBuilder");
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("CONCURRENT_HASH_MAP", "ConcurrentOpenHashMap", "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");
addClassMapper("SUB_LIST", "SubList"); addClassMapper("SUB_LIST", "SubList");
addAbstractMapper("BASE_TASK", "Base%sTask");
//Helper Classes //Helper Classes
addClassMapper("LISTS", "Lists"); addClassMapper("LISTS", "Lists");
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");
addBiClassMapper("NAVIGABLE_MAP", "NavigableMap", "2"); addBiClassMapper("NAVIGABLE_MAP", "NavigableMap", "2");
addBiClassMapper("ORDERED_MAP", "OrderedMap", "2");
addBiClassMapper("SORTED_MAP", "SortedMap", "2"); addBiClassMapper("SORTED_MAP", "SortedMap", "2");
addBiClassMapper("CONCURRENT_MAP", "ConcurrentMap", "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("ORDERED_SET", "OrderedSet");
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");
addClassMapper("TASK", "Task");
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 +264,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 +285,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 +397,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());
@@ -1,6 +1,8 @@
package speiger.src.builder; package speiger.src.builder;
import java.io.BufferedWriter;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.util.ArrayList; import java.util.ArrayList;
@@ -10,7 +12,9 @@ import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.StringJoiner;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.stream.Stream;
import speiger.src.builder.processor.TemplateProcess; import speiger.src.builder.processor.TemplateProcess;
import speiger.src.builder.processor.TemplateProcessor; import speiger.src.builder.processor.TemplateProcessor;
@@ -29,12 +33,22 @@ public class PrimitiveCollectionsBuilder extends TemplateProcessor
public PrimitiveCollectionsBuilder() public PrimitiveCollectionsBuilder()
{ {
super(Paths.get("src/builder/resources/speiger/assets/collections/templates/"), Paths.get("src/main/java/speiger/src/collections/"), Paths.get("src/builder/resources/speiger/assets/collections/")); this(false);
}
public PrimitiveCollectionsBuilder(boolean silencedSuccess)
{
super(silencedSuccess, Paths.get("src/builder/resources/speiger/assets/collections/templates/"), Paths.get("src/main/java/speiger/src/collections/"), Paths.get("src/builder/resources/speiger/assets/collections/"));
} }
public PrimitiveCollectionsBuilder(Path sourceFolder, Path outputFolder, Path dataFolder) public PrimitiveCollectionsBuilder(Path sourceFolder, Path outputFolder, Path dataFolder)
{ {
super(sourceFolder, outputFolder, dataFolder); this(false, sourceFolder, outputFolder, dataFolder);
}
public PrimitiveCollectionsBuilder(boolean silencedSuccess, Path sourceFolder, Path outputFolder, Path dataFolder)
{
super(silencedSuccess, sourceFolder, outputFolder, dataFolder);
} }
@Override @Override
@@ -55,6 +69,23 @@ public class PrimitiveCollectionsBuilder extends TemplateProcessor
return false; return false;
} }
@Override
protected void afterFinish()
{
if(getVersion() > 8)
{
Path basePath = Paths.get("src/main/java");
try(BufferedWriter writer = Files.newBufferedWriter(basePath.resolve("module-info.java")))
{
writer.write(getModuleInfo(basePath));
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
@Override @Override
protected void init() protected void init()
{ {
@@ -67,19 +98,30 @@ 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", "OrderedMap", "NavigableMap", "ConcurrentMap", "AbstractMap", "ConcurrentOpenHashMap", "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("CopyOnWriteList", "CopyOnWrite%sArrayList");
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", "OrderedSet", "NavigableSet", "OpenHashSet", "OpenCustomHashSet", "LinkedOpenHashSet", "LinkedOpenCustomHashSet");
addBlockage(ClassType.BOOLEAN, "SortedMap", "NavigableMap", "OpenHashMap", "LinkedOpenHashMap", "OpenCustomHashMap", "LinkedOpenCustomHashMap", "ArrayMap", "RBTreeMap", "AVLTreeMap"); addBlockage(ClassType.BOOLEAN, "ConcurrentOpenHashMap", "ImmutableOpenHashMap", "ImmutableOpenHashSet", "SortedMap", "OrderedMap", "NavigableMap", "ConcurrentMap", "OpenHashMap", "LinkedOpenHashMap", "OpenCustomHashMap", "LinkedOpenCustomHashMap", "ArrayMap", "RBTreeMap", "AVLTreeMap");
} }
protected void create(ClassType mainType, ClassType subType) protected void create(ClassType mainType, ClassType subType)
@@ -141,14 +183,71 @@ public class PrimitiveCollectionsBuilder extends TemplateProcessor
return variables; return variables;
} }
private String getModuleInfo(Path basePath) {
StringJoiner joiner = new StringJoiner("\n", "", "\n");
try(Stream<Path> stream = Files.walk(getOutputFolder()))
{
stream.filter(Files::isDirectory)
.filter(this::containsFiles)
.map(basePath::relativize)
.map(Path::toString)
.map(this::sanitize)
.forEach(T -> joiner.add("\texports "+T+";"));
}
catch(Exception e)
{
e.printStackTrace();
throw new RuntimeException(e);
}
StringBuilder builder = new StringBuilder();
builder.append("/** @author Speiger */\n");
builder.append("module ").append(sanitize(basePath.relativize(getOutputFolder()).toString())).append(" {\n");
builder.append(joiner.toString()).append("}");
return builder.toString();
}
private String sanitize(String input)
{
return input.replace("\\", ".").replace("/", ".");
}
private boolean containsFiles(Path path)
{
try(Stream<Path> stream = Files.walk(path, 1))
{
return stream.filter(Files::isRegularFile).findFirst().isPresent();
}
catch(Exception e)
{
e.printStackTrace();
}
return false;
}
private int getVersion()
{
String version = System.getProperty("java.version");
if(version.startsWith("1.")) return Integer.parseInt(version.substring(2, 3));
int dot = version.indexOf(".");
return Integer.parseInt(dot != -1 ? version.substring(0, dot) : version);
}
public static void main(String...args) public static void main(String...args)
{ {
try try
{ {
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 == 2) {
new PrimitiveCollectionsBuilder(Boolean.parseBoolean(args[1])).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 if(args.length == 4) {
new PrimitiveCollectionsBuilder(false, Paths.get(args[0]), Paths.get(args[1]), Paths.get(args[2])).process(Boolean.parseBoolean(args[3]));
} else if(args.length == 4) {
new PrimitiveCollectionsBuilder(Boolean.parseBoolean(args[4]), Paths.get(args[0]), Paths.get(args[1]), Paths.get(args[2])).process(Boolean.parseBoolean(args[3]));
} else { } 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,12 @@ 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;
#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 +38,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 +61,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 +71,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,23 +82,30 @@ 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
* @return true if any element is in this collection * @return true if any element is in this collection
* @deprecated if this is a primitive collection
* @throws java.lang.NullPointerException if the collection is null * @throws java.lang.NullPointerException if the collection is null
*/ */
@Override @Override
@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 +121,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 +164,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 +175,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,6 +216,27 @@ 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.
@@ -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,7 +140,48 @@ 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
@@ -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,29 @@
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.collections.SPLIT_ITERATOR; 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.lists.LIST;
import speiger.src.collections.PACKAGE.lists.ARRAY_LIST;
#if !TYPE_BOOLEAN
import speiger.src.collections.PACKAGE.sets.SET;
import speiger.src.collections.PACKAGE.sets.LINKED_HASH_SET;
#endif
import speiger.src.collections.PACKAGE.utils.ASYNC_BUILDER;
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
@@ -22,8 +38,8 @@ public interface ITERABLE KEY_GENERIC_TYPE extends Iterable<CLASS_TYPE>
*/ */
@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
* *
@@ -52,7 +68,19 @@ public interface ITERABLE KEY_GENERIC_TYPE extends Iterable<CLASS_TYPE>
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 +88,233 @@ 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); }
/**
* Creates a Async Builder for moving work of the thread.
* It is not designed to split the work to multithreaded work, so using this keep it singlethreaded, but it allows to be moved to another thread.
* @see ASYNC_BUILDER
* @return a AsyncBuilder
*/
default ASYNC_BUILDER KEY_GENERIC_TYPE asAsync() {
return new ASYNC_BUILDERBRACES(this);
}
/**
* 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;
}
/**
* A Helper function that reduces the usage of streams and allows to collect all elements as a ArrayList
* @return a new ArrayList of all elements
*/
default LIST KEY_GENERIC_TYPE pourAsList() {
return pour(new ARRAY_LISTBRACES());
}
#if !TYPE_BOOLEAN
/**
* A Helper function that reduces the usage of streams and allows to collect all elements as a LinkedHashSet
* @return a new LinkedHashSet of all elements
*/
default SET KEY_GENERIC_TYPE pourAsSet() {
return pour(new LINKED_HASH_SETBRACES());
}
#endif
/**
* 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
@@ -66,6 +67,18 @@ public interface ITERATOR KEY_GENERIC_TYPE extends Iterator<CLASS_TYPE>
} }
#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.
*/ */
@Override public void clear();
@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.
*/ */
@Override public default boolean isEmpty() {
@Deprecated return size() == 0;
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
} }
@@ -50,6 +50,10 @@ public interface COMPARATOR extends Comparator<CLASS_TYPE>
{ {
COMPARATOR original; COMPARATOR original;
/**
* default constructor
* @param original that is going to be reversed
*/
public Reversed(COMPARATOR original) { public Reversed(COMPARATOR original) {
this.original = original; this.original = original;
} }
@@ -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
}
@@ -0,0 +1,92 @@
package speiger.src.collections.PACKAGE.functions;
import java.util.concurrent.RunnableFuture;
#if !TYPE_OBJECT
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
#endif
/**
*
* A Type Specific Task interface that allows you to keep track of the task that is currently running.<br>
* It extends Runnable future and supports said functions but also provides quality of life functions like:<br>
*
* - isSuccesfull: which allows to detect if the task was completed properly and not interrupted or crashed.
* - pause/resume: which allows to pause/resume the task at any moment, making it easier to create thread-safe actions.
* @Type(T)
*/
public interface TASK KEY_GENERIC_TYPE extends RunnableFuture<CLASS_TYPE> {
/**
* Helper function to detect if the task is currently paused.
* @return true if paused
*/
public boolean isPaused();
/**
* Pauses the task, which lets the thread finish without completing the task.
* Tasks are written in the way where they can pause without any issues.
* This won't be instant, as this function is applied asynchronous and doesn't check if the thread paused.
* So make sure it had the time to pause.
*/
public void pause();
/**
* Pauses the task, which lets the thread finish without completing the task.
* Tasks are written in the way where they can pause without any issues.
* This won't be instant, as this function is applied asynchronous.
* It will await the pausing of the task.
*/
public void awaitPausing();
/**
* Continues the task if it wasn't already completed.
* This is done by resubmitting the task to the executor provided.
*/
public void resume();
/**
* Quality of life function that allows to detect if no cancellation/exception was applied to this task and it completed on its own.
* @return true if it was properly completed
*/
public boolean isSuccessful();
#if !TYPE_OBJECT
/**
* A Type Specific get method that allows to reduce (un)boxing of primtives.
*
* Waits if necessary for the computation to complete, and then
* retrieves its result.
*
* @return the computed result as primitive
* @throws CancellationException if the computation was cancelled
* @throws ExecutionException if the computation threw an exception
* @throws InterruptedException if the current thread was interrupted
* while waiting
*/
public KEY_TYPE GET_KEY() throws InterruptedException, ExecutionException;
/**
* Waits if necessary for at most the given time for the computation
* to complete, and then retrieves its result, if available.
*
* @param timeout the maximum time to wait
* @param unit the time unit of the timeout argument
* @return the computed result as primitive
* @throws CancellationException if the computation was cancelled
* @throws ExecutionException if the computation threw an exception
* @throws InterruptedException if the current thread was interrupted while waiting
* @throws TimeoutException if the wait timed out
*/
public KEY_TYPE GET_KEY(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException;
@Override
@Deprecated
public default CLASS_TYPE get() throws InterruptedException, ExecutionException { return KEY_TO_OBJ(GET_KEY()); }
@Override
@Deprecated
public default CLASS_TYPE get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return KEY_TO_OBJ(GET_KEY(timeout, unit)); }
#endif
}
@@ -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,16 +57,25 @@ 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);
} }
/** /**
* The IndexOf implementation iterates over all elements and compares them to the search value. * The IndexOf implementation iterates over all elements and compares them to the search value.
* @param o the value that the index is searched for. * @param o the value that the index is searched for.
* @return index of the value that was searched for. -1 if not found * @return index of the value that was searched for. -1 if not found
* @deprecated it is highly suggested not to use this with Primitives because of boxing. But it is still supported because of ObjectComparason that are custom objects and allow to find the contents. * @note it is highly suggested not to use this with Primitives because of boxing. But it is still supported because of ObjectComparason that are custom objects and allow to find the contents.
*/ */
@Override @Override
@Primitive @Primitive
@@ -92,7 +103,7 @@ public abstract class ABSTRACT_LIST KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION
* The lastIndexOf implementation iterates over all elements and compares them to the search value. * The lastIndexOf implementation iterates over all elements and compares them to the search value.
* @param o the value that the index is searched for. * @param o the value that the index is searched for.
* @return the last index of the value that was searched for. -1 if not found * @return the last index of the value that was searched for. -1 if not found
* @deprecated it is highly suggested not to use this with Primitives because of boxing. But it is still supported because of ObjectComparason that are custom objects and allow to find the contents. * @note it is highly suggested not to use this with Primitives because of boxing. But it is still supported because of ObjectComparason that are custom objects and allow to find the contents.
*/ */
@Override @Override
@Primitive @Primitive
@@ -148,6 +159,14 @@ 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.
*/ */
@@ -198,7 +217,8 @@ public abstract class ABSTRACT_LIST KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION
@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,20 @@ 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;
}
/**
* Creates a new ArrayList with a EmptyObject array of the Type requested
* @param c the type of the array
* @param size the initial size of the backing array
* @Type(T)
* @return a typed List
*/
public static GENERIC_KEY_BRACES ARRAY_LIST KEY_GENERIC_TYPE of(Class<KEY_TYPE> c, int size) {
ARRAY_LIST KEY_GENERIC_TYPE list = new ARRAY_LISTBRACES();
list.data = (KEY_TYPE[])ObjectArrays.newArray(c, size);
return list; return list;
} }
@@ -187,7 +206,7 @@ public class ARRAY_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
* Appends the specified element to the end of this list. * Appends the specified element to the end of this list.
* *
* @param e element to be appended to this list * @param e element to be appended to this list
* @return <tt>true</tt> (as specified by {@link Collection#add}) * @return true (as specified by {@link Collection#add})
*/ */
@Override @Override
public boolean add(KEY_TYPE e) { public boolean add(KEY_TYPE e) {
@@ -201,7 +220,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 +245,7 @@ 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 * @throws NullPointerException if collection contains a null element
*/ */
@Override @Override
@Primitive @Primitive
@@ -234,11 +253,14 @@ public class ARRAY_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
if(c instanceof COLLECTION) return addAll(index, (COLLECTION KEY_GENERIC_TYPE)c); if(c instanceof COLLECTION) return addAll(index, (COLLECTION KEY_GENERIC_TYPE)c);
int add = c.size(); int add = c.size();
if(add <= 0) return false; if(add <= 0) return false;
#if !TYPE_OBJECT
if(c.contains(null)) throw new NullPointerException();
#endif
grow(size + add); grow(size + add);
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 +270,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 +289,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 +302,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 +319,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 +343,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 +410,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 +432,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 +455,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 +483,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 +494,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 +580,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];
} }
@@ -593,6 +626,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 +763,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 +791,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 +817,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 +833,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 +843,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 +867,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 +893,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 +933,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 +976,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 +1040,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 +1055,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 +1107,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 +1134,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 +1157,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;
@@ -47,6 +51,26 @@ public interface LIST KEY_GENERIC_TYPE extends COLLECTION KEY_GENERIC_TYPE, List
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
@@ -147,12 +171,12 @@ public interface LIST KEY_GENERIC_TYPE extends COLLECTION KEY_GENERIC_TYPE, List
} }
#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,7 +262,7 @@ 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();
@@ -239,7 +278,7 @@ 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();
@@ -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.
@@ -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}
@@ -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
@@ -114,6 +159,12 @@ public abstract class ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE extends AbstractMap<CL
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
public void REPLACE_VALUES(UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) { public void REPLACE_VALUES(UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) {
Objects.requireNonNull(mappingFunction); Objects.requireNonNull(mappingFunction);
@@ -153,6 +204,20 @@ public abstract class ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE extends AbstractMap<CL
return value; 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;
}
@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);
@@ -178,6 +243,18 @@ public abstract class ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE extends AbstractMap<CL
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,35 +1,62 @@
package speiger.src.collections.PACKAGE.maps.impl.customHash; package speiger.src.collections.PACKAGE.maps.impl.customHash;
import java.util.Comparator; import java.util.Arrays;
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.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.ORDERED_MAP;
import speiger.src.collections.PACKAGE.sets.ABSTRACT_SET; import speiger.src.collections.PACKAGE.sets.ABSTRACT_SET;
import speiger.src.collections.PACKAGE.sets.SORTED_SET; import speiger.src.collections.PACKAGE.sets.ORDERED_SET;
import speiger.src.collections.PACKAGE.sets.SET; 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;
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;
import speiger.src.collections.objects.sets.ObjectSortedSet;
import speiger.src.collections.objects.sets.ObjectSet; import speiger.src.collections.objects.sets.ObjectSet;
#endif #endif
import speiger.src.collections.utils.HashUtil; import speiger.src.collections.utils.HashUtil;
@@ -41,7 +68,7 @@ import speiger.src.collections.utils.HashUtil;
* @Type(T) * @Type(T)
* @ValueType(V) * @ValueType(V)
*/ */
public class LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE implements SORTED_MAP KEY_VALUE_GENERIC_TYPE public class LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE implements ORDERED_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 transient long[] links; protected transient long[] links;
@@ -317,19 +344,22 @@ public class LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends CUSTOM_HASH_M
} }
@Override @Override
public COMPARATOR KEY_GENERIC_TYPE comparator() { public LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE copy() {
return null; 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
public SORTED_MAP KEY_VALUE_GENERIC_TYPE subMap(KEY_TYPE fromKey, KEY_TYPE toKey) { throw new UnsupportedOperationException(); }
@Override
public SORTED_MAP KEY_VALUE_GENERIC_TYPE headMap(KEY_TYPE toKey) { throw new UnsupportedOperationException(); }
@Override
public SORTED_MAP KEY_VALUE_GENERIC_TYPE tailMap(KEY_TYPE fromKey) { throw new UnsupportedOperationException(); }
@Override @Override
public KEY_TYPE FIRST_ENTRY_KEY() { public KEY_TYPE FIRST_ENTRY_KEY() {
if(size == 0) throw new NoSuchElementException(); if(size == 0) throw new NoSuchElementException();
@@ -423,6 +453,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 +529,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];
@@ -555,7 +603,7 @@ public class LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends CUSTOM_HASH_M
values = newValues; values = newValues;
} }
private class MapEntrySet extends AbstractObjectSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> implements SORTED_MAP.FastSortedSet KEY_VALUE_GENERIC_TYPE { private class MapEntrySet extends AbstractObjectSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> implements ORDERED_MAP.FastOrderedSet KEY_VALUE_GENERIC_TYPE {
@Override @Override
public boolean addAndMoveToFirst(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); } public boolean addAndMoveToFirst(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); }
@Override @Override
@@ -615,10 +663,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 +679,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;
} }
@@ -668,20 +843,9 @@ public class LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends CUSTOM_HASH_M
public void clear() { public void clear() {
LINKED_CUSTOM_HASH_MAP.this.clear(); LINKED_CUSTOM_HASH_MAP.this.clear();
} }
@Override
public Comparator<MAP.Entry KEY_VALUE_GENERIC_TYPE> comparator() {
return null;
}
@Override
public ObjectSortedSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> subSet(MAP.Entry KEY_VALUE_GENERIC_TYPE fromElement, MAP.Entry KEY_VALUE_GENERIC_TYPE toElement) { throw new UnsupportedOperationException(); }
@Override
public ObjectSortedSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> headSet(MAP.Entry KEY_VALUE_GENERIC_TYPE toElement) { throw new UnsupportedOperationException(); }
@Override
public ObjectSortedSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> tailSet(MAP.Entry KEY_VALUE_GENERIC_TYPE fromElement) { throw new UnsupportedOperationException(); }
} }
private final class KeySet extends ABSTRACT_SET KEY_GENERIC_TYPE implements SORTED_SET KEY_GENERIC_TYPE { private final class KeySet extends ABSTRACT_SET KEY_GENERIC_TYPE implements ORDERED_SET KEY_GENERIC_TYPE {
#if TYPE_OBJECT #if TYPE_OBJECT
@Override @Override
@Deprecated @Deprecated
@@ -692,7 +856,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 +869,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 +905,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 +938,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,18 +947,123 @@ 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 @Override
public COMPARATOR KEY_GENERIC_TYPE comparator() { return null; } 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 @Override
public SORTED_SET KEY_GENERIC_TYPE subSet(KEY_TYPE fromElement, KEY_TYPE toElement) { throw new UnsupportedOperationException(); } 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 @Override
public SORTED_SET KEY_GENERIC_TYPE headSet(KEY_TYPE toElement) { throw new UnsupportedOperationException(); } public int count(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
@Override if(size() <= 0) return 0;
public SORTED_SET KEY_GENERIC_TYPE tailSet(KEY_TYPE fromElement) { throw new UnsupportedOperationException(); } int result = 0;
int index = firstIndex;
while(index != -1){
if(filter.TEST_VALUE(keys[index])) result++;
index = (int)links[index];
}
return result;
}
} }
private class Values extends VALUE_ABSTRACT_COLLECTION VALUE_GENERIC_TYPE { private class Values extends VALUE_ABSTRACT_COLLECTION VALUE_GENERIC_TYPE {
@@ -840,16 +1101,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 +1109,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> {
@@ -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;
@@ -247,6 +286,15 @@ public class CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VAL
return oldValue; return oldValue;
} }
@Override
public VALUE_TYPE subFrom(KEY_TYPE key, VALUE_TYPE value) {
int slot = findIndex(key);
if(slot < 0) return getDefaultReturnValue();
VALUE_TYPE oldValue = values[slot];
values[slot] -= value;
if(value < 0 ? (values[slot] >= getDefaultReturnValue()) : (values[slot] <= getDefaultReturnValue())) removeIndex(slot);
return oldValue;
}
#endif #endif
#if !TYPE_OBJECT #if !TYPE_OBJECT
@Override @Override
@@ -256,7 +304,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 +316,45 @@ 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; if(containsNull && VALUE_EQUALS(values[nullIndex], value)) return true;
for(int i = nullIndex-1;i >= 0;i--) for(int i = nullIndex;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; #if VALUE_OBJECT
if(containsNull && VALUE_EQUALS(values[nullIndex], value)) return true;
#else
if(containsNull && ((value == null && values[nullIndex] == getDefaultReturnValue()) || EQUALS_VALUE_TYPE(values[nullIndex], value))) return true;
#endif
for(int i = nullIndex-1;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 +451,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 +492,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 +625,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 +680,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 +715,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 +820,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 +850,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 +1004,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 +1045,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 +1058,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 +1073,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 +1086,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 +1243,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 +1404,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 +1436,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 +1456,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,37 +1,61 @@
package speiger.src.collections.PACKAGE.maps.impl.hash; package speiger.src.collections.PACKAGE.maps.impl.hash;
import java.util.Comparator; import java.util.Arrays;
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.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.ORDERED_MAP;
import speiger.src.collections.PACKAGE.sets.ABSTRACT_SET; import speiger.src.collections.PACKAGE.sets.ABSTRACT_SET;
import speiger.src.collections.PACKAGE.sets.SORTED_SET; import speiger.src.collections.PACKAGE.sets.ORDERED_SET;
import speiger.src.collections.PACKAGE.sets.SET; 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;
import speiger.src.collections.objects.sets.ObjectSortedSet;
import speiger.src.collections.objects.sets.ObjectSet; import speiger.src.collections.objects.sets.ObjectSet;
#endif #endif
import speiger.src.collections.utils.HashUtil; import speiger.src.collections.utils.HashUtil;
@@ -43,10 +67,10 @@ import speiger.src.collections.utils.HashUtil;
* @Type(T) * @Type(T)
* @ValueType(V) * @ValueType(V)
*/ */
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 ORDERED_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,19 +320,49 @@ 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 @Override
public COMPARATOR KEY_GENERIC_TYPE comparator() { public boolean containsValue(VALUE_TYPE value) {
return null; 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 @Override
public SORTED_MAP KEY_VALUE_GENERIC_TYPE subMap(KEY_TYPE fromKey, KEY_TYPE toKey) { throw new UnsupportedOperationException(); } public LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE copy() {
LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE map = new LINKED_HASH_MAPKV_BRACES(0, loadFactor);
@Override map.minCapacity = minCapacity;
public SORTED_MAP KEY_VALUE_GENERIC_TYPE headMap(KEY_TYPE toKey) { throw new UnsupportedOperationException(); } map.mask = mask;
map.maxFill = maxFill;
@Override map.nullIndex = nullIndex;
public SORTED_MAP KEY_VALUE_GENERIC_TYPE tailMap(KEY_TYPE fromKey) { throw new UnsupportedOperationException(); } 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 KEY_TYPE FIRST_ENTRY_KEY() { public KEY_TYPE FIRST_ENTRY_KEY() {
@@ -403,6 +457,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 +533,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];
@@ -535,7 +607,7 @@ public class LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE extends HASH_MAP KEY_VALUE_G
values = newValues; values = newValues;
} }
private class MapEntrySet extends AbstractObjectSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> implements SORTED_MAP.FastSortedSet KEY_VALUE_GENERIC_TYPE { private class MapEntrySet extends AbstractObjectSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> implements ORDERED_MAP.FastOrderedSet KEY_VALUE_GENERIC_TYPE {
@Override @Override
public boolean addAndMoveToFirst(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); } public boolean addAndMoveToFirst(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); }
@Override @Override
@@ -595,6 +667,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 +690,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;
} }
@@ -648,20 +844,9 @@ public class LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE extends HASH_MAP KEY_VALUE_G
public void clear() { public void clear() {
LINKED_HASH_MAP.this.clear(); LINKED_HASH_MAP.this.clear();
} }
@Override
public Comparator<MAP.Entry KEY_VALUE_GENERIC_TYPE> comparator() {
return null;
}
@Override
public ObjectSortedSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> subSet(MAP.Entry KEY_VALUE_GENERIC_TYPE fromElement, MAP.Entry KEY_VALUE_GENERIC_TYPE toElement) { throw new UnsupportedOperationException(); }
@Override
public ObjectSortedSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> headSet(MAP.Entry KEY_VALUE_GENERIC_TYPE toElement) { throw new UnsupportedOperationException(); }
@Override
public ObjectSortedSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> tailSet(MAP.Entry KEY_VALUE_GENERIC_TYPE fromElement) { throw new UnsupportedOperationException(); }
} }
private final class KeySet extends ABSTRACT_SET KEY_GENERIC_TYPE implements SORTED_SET KEY_GENERIC_TYPE { private final class KeySet extends ABSTRACT_SET KEY_GENERIC_TYPE implements ORDERED_SET KEY_GENERIC_TYPE {
#if TYPE_OBJECT #if TYPE_OBJECT
@Override @Override
@Deprecated @Deprecated
@@ -672,7 +857,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,15 +870,13 @@ 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;
} }
#endif #endif
@Override @Override
public boolean add(KEY_TYPE o) { public boolean add(KEY_TYPE o) { throw new UnsupportedOperationException(); }
throw new UnsupportedOperationException();
}
@Override @Override
public boolean addAndMoveToFirst(KEY_TYPE o) { throw new UnsupportedOperationException(); } public boolean addAndMoveToFirst(KEY_TYPE o) { throw new UnsupportedOperationException(); }
@@ -721,6 +904,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 +937,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,18 +946,123 @@ 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 @Override
public COMPARATOR KEY_GENERIC_TYPE comparator() { return null; } 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 @Override
public SORTED_SET KEY_GENERIC_TYPE subSet(KEY_TYPE fromElement, KEY_TYPE toElement) { throw new UnsupportedOperationException(); } 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 @Override
public SORTED_SET KEY_GENERIC_TYPE headSet(KEY_TYPE toElement) { throw new UnsupportedOperationException(); } public int count(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
@Override if(size() <= 0) return 0;
public SORTED_SET KEY_GENERIC_TYPE tailSet(KEY_TYPE fromElement) { throw new UnsupportedOperationException(); } int result = 0;
int index = firstIndex;
while(index != -1){
if(filter.TEST_VALUE(keys[index])) result++;
index = (int)links[index];
}
return result;
}
} }
private class Values extends VALUE_ABSTRACT_COLLECTION VALUE_GENERIC_TYPE { private class Values extends VALUE_ABSTRACT_COLLECTION VALUE_GENERIC_TYPE {
@@ -820,25 +1100,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> {
@@ -940,7 +1328,6 @@ public class LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE extends HASH_MAP KEY_VALUE_G
@Override @Override
public void add(VALUE_TYPE e) { throw new UnsupportedOperationException(); } public void add(VALUE_TYPE e) { throw new UnsupportedOperationException(); }
} }
private class MapIterator { private class MapIterator {
@@ -1010,7 +1397,7 @@ public class LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE extends HASH_MAP KEY_VALUE_G
if(previous == -1) firstIndex = next; if(previous == -1) firstIndex = next;
else links[previous] ^= ((links[previous] ^ (next & 0xFFFFFFFFL)) & 0xFFFFFFFFL); else links[previous] ^= ((links[previous] ^ (next & 0xFFFFFFFFL)) & 0xFFFFFFFFL);
if (next == -1) lastIndex = previous; if(next == -1) lastIndex = previous;
else links[next] ^= ((links[next] ^ ((previous & 0xFFFFFFFFL) << 32)) & 0xFFFFFFFF00000000L); else links[next] ^= ((links[next] ^ ((previous & 0xFFFFFFFFL) << 32)) & 0xFFFFFFFF00000000L);
if(current == nullIndex) { if(current == nullIndex) {
current = -1; current = -1;
@@ -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;
@@ -222,6 +261,15 @@ public class HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENE
return oldValue; return oldValue;
} }
@Override
public VALUE_TYPE subFrom(KEY_TYPE key, VALUE_TYPE value) {
int slot = findIndex(key);
if(slot < 0) return getDefaultReturnValue();
VALUE_TYPE oldValue = values[slot];
values[slot] -= value;
if(value < 0 ? (values[slot] >= getDefaultReturnValue()) : (values[slot] <= getDefaultReturnValue())) removeIndex(slot);
return oldValue;
}
#endif #endif
#if !TYPE_OBJECT #if !TYPE_OBJECT
@Override @Override
@@ -231,7 +279,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,7 +287,7 @@ 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; if(containsNull && VALUE_EQUALS(values[nullIndex], value)) return true;
for(int i = nullIndex-1;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;
@@ -247,23 +295,37 @@ public class HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENE
#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; #if VALUE_OBJECT
if(containsNull && VALUE_EQUALS(values[nullIndex], value)) return true;
#else
if(containsNull && ((value == null && values[nullIndex] == getDefaultReturnValue()) || EQUALS_VALUE_TYPE(values[nullIndex], value))) return true;
#endif
for(int i = nullIndex-1;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 +412,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 +453,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 +586,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 +640,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 +675,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 +780,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 +817,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 +964,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 +1002,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 +1015,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 +1040,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 +1199,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 +1360,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 +1392,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 +1412,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,13 +34,13 @@ 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 */
@@ -44,6 +50,9 @@ public class ENUM_MAP KEY_ENUM_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE
/** 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 * Default Constructor
* @param keyType the type of Enum that should be used * @param keyType the type of Enum that should be used
@@ -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();
@@ -91,9 +180,22 @@ public class ENUM_MAP KEY_ENUM_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE
return getDefaultReturnValue(); return getDefaultReturnValue();
} }
@Override
public VALUE_TYPE subFrom(T key, VALUE_TYPE value) {
int index = key.ordinal();
if(!isSet(index)) return getDefaultReturnValue();
VALUE_TYPE oldValue = values[index];
values[index] -= value;
if(value < 0 ? (values[index] >= getDefaultReturnValue()) : (values[index] <= getDefaultReturnValue())) {
clear(index);
values[index] = EMPTY_VALUE;
}
return oldValue;
}
#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 +203,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 +211,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 +238,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 +271,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 +279,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 +287,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 +320,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,24 +481,39 @@ 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(); protected static <K extends Enum<K>> K[] getKeyUniverse(Class<K> keyType) {
return SharedSecrets.getJavaLangAccess().getEnumConstantsShared(keyType); return keyType.getEnumConstants();
} }
class EntrySet extends AbstractObjectSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> { class EntrySet extends AbstractObjectSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> {
@Override @Override
public boolean contains(Object o) { public boolean contains(Object o) {
if(o instanceof Map.Entry) return containsKey(((Map.Entry<?, ?>)o).getKey()); if(o instanceof Map.Entry) {
if(o instanceof MAP.Entry) {
MAP.Entry KEY_VALUE_GENERIC_TYPE entry = (MAP.Entry KEY_VALUE_GENERIC_TYPE)o;
if(!keyType.isInstance(entry.ENTRY_KEY())) return false;
int index = ((T)entry.ENTRY_KEY()).ordinal();
if(index >= 0 && ENUM_MAP.this.isSet(index)) return VALUE_EQUALS(entry.ENTRY_VALUE(), ENUM_MAP.this.values[index]);
}
else {
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; return false;
} }
@@ -306,8 +609,7 @@ public class ENUM_MAP KEY_ENUM_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE
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]);
} }
} }
@@ -342,13 +644,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]);
} }
} }
} }
@@ -0,0 +1,965 @@
package speiger.src.collections.PACKAGE.maps.impl.misc;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.function.Consumer;
#if TYPE_OBJECT
import java.util.Objects;
#endif
import speiger.src.collections.PACKAGE.collections.BI_ITERATOR;
#if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.functions.CONSUMER;
#endif
import speiger.src.collections.PACKAGE.functions.consumer.BI_CONSUMER;
import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR;
import speiger.src.collections.PACKAGE.maps.interfaces.MAP;
import speiger.src.collections.PACKAGE.maps.interfaces.ORDERED_MAP;
import speiger.src.collections.PACKAGE.sets.ABSTRACT_SET;
import speiger.src.collections.PACKAGE.sets.ORDERED_SET;
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_COLLECTION;
import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ITERATOR;
#if !VALUE_OBJECT && !SAME_TYPE
import speiger.src.collections.VALUE_PACKAGE.functions.VALUE_CONSUMER;
import speiger.src.collections.VALUE_PACKAGE.lists.VALUE_LIST_ITERATOR;
#endif
#if !TYPE_OBJECT
import speiger.src.collections.objects.collections.ObjectBidirectionalIterator;
import speiger.src.collections.objects.lists.ObjectListIterator;
import speiger.src.collections.objects.sets.AbstractObjectSet;
import speiger.src.collections.objects.sets.ObjectSet;
#endif
/**
* A Type Specific LinkedEnumMap implementation that allows for Primitive Values and faster iteration.
* Unlike javas implementation this one does not jump around between a single long or long array implementation based around the enum size
* This will cause a bit more memory usage but allows for a simpler implementation.
* @Type(T)
* @ValueType(V)
*/
public class LINKED_ENUM_MAP KEY_ENUM_VALUE_GENERIC_TYPE extends ENUM_MAP KEY_VALUE_GENERIC_TYPE implements ORDERED_MAP KEY_VALUE_GENERIC_TYPE
{
/** The Backing array for links between nodes. Left 32 Bits => Previous Entry, Right 32 Bits => Next Entry */
protected long[] links;
/** The First Index in the Map */
protected int firstIndex = -1;
/** The Last Index in the Map */
protected int lastIndex = -1;
/**
* Default Constructor
* @param keyType the type of Enum that should be used
*/
public LINKED_ENUM_MAP(Class<T> keyType) {
super(keyType);
links = new long[keys.length];
}
#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 LINKED_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];
links = new long[keys.length];
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 LINKED_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];
links = new long[keys.length];
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 LINKED_ENUM_MAP(Map<? extends CLASS_TYPE, ? extends CLASS_VALUE_TYPE> map) {
if(map instanceof LINKED_ENUM_MAP) {
LINKED_ENUM_MAP KEY_VALUE_GENERIC_TYPE enumMap = (LINKED_ENUM_MAP KEY_VALUE_GENERIC_TYPE)map;
keyType = enumMap.keyType;
keys = enumMap.keys;
values = enumMap.values.clone();
present = enumMap.present.clone();
links = enumMap.links.clone();
size = enumMap.size;
}
else 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();
links = new long[keys.length];
for(int i = 0,m=keys.length;i<m;i++) {
if(isSet(i)) {
if(size == 0) {
firstIndex = lastIndex = i;
links[i] = -1L;
}
else {
links[lastIndex] ^= ((links[lastIndex] ^ (i & 0xFFFFFFFFL)) & 0xFFFFFFFFL);
links[i] = ((lastIndex & 0xFFFFFFFFL) << 32) | 0xFFFFFFFFL;
lastIndex = i;
}
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];
links = new long[keys.length];
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 LINKED_ENUM_MAP(MAP KEY_VALUE_GENERIC_TYPE map) {
if(map instanceof LINKED_ENUM_MAP) {
LINKED_ENUM_MAP KEY_VALUE_GENERIC_TYPE enumMap = (LINKED_ENUM_MAP KEY_VALUE_GENERIC_TYPE)map;
keyType = enumMap.keyType;
keys = enumMap.keys;
values = enumMap.values.clone();
present = enumMap.present.clone();
links = enumMap.links.clone();
size = enumMap.size;
}
else 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();
links = new long[keys.length];
for(int i = 0,m=keys.length;i<m;i++) {
if(isSet(i)) {
if(size == 0) {
firstIndex = lastIndex = i;
links[i] = -1L;
}
else {
links[lastIndex] ^= ((links[lastIndex] ^ (i & 0xFFFFFFFFL)) & 0xFFFFFFFFL);
links[i] = ((lastIndex & 0xFFFFFFFFL) << 32) | 0xFFFFFFFFL;
lastIndex = i;
}
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];
links = new long[keys.length];
putAll(map);
}
}
@Override
public VALUE_TYPE putAndMoveToFirst(T key, VALUE_TYPE value) {
int index = key.ordinal();
if(isSet(index)) {
VALUE_TYPE result = values[index];
values[index] = value;
moveToFirstIndex(index);
return result;
}
set(index);
values[index] = value;
onNodeAdded(index);
moveToFirstIndex(index);
return getDefaultReturnValue();
}
@Override
public VALUE_TYPE putAndMoveToLast(T key, VALUE_TYPE value) {
int index = key.ordinal();
if(isSet(index)) {
VALUE_TYPE result = values[index];
values[index] = value;
moveToLastIndex(index);
return result;
}
set(index);
values[index] = value;
onNodeAdded(index);
moveToLastIndex(index);
return getDefaultReturnValue();
}
@Override
public boolean moveToFirst(T key) {
int index = key.ordinal();
if(isSet(index)) {
moveToFirstIndex(index);
return true;
}
return false;
}
@Override
public boolean moveToLast(T key) {
int index = key.ordinal();
if(isSet(index)) {
moveToLastIndex(index);
return true;
}
return false;
}
@Override
public VALUE_TYPE getAndMoveToFirst(T key) {
int index = key.ordinal();
if(index < 0) return getDefaultReturnValue();
moveToFirstIndex(index);
return values[index];
}
@Override
public VALUE_TYPE getAndMoveToLast(T key) {
int index = key.ordinal();
if(index < 0) return getDefaultReturnValue();
moveToLastIndex(index);
return values[index];
}
@Override
public LINKED_ENUM_MAP KEY_VALUE_GENERIC_TYPE copy() {
LINKED_ENUM_MAP KEY_VALUE_GENERIC_TYPE map = new LINKED_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));
System.arraycopy(links, 0, map.links, 0, Math.min(links.length, map.links.length));
map.firstIndex = firstIndex;
map.lastIndex = lastIndex;
return map;
}
@Override
public T FIRST_ENTRY_KEY() {
if(size == 0) throw new NoSuchElementException();
return keys[firstIndex];
}
@Override
public T POLL_FIRST_ENTRY_KEY() {
if(size == 0) throw new NoSuchElementException();
int pos = firstIndex;
firstIndex = (int)links[pos];
if(0 <= firstIndex) links[firstIndex] |= 0xFFFFFFFF00000000L;
T result = keys[pos];
size--;
values[result.ordinal()] = EMPTY_VALUE;
return result;
}
@Override
public T LAST_ENTRY_KEY() {
if(size == 0) throw new NoSuchElementException();
return keys[lastIndex];
}
@Override
public T POLL_LAST_ENTRY_KEY() {
if(size == 0) throw new NoSuchElementException();
int pos = lastIndex;
lastIndex = (int)(links[pos] >>> 32);
if(0 <= lastIndex) links[lastIndex] |= 0xFFFFFFFFL;
T result = keys[pos];
size--;
values[result.ordinal()] = EMPTY_VALUE;
return result;
}
@Override
public VALUE_TYPE FIRST_ENTRY_VALUE() {
if(size == 0) throw new NoSuchElementException();
return values[firstIndex];
}
@Override
public VALUE_TYPE LAST_ENTRY_VALUE() {
if(size == 0) throw new NoSuchElementException();
return values[lastIndex];
}
@Override
public ObjectSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> ENTRY_SET() {
if(entrySet == null) entrySet = new MapEntrySet();
return entrySet;
}
@Override
public SET KEY_GENERIC_TYPE keySet() {
if(keySet == null) keySet = new KeySet();
return keySet;
}
@Override
public VALUE_COLLECTION VALUE_GENERIC_TYPE values() {
if(valuesC == null) valuesC = new Values();
return valuesC;
}
@Override
public void forEach(BI_CONSUMER KEY_VALUE_GENERIC_TYPE action) {
int index = firstIndex;
while(index != -1){
action.accept(keys[index], values[index]);
index = (int)links[index];
}
}
@Override
public void clear() {
super.clear();
firstIndex = lastIndex = -1;
}
protected void moveToFirstIndex(int startPos) {
if(size == 1 || firstIndex == startPos) return;
if(lastIndex == startPos) {
lastIndex = (int)(links[startPos] >>> 32);
links[lastIndex] |= 0xFFFFFFFFL;
}
else {
long link = links[startPos];
int prev = (int)(link >>> 32);
int next = (int)link;
links[prev] ^= ((links[prev] ^ (link & 0xFFFFFFFFL)) & 0xFFFFFFFFL);
links[next] ^= ((links[next] ^ (link & 0xFFFFFFFF00000000L)) & 0xFFFFFFFF00000000L);
}
links[firstIndex] ^= ((links[firstIndex] ^ ((startPos & 0xFFFFFFFFL) << 32)) & 0xFFFFFFFF00000000L);
links[startPos] = 0xFFFFFFFF00000000L | (firstIndex & 0xFFFFFFFFL);
firstIndex = startPos;
}
protected void moveToLastIndex(int startPos) {
if(size == 1 || lastIndex == startPos) return;
if(firstIndex == startPos) {
firstIndex = (int)links[startPos];
links[lastIndex] |= 0xFFFFFFFF00000000L;
}
else {
long link = links[startPos];
int prev = (int)(link >>> 32);
int next = (int)link;
links[prev] ^= ((links[prev] ^ (link & 0xFFFFFFFFL)) & 0xFFFFFFFFL);
links[next] ^= ((links[next] ^ (link & 0xFFFFFFFF00000000L)) & 0xFFFFFFFF00000000L);
}
links[lastIndex] ^= ((links[lastIndex] ^ (startPos & 0xFFFFFFFFL)) & 0xFFFFFFFFL);
links[startPos] = ((lastIndex & 0xFFFFFFFFL) << 32) | 0xFFFFFFFFL;
lastIndex = startPos;
}
@Override
protected void onNodeAdded(int pos) {
if(size == 0) {
firstIndex = lastIndex = pos;
links[pos] = -1L;
}
else {
links[lastIndex] ^= ((links[lastIndex] ^ (pos & 0xFFFFFFFFL)) & 0xFFFFFFFFL);
links[pos] = ((lastIndex & 0xFFFFFFFFL) << 32) | 0xFFFFFFFFL;
lastIndex = pos;
}
}
@Override
protected void onNodeRemoved(int pos) {
if(size == 0) firstIndex = lastIndex = -1;
else if(firstIndex == pos) {
firstIndex = (int)links[pos];
if(0 <= firstIndex) links[firstIndex] |= 0xFFFFFFFF00000000L;
}
else if(lastIndex == pos) {
lastIndex = (int)(links[pos] >>> 32);
if(0 <= lastIndex) links[lastIndex] |= 0xFFFFFFFFL;
}
else {
long link = links[pos];
int prev = (int)(link >>> 32);
int next = (int)link;
links[prev] ^= ((links[prev] ^ (link & 0xFFFFFFFFL)) & 0xFFFFFFFFL);
links[next] ^= ((links[next] ^ (link & 0xFFFFFFFF00000000L)) & 0xFFFFFFFF00000000L);
}
}
private class MapEntrySet extends AbstractObjectSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> implements ORDERED_MAP.FastOrderedSet KEY_VALUE_GENERIC_TYPE {
@Override
public boolean addAndMoveToFirst(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); }
@Override
public boolean addAndMoveToLast(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); }
@Override
public boolean moveToFirst(MAP.Entry KEY_VALUE_GENERIC_TYPE o) {
return LINKED_ENUM_MAP.this.moveToFirst(o.ENTRY_KEY());
}
@Override
public boolean moveToLast(MAP.Entry KEY_VALUE_GENERIC_TYPE o) {
return LINKED_ENUM_MAP.this.moveToLast(o.ENTRY_KEY());
}
@Override
public MAP.Entry KEY_VALUE_GENERIC_TYPE first() {
return new BasicEntryKV_BRACES(FIRST_ENTRY_KEY(), FIRST_ENTRY_VALUE());
}
@Override
public MAP.Entry KEY_VALUE_GENERIC_TYPE last() {
return new BasicEntryKV_BRACES(LAST_ENTRY_KEY(), LAST_ENTRY_VALUE());
}
@Override
public MAP.Entry KEY_VALUE_GENERIC_TYPE pollFirst() {
BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(FIRST_ENTRY_KEY(), FIRST_ENTRY_VALUE());
POLL_FIRST_ENTRY_KEY();
return entry;
}
@Override
public MAP.Entry KEY_VALUE_GENERIC_TYPE pollLast() {
BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(LAST_ENTRY_KEY(), LAST_ENTRY_VALUE());
POLL_LAST_ENTRY_KEY();
return entry;
}
@Override
public ObjectBidirectionalIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> iterator() {
return new EntryIterator();
}
@Override
public ObjectBidirectionalIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> iterator(MAP.Entry KEY_VALUE_GENERIC_TYPE fromElement) {
return new EntryIterator(fromElement.ENTRY_KEY());
}
@Override
public ObjectBidirectionalIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> fastIterator() {
return new FastEntryIterator();
}
@Override
public ObjectBidirectionalIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> fastIterator(T fromElement) {
return new FastEntryIterator(fromElement);
}
public MapEntrySet copy() { throw new UnsupportedOperationException(); }
@Override
public void forEach(Consumer<? super MAP.Entry KEY_VALUE_GENERIC_TYPE> action) {
int index = firstIndex;
while(index != -1){
action.accept(new BasicEntryKV_BRACES(keys[index], values[index]));
index = (int)links[index];
}
}
@Override
public void fastForEach(Consumer<? super MAP.Entry KEY_VALUE_GENERIC_TYPE> action) {
BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES();
int index = firstIndex;
while(index != -1){
entry.set(keys[index], values[index]);
action.accept(entry);
index = (int)links[index];
}
}
@Override
@Deprecated
public boolean contains(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;
if(!keyType.isInstance(entry.ENTRY_KEY())) return false;
int index = ((T)entry.ENTRY_KEY()).ordinal();
if(index >= 0 && LINKED_ENUM_MAP.this.isSet(index)) return VALUE_EQUALS(entry.ENTRY_VALUE(), LINKED_ENUM_MAP.this.values[index]);
}
else {
Map.Entry<?, ?> entry = (Map.Entry<?, ?>)o;
if(!keyType.isInstance(entry.getKey())) return false;
int index = ((T)entry.getKey()).ordinal();
if(index >= 0 && LINKED_ENUM_MAP.this.isSet(index)) return Objects.equals(entry.getValue(), VALUE_TO_OBJ(LINKED_ENUM_MAP.this.values[index]));
}
}
return false;
}
@Override
@Deprecated
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 LINKED_ENUM_MAP.this.remove(entry.ENTRY_KEY(), entry.ENTRY_VALUE());
}
Map.Entry<?, ?> entry = (Map.Entry<?, ?>)o;
return LINKED_ENUM_MAP.this.remove(entry.getKey(), entry.getValue());
}
return false;
}
@Override
public int size() {
return LINKED_ENUM_MAP.this.size();
}
@Override
public void clear() {
LINKED_ENUM_MAP.this.clear();
}
}
private final class KeySet extends ABSTRACT_SET KEY_GENERIC_TYPE implements ORDERED_SET KEY_GENERIC_TYPE {
#if TYPE_OBJECT
@Override
@Deprecated
public boolean contains(Object e) {
return containsKey(e);
}
@Override
public boolean remove(Object o) {
int oldSize = size;
LINKED_ENUM_MAP.this.remove(o);
return size != oldSize;
}
#else
@Override
public boolean contains(T e) {
return containsKey(e);
}
@Override
public boolean remove(T o) {
int oldSize = size;
LINKED_ENUM_MAP.this.remove(o);
return size != oldSize;
}
#endif
@Override
public boolean add(T o) {
throw new UnsupportedOperationException();
}
@Override
public boolean addAndMoveToFirst(T o) { throw new UnsupportedOperationException(); }
@Override
public boolean addAndMoveToLast(T o) { throw new UnsupportedOperationException(); }
@Override
public boolean moveToFirst(T o) {
return LINKED_ENUM_MAP.this.moveToFirst(o);
}
@Override
public boolean moveToLast(T o) {
return LINKED_ENUM_MAP.this.moveToLast(o);
}
@Override
public LIST_ITERATOR KEY_GENERIC_TYPE iterator() {
return new KeyIterator();
}
@Override
public BI_ITERATOR KEY_GENERIC_TYPE iterator(T fromElement) {
return new KeyIterator(fromElement);
}
public KeySet copy() { throw new UnsupportedOperationException(); }
@Override
public int size() {
return LINKED_ENUM_MAP.this.size();
}
@Override
public void clear() {
LINKED_ENUM_MAP.this.clear();
}
@Override
public T FIRST_KEY() {
return FIRST_ENTRY_KEY();
}
@Override
public T POLL_FIRST_KEY() {
return POLL_FIRST_ENTRY_KEY();
}
@Override
public T LAST_KEY() {
return LAST_ENTRY_KEY();
}
@Override
public T POLL_LAST_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
public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) {
int index = firstIndex;
while(index != -1){
action.accept(keys[index]);
index = (int)links[index];
}
}
#endif
}
private class Values extends VALUE_ABSTRACT_COLLECTION VALUE_GENERIC_TYPE {
#if VALUE_OBJECT
@Override
@Deprecated
public boolean contains(Object e) {
return containsValue(e);
}
#else
@Override
public boolean contains(VALUE_TYPE e) {
return containsValue(e);
}
#endif
@Override
public boolean add(VALUE_TYPE o) {
throw new UnsupportedOperationException();
}
@Override
public VALUE_ITERATOR VALUE_GENERIC_TYPE iterator() {
return new ValueIterator();
}
@Override
public int size() {
return LINKED_ENUM_MAP.this.size();
}
@Override
public void clear() {
LINKED_ENUM_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
public void forEach(VALUE_CONSUMER VALUE_SUPER_GENERIC_TYPE action) {
int index = firstIndex;
while(index != -1){
action.accept(values[index]);
index = (int)links[index];
}
}
#endif
}
private class FastEntryIterator extends MapIterator implements ObjectListIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> {
MapEntry entry = new MapEntry();
public FastEntryIterator() {}
public FastEntryIterator(T from) {
super(from);
}
@Override
public MAP.Entry KEY_VALUE_GENERIC_TYPE next() {
entry.index = nextEntry();
return entry;
}
@Override
public MAP.Entry KEY_VALUE_GENERIC_TYPE previous() {
entry.index = previousEntry();
return entry;
}
@Override
public void set(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { throw new UnsupportedOperationException(); }
@Override
public void add(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { throw new UnsupportedOperationException(); }
}
private class EntryIterator extends MapIterator implements ObjectListIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> {
MapEntry entry;
public EntryIterator() {}
public EntryIterator(T from) {
super(from);
}
@Override
public MAP.Entry KEY_VALUE_GENERIC_TYPE next() {
return entry = new MapEntry(nextEntry());
}
@Override
public MAP.Entry KEY_VALUE_GENERIC_TYPE previous() {
return entry = new MapEntry(previousEntry());
}
@Override
public void remove() {
super.remove();
entry.index = -1;
}
@Override
public void set(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { throw new UnsupportedOperationException(); }
@Override
public void add(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { throw new UnsupportedOperationException(); }
}
private class KeyIterator extends MapIterator implements LIST_ITERATOR KEY_GENERIC_TYPE {
public KeyIterator() {}
public KeyIterator(T from) {
super(from);
}
@Override
public T PREVIOUS() {
return keys[previousEntry()];
}
@Override
public T NEXT() {
return keys[nextEntry()];
}
@Override
public void set(T e) { throw new UnsupportedOperationException(); }
@Override
public void add(T e) { throw new UnsupportedOperationException(); }
}
private class ValueIterator extends MapIterator implements VALUE_LIST_ITERATOR VALUE_GENERIC_TYPE {
public ValueIterator() {}
@Override
public VALUE_TYPE VALUE_PREVIOUS() {
return values[previousEntry()];
}
@Override
public VALUE_TYPE VALUE_NEXT() {
return values[nextEntry()];
}
@Override
public void set(VALUE_TYPE e) { throw new UnsupportedOperationException(); }
@Override
public void add(VALUE_TYPE e) { throw new UnsupportedOperationException(); }
}
private class MapIterator {
int previous = -1;
int next = -1;
int current = -1;
int index = 0;
MapIterator() {
next = firstIndex;
}
MapIterator(T from) {
previous = from.ordinal() - 1;
index = from.ordinal();
next = from.ordinal();
}
public boolean hasNext() {
return next != -1;
}
public boolean hasPrevious() {
return previous != -1;
}
public int nextIndex() {
ensureIndexKnown();
return index;
}
public int previousIndex() {
ensureIndexKnown();
return index - 1;
}
public void remove() {
if(current == -1) throw new IllegalStateException();
ensureIndexKnown();
if(current == previous) {
index--;
previous = (int)(links[current] >>> 32);
}
else next = (int)links[current];
size--;
if(previous == -1) firstIndex = next;
else links[previous] ^= ((links[previous] ^ (next & 0xFFFFFFFFL)) & 0xFFFFFFFFL);
if (next == -1) lastIndex = previous;
else links[next] ^= ((links[next] ^ ((previous & 0xFFFFFFFFL) << 32)) & 0xFFFFFFFF00000000L);
values[current] = EMPTY_VALUE;
present[current >> 6] &= ~(1L << current);
current = -1;
}
public int previousEntry() {
if(!hasPrevious()) throw new NoSuchElementException();
current = previous;
previous = (int)(links[current] >> 32);
next = current;
if(index >= 0) index--;
return current;
}
public int nextEntry() {
if(!hasNext()) throw new NoSuchElementException();
current = next;
next = (int)(links[current]);
previous = current;
if(index >= 0) index++;
return 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++);
}
}
}
}
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]);
}
}
}
@@ -0,0 +1,95 @@
package speiger.src.collections.PACKAGE.maps.interfaces;
import java.util.concurrent.ConcurrentMap;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Function;
/**
* A type specific ConcurrentMap interface that reduces boxing/unboxing.
* Since the interface adds nothing new. It is there just for completion sake.
* @Type(T)
* @ValueType(V)
*/
public interface CONCURRENT_MAP KEY_VALUE_GENERIC_TYPE extends ConcurrentMap<CLASS_TYPE, CLASS_VALUE_TYPE>, MAP KEY_VALUE_GENERIC_TYPE
{
@Override
@Primitive
public default CLASS_VALUE_TYPE compute(CLASS_TYPE key, BiFunction<? super CLASS_TYPE, ? super CLASS_VALUE_TYPE, ? extends CLASS_VALUE_TYPE> mappingFunction) {
return MAP.super.compute(key, mappingFunction);
}
@Override
@Primitive
public default CLASS_VALUE_TYPE computeIfAbsent(CLASS_TYPE key, Function<? super CLASS_TYPE, ? extends CLASS_VALUE_TYPE> mappingFunction) {
return MAP.super.computeIfAbsent(key, mappingFunction);
}
@Override
@Primitive
public default CLASS_VALUE_TYPE computeIfPresent(CLASS_TYPE key, BiFunction<? super CLASS_TYPE, ? super CLASS_VALUE_TYPE, ? extends CLASS_VALUE_TYPE> mappingFunction) {
return MAP.super.computeIfPresent(key, mappingFunction);
}
@Override
@Primitive
public default void forEach(BiConsumer<? super CLASS_TYPE, ? super CLASS_VALUE_TYPE> action) {
MAP.super.forEach(action);
}
@Override
@Primitive
public default CLASS_VALUE_TYPE merge(CLASS_TYPE key, CLASS_VALUE_TYPE value, BiFunction<? super CLASS_VALUE_TYPE, ? super CLASS_VALUE_TYPE, ? extends CLASS_VALUE_TYPE> mappingFunction) {
return MAP.super.merge(key, value, mappingFunction);
}
#if TYPE_OBJECT && VALUE_OBJECT
@Override
public CLASS_VALUE_TYPE getOrDefault(Object key, CLASS_VALUE_TYPE defaultValue);
@Override
public CLASS_VALUE_TYPE putIfAbsent(CLASS_TYPE key, CLASS_VALUE_TYPE value);
@Override
public boolean remove(Object key, Object value);
@Override
public boolean replace(CLASS_TYPE key, CLASS_VALUE_TYPE oldValue, CLASS_VALUE_TYPE newValue);
@Override
public CLASS_VALUE_TYPE replace(CLASS_TYPE key, CLASS_VALUE_TYPE value);
#else
@Primitive
@Override
public default CLASS_VALUE_TYPE getOrDefault(Object key, CLASS_VALUE_TYPE defaultValue) {
return MAP.super.getOrDefault(key, defaultValue);
}
@Override
@Primitive
public default CLASS_VALUE_TYPE putIfAbsent(CLASS_TYPE key, CLASS_VALUE_TYPE value) {
return MAP.super.putIfAbsent(key, value);
}
@Override
@Deprecated
public default boolean remove(Object key, Object value) {
return MAP.super.remove(key, value);
}
@Override
@Deprecated
public default boolean replace(CLASS_TYPE key, CLASS_VALUE_TYPE oldValue, CLASS_VALUE_TYPE newValue) {
return MAP.super.replace(key, oldValue, newValue);
}
@Override
@Deprecated
public default CLASS_VALUE_TYPE replace(CLASS_TYPE key, CLASS_VALUE_TYPE value) {
return MAP.super.replace(key, value);
}
#endif
@Override
@Deprecated
public default void replaceAll(BiFunction<? super CLASS_TYPE, ? super CLASS_VALUE_TYPE, ? extends CLASS_VALUE_TYPE> mappingFunction) {
MAP.super.replaceAll(mappingFunction);
}
}
@@ -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
@@ -182,13 +207,13 @@ public interface NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE extends SORTED_MAP KEY_VAL
default NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE tailMap(CLASS_TYPE fromKey) { return tailMap(OBJ_TO_KEY(fromKey), true); } default NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE tailMap(CLASS_TYPE fromKey) { return tailMap(OBJ_TO_KEY(fromKey), true); }
#else #else
@Override @Override
default MAP.Entry KEY_VALUE_GENERIC_TYPE lowerEntry(CLASS_TYPE key) { return lowerEntry(OBJ_TO_KEY(key)); } MAP.Entry KEY_VALUE_GENERIC_TYPE lowerEntry(CLASS_TYPE key);
@Override @Override
default MAP.Entry KEY_VALUE_GENERIC_TYPE floorEntry(CLASS_TYPE key) { return floorEntry(OBJ_TO_KEY(key)); } MAP.Entry KEY_VALUE_GENERIC_TYPE floorEntry(CLASS_TYPE key);
@Override @Override
default MAP.Entry KEY_VALUE_GENERIC_TYPE ceilingEntry(CLASS_TYPE key) { return ceilingEntry(OBJ_TO_KEY(key)); } MAP.Entry KEY_VALUE_GENERIC_TYPE ceilingEntry(CLASS_TYPE key);
@Override @Override
default MAP.Entry KEY_VALUE_GENERIC_TYPE higherEntry(CLASS_TYPE key) { return higherEntry(OBJ_TO_KEY(key)); } MAP.Entry KEY_VALUE_GENERIC_TYPE higherEntry(CLASS_TYPE key);
@Override @Override
public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE subMap(CLASS_TYPE fromKey, boolean fromInclusive, CLASS_TYPE toKey, boolean toInclusive); public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE subMap(CLASS_TYPE fromKey, boolean fromInclusive, CLASS_TYPE toKey, boolean toInclusive);
@@ -0,0 +1,138 @@
package speiger.src.collections.PACKAGE.maps.interfaces;
import speiger.src.collections.PACKAGE.utils.maps.MAPS;
import speiger.src.collections.objects.collections.ObjectBidirectionalIterator;
import speiger.src.collections.objects.sets.ObjectOrderedSet;
/**
* A Special Map Interface giving Access to some really usefull functions
* The Idea behind this interface is to allow access to functions that give control to the Order of elements.
* Since Linked implementations as examples can be reordered outside of the Insertion Order.
* This interface provides basic access to such functions while also providing some Sorted/NaivgableMap implementations that still fit into here.
*
* @Type(T)
* @ValueType(V)
*/
public interface ORDERED_MAP KEY_VALUE_GENERIC_TYPE extends MAP KEY_VALUE_GENERIC_TYPE
{
/**
* A customized put method that allows you to insert into the first index.
* @param key the key that should be inserted
* @param value the value that should be inserted
* @return the previous present or default return value
* @see java.util.Map#put(Object, Object)
*/
public VALUE_TYPE putAndMoveToFirst(KEY_TYPE key, VALUE_TYPE value);
/**
* A customized put method that allows you to insert into the last index. (This may be nessesary depending on the implementation)
* @param key the key that should be inserted
* @param value the value that should be inserted
* @return the previous present or default return value
* @see java.util.Map#put(Object, Object)
*/
public VALUE_TYPE putAndMoveToLast(KEY_TYPE key, VALUE_TYPE value);
/**
* A specific move method to move a given key/value to the first index.
* @param key that should be moved to the first index
* @return true if the value was moved.
* @note returns false if the value was not present in the first place
*/
public boolean moveToFirst(KEY_TYPE key);
/**
* A specific move method to move a given key/value to the last index.
* @param key that should be moved to the first last
* @return true if the value was moved.
* @note returns false if the value was not present in the first place
*/
public boolean moveToLast(KEY_TYPE key);
/**
* A Specific get method that allows to move teh given key/value int the first index.
* @param key that is searched for
* @return the given value for the requested key or default return value
*/
public VALUE_TYPE getAndMoveToFirst(KEY_TYPE key);
/**
* A Specific get method that allows to move teh given key/value int the last index.
* @param key that is searched for
* @return the given value for the requested key or default return value
*/
public VALUE_TYPE getAndMoveToLast(KEY_TYPE key);
/**
* A method to get the first Key of a Map.
* @return the first key in the map
*/
public KEY_TYPE FIRST_ENTRY_KEY();
/**
* A method to get and remove the first Key of a Map.
* @return the first key in the map
*/
public KEY_TYPE POLL_FIRST_ENTRY_KEY();
/**
* A method to get the last Key of a Map.
* @return the last key in the map
*/
public KEY_TYPE LAST_ENTRY_KEY();
/**
* A method to get and remove the last Key of a Map.
* @return the last key in the map
*/
public KEY_TYPE POLL_LAST_ENTRY_KEY();
/**
* A method to get the first Value of a Map.
* @return the first key in the map
*/
public VALUE_TYPE FIRST_ENTRY_VALUE();
/**
* A method to get the last Value of a Map.
* @return the last key in the map
*/
public VALUE_TYPE LAST_ENTRY_VALUE();
@Override
public ORDERED_MAP KEY_VALUE_GENERIC_TYPE copy();
/**
* Creates a Wrapped SortedMap that is Synchronized
* @return a new SortedMap that is synchronized
* @see MAPS#synchronize
*/
@Override
public default ORDERED_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
*/
@Override
public default ORDERED_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
*/
@Override
public default ORDERED_MAP KEY_VALUE_GENERIC_TYPE unmodifiable() { return MAPS.unmodifiable(this); }
/**
* Fast Ordered Entry Set that allows for a faster Entry Iterator by recycling the Entry Object and just exchanging 1 internal value
* @Type(T)
* @ValueType(V)
*/
interface FastOrderedSet KEY_VALUE_GENERIC_TYPE extends MAP.FastEntrySet KEY_VALUE_GENERIC_TYPE, ObjectOrderedSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> {
@Override
public ObjectBidirectionalIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> fastIterator();
/**
* Fast iterator that recycles the given Entry object to improve speed and reduce object allocation
* @param fromElement that is going to be started from.
* @return a improved iterator that starts from the desired element
*/
public ObjectBidirectionalIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> fastIterator(KEY_TYPE fromElement);
}
}
@@ -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;
@@ -18,68 +19,44 @@ import speiger.src.collections.objects.collections.ObjectBidirectionalIterator;
* *
* @Type(T) * @Type(T)
* @ValueType(V) * @ValueType(V)
* @note ORDERED_MAP is only extended until 0.6.0 for Compat reasons.
* The supported classes already implement ORDERED_MAP directly and will remove SORTED_MAP implementations in favor of ORDERED_MAP instead
*/ */
public interface SORTED_MAP KEY_VALUE_GENERIC_TYPE extends SortedMap<CLASS_TYPE, CLASS_VALUE_TYPE>, MAP KEY_VALUE_GENERIC_TYPE public interface SORTED_MAP KEY_VALUE_GENERIC_TYPE extends SortedMap<CLASS_TYPE, CLASS_VALUE_TYPE>, MAP KEY_VALUE_GENERIC_TYPE
{ {
/**
* A customized put method that allows you to insert into the first index.
* @param key the key that should be inserted
* @param value the value that should be inserted
* @return the previous present or default return value
* @see java.util.Map#put(Object, Object)
* @note some implementations do not support this method
*/
public VALUE_TYPE putAndMoveToFirst(KEY_TYPE key, VALUE_TYPE value);
/**
* A customized put method that allows you to insert into the last index. (This may be nessesary depending on the implementation)
* @param key the key that should be inserted
* @param value the value that should be inserted
* @return the previous present or default return value
* @see java.util.Map#put(Object, Object)
* @note some implementations do not support this method
*/
public VALUE_TYPE putAndMoveToLast(KEY_TYPE key, VALUE_TYPE value);
/**
* A specific move method to move a given key/value to the first index.
* @param key that should be moved to the first index
* @return true if the value was moved.
* @note returns false if the value was not present in the first place
* @note some implementations do not support this method
*/
public boolean moveToFirst(KEY_TYPE key);
/**
* A specific move method to move a given key/value to the last index.
* @param key that should be moved to the first last
* @return true if the value was moved.
* @note returns false if the value was not present in the first place
* @note some implementations do not support this method
*/
public boolean moveToLast(KEY_TYPE key);
/**
* A Specific get method that allows to move teh given key/value int the first index.
* @param key that is searched for
* @return the given value for the requested key or default return value
* @note some implementations do not support this method
*/
public VALUE_TYPE getAndMoveToFirst(KEY_TYPE key);
/**
* A Specific get method that allows to move teh given key/value int the last index.
* @param key that is searched for
* @return the given value for the requested key or default return value
* @note some implementations do not support this method
*/
public VALUE_TYPE getAndMoveToLast(KEY_TYPE key);
@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
@@ -193,6 +170,11 @@ public interface SORTED_MAP KEY_VALUE_GENERIC_TYPE extends SortedMap<CLASS_TYPE,
interface FastSortedSet KEY_VALUE_GENERIC_TYPE extends MAP.FastEntrySet KEY_VALUE_GENERIC_TYPE, ObjectSortedSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> { interface FastSortedSet KEY_VALUE_GENERIC_TYPE extends MAP.FastEntrySet KEY_VALUE_GENERIC_TYPE, ObjectSortedSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> {
@Override @Override
public ObjectBidirectionalIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> fastIterator(); public ObjectBidirectionalIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> fastIterator();
/**
* Fast iterator that recycles the given Entry object to improve speed and reduce object allocation
* @param fromElement that is going to be started from.
* @return a improved iterator that starts from the desired element
*/
public ObjectBidirectionalIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> fastIterator(KEY_TYPE fromElement); public ObjectBidirectionalIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> fastIterator(KEY_TYPE fromElement);
} }
} }
@@ -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,7 +24,7 @@ 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;
@@ -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+1));
minCapacity = array.length;
} }
/** /**
@@ -101,33 +113,33 @@ 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; if(last == array.length) last = 0;
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
array[first] = null; array[first] = null;
#endif #endif
first = ++first % array.length; if(++first == array.length) first = 0;
reduce(); reduce();
return data; return data;
} }
@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,14 @@ 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]; index += first;
return index > array.length ? array[index-array.length] : array[index];
} }
@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 +169,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 +230,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 +367,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 +394,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,15 +4,22 @@ 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;
import speiger.src.collections.utils.SanityChecks;
/** /**
* A Array Priority Queue, this is a very unoptimized implementation of the PriorityQueue for very specific usecases. * A Array Priority Queue, this is a very unoptimized implementation of the PriorityQueue for very specific usecases.
@@ -20,7 +27,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;
@@ -64,7 +71,6 @@ public class ARRAY_PRIORITY_QUEUE KEY_GENERIC_TYPE implements PRIORITY_QUEUE KEY
public ARRAY_PRIORITY_QUEUE(int size, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) { public ARRAY_PRIORITY_QUEUE(int size, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) {
if(size < 0) throw new IllegalAccessError("Size has to be 0 or positive"); if(size < 0) throw new IllegalAccessError("Size has to be 0 or positive");
if(size > 0) array = NEW_KEY_ARRAY(size); if(size > 0) array = NEW_KEY_ARRAY(size);
this.size = size;
comparator = comp; comparator = comp;
} }
@@ -180,8 +186,8 @@ 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, (int)Math.max(Math.min((long)array.length + (array.length >> 1), SanityChecks.MAX_ARRAY_SIZE), 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]);
if(compare < 0) firstIndex = size; if(compare < 0) firstIndex = size;
@@ -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,22 +4,29 @@ 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;
import speiger.src.collections.utils.SanityChecks;
/** /**
* A Simple Heap base Priority Queue implementation * A Simple Heap base Priority Queue implementation
* 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;
@@ -60,7 +67,6 @@ public class HEAP_PRIORITY_QUEUE KEY_GENERIC_TYPE implements PRIORITY_QUEUE KEY_
*/ */
public HEAP_PRIORITY_QUEUE(int size, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) { public HEAP_PRIORITY_QUEUE(int size, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) {
if(size > 0) array = NEW_KEY_ARRAY(size); if(size > 0) array = NEW_KEY_ARRAY(size);
this.size = size;
comparator = comp; comparator = comp;
} }
@@ -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, (int)Math.max(Math.min((long)array.length + (array.length >> 1), SanityChecks.MAX_ARRAY_SIZE), 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
} }
File diff suppressed because it is too large Load Diff
@@ -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;
@@ -13,15 +14,22 @@ import speiger.src.collections.PACKAGE.collections.ITERATOR;
*/ */
public abstract class ABSTRACT_SET KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION KEY_GENERIC_TYPE implements SET KEY_GENERIC_TYPE public abstract class ABSTRACT_SET KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION KEY_GENERIC_TYPE implements SET KEY_GENERIC_TYPE
{ {
#if TYPE_OBJECT
@Override
public KEY_TYPE addOrGet(KEY_TYPE o) { throw new UnsupportedOperationException(); }
#endif
@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;
} }
@@ -33,24 +41,10 @@ public abstract class ABSTRACT_SET KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION
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();
ITERATOR e2 = ((SET)l).iterator();
while (e1.hasNext() && e2.hasNext()) {
if(!(KEY_EQUALS(e1.NEXT(), e2.NEXT())))
return false; 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());
} }
} }
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,579 @@
package speiger.src.collections.PACKAGE.sets;
#if TYPE_OBJECT
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.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 ORDERED_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(); }
#if TYPE_OBJECT
@Override
public KEY_TYPE addOrGet(KEY_TYPE o) { throw new UnsupportedOperationException(); }
#endif
@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 TYPE_OBJECT
if(o == null) return containsNull;
#else
if(o == null) return false;
if(o instanceof CLASS_TYPE && KEY_EQUALS(CLASS_TO_KEY(o), EMPTY_KEY_VALUE)) return containsNull;
#endif
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 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
}
}
@@ -1,8 +1,11 @@
package speiger.src.collections.PACKAGE.sets; package speiger.src.collections.PACKAGE.sets;
#if TYPE_OBJECT #if TYPE_OBJECT
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;
@@ -12,13 +15,14 @@ import speiger.src.collections.PACKAGE.collections.COLLECTION;
import speiger.src.collections.PACKAGE.collections.ITERATOR; import speiger.src.collections.PACKAGE.collections.ITERATOR;
#endif #endif
import speiger.src.collections.PACKAGE.collections.BI_ITERATOR; import speiger.src.collections.PACKAGE.collections.BI_ITERATOR;
#if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.functions.COMPARATOR;
#endif
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;
@@ -29,7 +33,7 @@ import speiger.src.collections.utils.SanityChecks;
* This implementation of SortedSet does not support SubSet of any kind. It implements the interface due to sortability and first/last access * This implementation of SortedSet does not support SubSet of any kind. It implements the interface due to sortability and first/last access
* @Type(T) * @Type(T)
*/ */
public class LINKED_CUSTOM_HASH_SET KEY_GENERIC_TYPE extends CUSTOM_HASH_SET KEY_GENERIC_TYPE implements SORTED_SET KEY_GENERIC_TYPE public class LINKED_CUSTOM_HASH_SET KEY_GENERIC_TYPE extends CUSTOM_HASH_SET KEY_GENERIC_TYPE implements ORDERED_SET KEY_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 transient long[] links; protected transient long[] links;
@@ -130,7 +134,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 +147,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 +428,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 +505,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();
@@ -512,16 +653,20 @@ public class LINKED_CUSTOM_HASH_SET KEY_GENERIC_TYPE extends CUSTOM_HASH_SET KEY
} }
@Override @Override
public COMPARATOR KEY_GENERIC_TYPE comparator() { return null; } 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);
@Override set.minCapacity = minCapacity;
public SORTED_SET KEY_GENERIC_TYPE subSet(KEY_TYPE fromElement, KEY_TYPE toElement) { throw new UnsupportedOperationException(); } set.mask = mask;
set.maxFill = maxFill;
@Override set.nullIndex = nullIndex;
public SORTED_SET KEY_GENERIC_TYPE headSet(KEY_TYPE toElement) { throw new UnsupportedOperationException(); } set.containsNull = containsNull;
set.size = size;
@Override set.keys = Arrays.copyOf(keys, keys.length);
public SORTED_SET KEY_GENERIC_TYPE tailSet(KEY_TYPE fromElement) { throw new UnsupportedOperationException(); } set.links = Arrays.copyOf(links, links.length);
set.firstIndex = firstIndex;
set.lastIndex = lastIndex;
return set;
}
private class SetIterator implements LIST_ITERATOR KEY_GENERIC_TYPE { private class SetIterator implements LIST_ITERATOR KEY_GENERIC_TYPE {
int previous = -1; int previous = -1;
@@ -1,13 +1,13 @@
package speiger.src.collections.PACKAGE.sets; package speiger.src.collections.PACKAGE.sets;
#if TYPE_OBJECT import java.util.Arrays;
import java.util.Comparator;
#endif
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;
@@ -16,8 +16,11 @@ import speiger.src.collections.PACKAGE.collections.ITERATOR;
#endif #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.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;
@@ -31,7 +34,7 @@ import speiger.src.collections.utils.SanityChecks;
* This implementation of SortedSet does not support SubSet of any kind. It implements the interface due to sortability and first/last access * This implementation of SortedSet does not support SubSet of any kind. It implements the interface due to sortability and first/last access
* @Type(T) * @Type(T)
*/ */
public class LINKED_HASH_SET KEY_GENERIC_TYPE extends HASH_SET KEY_GENERIC_TYPE implements SORTED_SET KEY_GENERIC_TYPE public class LINKED_HASH_SET KEY_GENERIC_TYPE extends HASH_SET KEY_GENERIC_TYPE implements ORDERED_SET KEY_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 transient long[] links; protected transient long[] links;
@@ -116,7 +119,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 +130,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 +377,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 +519,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 +596,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();
@@ -484,16 +624,20 @@ public class LINKED_HASH_SET KEY_GENERIC_TYPE extends HASH_SET KEY_GENERIC_TYPE
} }
@Override @Override
public COMPARATOR KEY_GENERIC_TYPE comparator() { return null; } public LINKED_HASH_SET KEY_GENERIC_TYPE copy() {
LINKED_HASH_SET KEY_GENERIC_TYPE set = new LINKED_HASH_SETBRACES(0, loadFactor);
@Override set.minCapacity = minCapacity;
public SORTED_SET KEY_GENERIC_TYPE subSet(KEY_TYPE fromElement, KEY_TYPE toElement) { throw new UnsupportedOperationException(); } set.mask = mask;
set.maxFill = maxFill;
@Override set.nullIndex = nullIndex;
public SORTED_SET KEY_GENERIC_TYPE headSet(KEY_TYPE toElement) { throw new UnsupportedOperationException(); } set.containsNull = containsNull;
set.size = size;
@Override set.keys = Arrays.copyOf(keys, keys.length);
public SORTED_SET KEY_GENERIC_TYPE tailSet(KEY_TYPE fromElement) { throw new UnsupportedOperationException(); } set.links = Arrays.copyOf(links, links.length);
set.firstIndex = firstIndex;
set.lastIndex = lastIndex;
return set;
}
private class SetIterator implements LIST_ITERATOR KEY_GENERIC_TYPE { private class SetIterator implements LIST_ITERATOR KEY_GENERIC_TYPE {
int previous = -1; int previous = -1;
@@ -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
@@ -144,10 +171,10 @@ public interface NAVIGABLE_SET KEY_GENERIC_TYPE extends NavigableSet<CLASS_TYPE>
default CLASS_TYPE last() { return SORTED_SET.super.last(); } default CLASS_TYPE last() { return SORTED_SET.super.last(); }
@Override @Override
@Deprecated @Deprecated
public default CLASS_TYPE pollFirst() { return KEY_TO_OBJ(POLL_FIRST_KEY()); } public default CLASS_TYPE pollFirst() { return isEmpty() ? null : KEY_TO_OBJ(POLL_FIRST_KEY()); }
@Override @Override
@Deprecated @Deprecated
public default CLASS_TYPE pollLast() { return KEY_TO_OBJ(POLL_LAST_KEY()); } public default CLASS_TYPE pollLast() { return isEmpty() ? null : KEY_TO_OBJ(POLL_LAST_KEY()); }
@Override @Override
@Deprecated @Deprecated
@@ -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);
@@ -267,8 +277,32 @@ public class CUSTOM_HASH_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_T
return true; return true;
} }
#if TYPE_OBJECT
@Override @Override
@Deprecated public KEY_TYPE addOrGet(KEY_TYPE o) {
if(strategy.equals(o, EMPTY_KEY_VALUE)) {
if(containsNull) return EMPTY_KEY_VALUE;
containsNull = true;
onNodeAdded(nullIndex);
}
else {
int pos = HashUtil.mix(strategy.hashCode(o)) & mask;
KEY_TYPE current = keys[pos];
if(!strategy.equals(current, EMPTY_KEY_VALUE)) {
if(strategy.equals(current, o)) return current;
while(!strategy.equals((current = keys[pos = (++pos & mask)]), EMPTY_KEY_VALUE))
if(strategy.equals(current, o)) return current;
}
keys[pos] = o;
onNodeAdded(pos);
}
if(size++ >= maxFill) rehash(HashUtil.arraySize(size+1, loadFactor));
return o;
}
#endif
@Override
@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 +382,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 +456,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 +475,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 +501,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 +659,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 +678,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);
@@ -226,8 +235,32 @@ public class HASH_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE imp
return true; return true;
} }
#if TYPE_OBJECT
@Override @Override
@Deprecated public KEY_TYPE addOrGet(KEY_TYPE o) {
if(KEY_EQUALS_NULL(o)) {
if(containsNull) return null;
containsNull = true;
onNodeAdded(nullIndex);
}
else {
int pos = HashUtil.mix(KEY_TO_HASH(o)) & mask;
KEY_TYPE current = keys[pos];
if(KEY_EQUALS_NOT_NULL(current)) {
if(KEY_EQUALS(current, o)) return current;
while(KEY_EQUALS_NOT_NULL((current = keys[pos = (++pos & mask)])))
if(KEY_EQUALS(current, o)) return current;
}
keys[pos] = o;
onNodeAdded(pos);
}
if(size++ >= maxFill) rehash(HashUtil.arraySize(size+1, loadFactor));
return o;
}
#endif
@Override
@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());
@@ -243,7 +276,12 @@ public class HASH_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE imp
@Override @Override
public boolean contains(Object o) { public boolean contains(Object o) {
#if TYPE_OBJECT
if(o == null) return containsNull; if(o == null) return containsNull;
#else
if(o == null) return false;
if(o instanceof CLASS_TYPE && KEY_EQUALS(CLASS_TO_KEY(o), EMPTY_KEY_VALUE)) return containsNull;
#endif
int pos = HashUtil.mix(o.hashCode()) & mask; int pos = HashUtil.mix(o.hashCode()) & 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;
@@ -256,7 +294,12 @@ public class HASH_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE imp
@Override @Override
public boolean remove(Object o) { public boolean remove(Object o) {
#if TYPE_OBJECT
if(o == null) return (containsNull ? removeNullIndex() : false); if(o == null) return (containsNull ? removeNullIndex() : false);
#else
if(o == null) return false;
if(o instanceof CLASS_TYPE && KEY_EQUALS(CLASS_TO_KEY(o), EMPTY_KEY_VALUE)) return (containsNull ? removeNullIndex() : false);
#endif
int pos = HashUtil.mix(o.hashCode()) & mask; int pos = HashUtil.mix(o.hashCode()) & 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;
@@ -283,7 +326,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 +349,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 +546,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 +565,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 +593,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 +627,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 +646,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--;
@@ -0,0 +1,114 @@
package speiger.src.collections.PACKAGE.sets;
import speiger.src.collections.PACKAGE.collections.BI_ITERATOR;
import speiger.src.collections.PACKAGE.collections.SPLIT_ITERATOR;
import speiger.src.collections.PACKAGE.utils.SETS;
import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS;
/**
* A Special Set Interface giving Access to some really usefull functions
* The Idea behind this interface is to allow access to functions that give control to the Order of elements.
* Since Linked implementations as examples can be reordered outside of the Insertion Order.
* This interface provides basic access to such functions while also providing some Sorted/NaivgableSet implementations that still fit into here.
*
* @Type(T)
*/
public interface ORDERED_SET KEY_GENERIC_TYPE extends SET KEY_GENERIC_TYPE
{
/**
* A customized add method that allows you to insert into the first index.
* @param o the element that should be inserted
* @return true if it was added
* @see java.util.Set#add(Object)
*/
public boolean addAndMoveToFirst(KEY_TYPE o);
/**
* A customized add method that allows you to insert into the last index.
* @param o the element that should be inserted
* @return true if it was added
* @see java.util.Set#add(Object)
*/
public boolean addAndMoveToLast(KEY_TYPE o);
/**
* A specific move method to move a given key to the first index.
* @param o that should be moved to the first index
* @return true if the value was moved.
* @note returns false if the value was not present in the first place
*/
public boolean moveToFirst(KEY_TYPE o);
/**
* A specific move method to move a given key to the last index.
* @param o that should be moved to the first last
* @return true if the value was moved.
* @note returns false if the value was not present in the first place
*/
public boolean moveToLast(KEY_TYPE o);
@Override
public ORDERED_SET KEY_GENERIC_TYPE copy();
@Override
public BI_ITERATOR KEY_GENERIC_TYPE iterator();
/**
* A type Specific Iterator starting from a given key
* @param fromElement the element the iterator should start from
* @return a iterator starting from the given element
* @throws java.util.NoSuchElementException if fromElement isn't found
*/
public BI_ITERATOR KEY_GENERIC_TYPE iterator(KEY_TYPE fromElement);
/**
* A Type Specific Type Splititerator to reduce boxing/unboxing
* @return type specific splititerator
*/
@Override
default SPLIT_ITERATOR KEY_GENERIC_TYPE spliterator() { return SPLIT_ITERATORS.createSplititerator(this, 0); }
/**
* A method to get the first element in the set
* @return first element in the set
*/
public KEY_TYPE FIRST_KEY();
/**
* A method to get and remove the first element in the set
* @return first element in the set
*/
public KEY_TYPE POLL_FIRST_KEY();
/**
* A method to get the last element in the set
* @return last element in the set
*/
public KEY_TYPE LAST_KEY();
/**
* A method to get and remove the last element in the set
* @return last element in the set
*/
public KEY_TYPE POLL_LAST_KEY();
#if !TYPE_BOOLEAN
/**
* Creates a Wrapped OrderedSet that is Synchronized
* @return a new OrderedSet that is synchronized
* @see SETS#synchronize
*/
public default ORDERED_SET KEY_GENERIC_TYPE synchronize() { return SETS.synchronize(this); }
/**
* Creates a Wrapped OrderedSet that is Synchronized
* @param mutex is the controller of the synchronization block
* @return a new OrderedSet Wrapper that is synchronized
* @see SETS#synchronize
*/
public default ORDERED_SET KEY_GENERIC_TYPE synchronize(Object mutex) { return SETS.synchronize(this, mutex); }
/**
* Creates a Wrapped OrderedSet that is unmodifiable
* @return a new OrderedSet Wrapper that is unmodifiable
* @see SETS#unmodifiable
*/
public default ORDERED_SET KEY_GENERIC_TYPE unmodifiable() { return SETS.unmodifiable(this); }
#endif
}
File diff suppressed because it is too large Load Diff
@@ -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,40 @@ 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);
} }
#else
/**
* A Helper method that allows to add a element or getting the already present implement.
* Allowing to make unique references reuseable.
* @param o the element to add
* @return either the inserted element or the present element.
*/
public KEY_TYPE addOrGet(KEY_TYPE 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,50 +9,18 @@ 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;
/** /**
* A Type Specific SortedSet implementation to reduce boxing/unboxing * A Type Specific SortedSet implementation to reduce boxing/unboxing
* with a couple extra methods that allow greater control over sets. * with a couple extra methods that allow greater control over sets.
* @Type(T) * @Type(T)
* @note ORDERED_SET is only extended until 0.6.0 for Compat reasons.
* The supported classes already implement ORDERED_SET directly and will remove SORTED_SET implementations in favor of ORDERED_SET instead
*/ */
public interface SORTED_SET KEY_GENERIC_TYPE extends SET KEY_GENERIC_TYPE, SortedSet<CLASS_TYPE> public interface SORTED_SET KEY_GENERIC_TYPE extends SET KEY_GENERIC_TYPE, SortedSet<CLASS_TYPE>
{ {
/**
* A customized add method that allows you to insert into the first index.
* @param o the element that should be inserted
* @return true if it was added
* @see java.util.Set#add(Object)
* @note some implementations do not support this method
*/
public boolean addAndMoveToFirst(KEY_TYPE o);
/**
* A customized add method that allows you to insert into the last index.
* @param o the element that should be inserted
* @return true if it was added
* @see java.util.Set#add(Object)
* @note some implementations do not support this method
*/
public boolean addAndMoveToLast(KEY_TYPE o);
/**
* A specific move method to move a given key to the first index.
* @param o that should be moved to the first index
* @return true if the value was moved.
* @note returns false if the value was not present in the first place
* @note some implementations do not support this method
*/
public boolean moveToFirst(KEY_TYPE o);
/**
* A specific move method to move a given key to the last index.
* @param o that should be moved to the first last
* @return true if the value was moved.
* @note returns false if the value was not present in the first place
* @note some implementations do not support this method
*/
public boolean moveToLast(KEY_TYPE o);
/** /**
* A Type Specific Comparator method * A Type Specific Comparator method
* @return the type specific comparator * @return the type specific comparator
@@ -60,6 +28,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 +41,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,7 +557,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 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;
@@ -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,7 +639,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 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;
@@ -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;
@@ -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;
@@ -0,0 +1,891 @@
package speiger.src.collections.PACKAGE.utils;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.locks.LockSupport;
import java.util.function.Consumer;
#if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.functions.CONSUMER;
#else
import java.util.function.BiFunction;
#endif
import speiger.src.collections.PACKAGE.collections.ITERABLE;
import speiger.src.collections.PACKAGE.collections.COLLECTION;
import speiger.src.collections.PACKAGE.collections.ITERATOR;
import speiger.src.collections.PACKAGE.functions.TASK;
import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
import speiger.src.collections.PACKAGE.functions.function.TO_OBJECT_FUNCTION;
import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR;
import speiger.src.collections.PACKAGE.lists.ARRAY_LIST;
import speiger.src.collections.PACKAGE.lists.LIST;
#if !TYPE_BOOLEAN
import speiger.src.collections.PACKAGE.sets.SET;
import speiger.src.collections.PACKAGE.sets.LINKED_HASH_SET;
#endif
#if !TYPE_BOOLEAN
import speiger.src.collections.booleans.utils.BooleanAsyncBuilder;
import speiger.src.collections.booleans.utils.BooleanAsyncBuilder.BaseBooleanTask;
#endif
#if !TYPE_OBJECT
import speiger.src.collections.objects.utils.ObjectAsyncBuilder;
import speiger.src.collections.objects.utils.ObjectAsyncBuilder.BaseObjectTask;
#endif
#if !TYPE_INT
import speiger.src.collections.ints.utils.IntAsyncBuilder;
import speiger.src.collections.ints.utils.IntAsyncBuilder.BaseIntTask;
#endif
import speiger.src.collections.utils.SanityChecks;
/**
*
*
* The Async API allows you to process collections on a different thread without having to deal with the Multithreading complexity. <br>
* It uses the Lightweight Stream Replace API to do its work, which can make it faster then sequential streams. <br>
* This feature isn't designed to do Multithreading work, but to allow moving work off the main thread into a worker thread. <br>
* So anything executed on this is still Singlethreaded. <br>
* <br>
* How it works is you create the AsyncBuilder using a Iterable of the Type. <br>
* Then select things you want to use on the Iterable. <br>
* - For example: map/filter/peek/limit/etc <br>
* <br>
* After that you select your action the Iterable should be applied on. <br>
* - For Example: forEach/findFirst/matchAny/etc <br>
* <br>
* Then optionally a custom Executor or callback can be applied <br>
* At the end either execute or join can be called to start the task. <br>
* - execute will return the Task reference so that the task can be traced back. <br>
* - join will await the completion of the task and return the return value <br>
* <br>
* During Construction a couple Disposable Builder Objects will be created. <br>
* These will be only used during construction. <br>
* <br>
* The Task Object is also pause-able/Interruptable at any moment during the Processing. <br>
*
* A small example
* <pre><code>
* public void processFiles(ObjectCollection&#60;String&#62; potentialFiles) {
* potentialFiles.asAsync()
* .map(Paths::get).filter(Files::exists) //Modifies the collection (Optional)
* .forEach(Files::delete) //Creates the action (Required)
* .onCompletion(T -&#62; {}} //Callback on completion (Optional)
* .execute() //Starts the task. (Required)
* }
* </code></pre>
* @author Speiger
*
* @Type(T)
*/
public class ASYNC_BUILDER KEY_GENERIC_TYPE
{
ITERABLE KEY_GENERIC_TYPE iterable;
BASE_TASK KEY_GENERIC_TYPE task;
/**
* Main Constructor that uses a Iterable to build a Offthread Task.
* @param iterable that should be processed
*/
public ASYNC_BUILDER(ITERABLE KEY_GENERIC_TYPE iterable) {
this.iterable = iterable;
}
/**
* Helper constructor.
* @param task that had been build
*/
public ASYNC_BUILDER(BASE_TASK KEY_GENERIC_TYPE task) {
this.task = task;
}
/**
* Helper function that automatically wraps a Iterable into a AsyncBuilder since it forces this collections Iterable.
* @param iterable that should be wrapped
* @Type(T)
* @return a AsyncBuilder with the iterable wrapped
*/
public static GENERIC_KEY_BRACES ASYNC_BUILDER KEY_GENERIC_TYPE of(Iterable<CLASS_TYPE> iterable) {
return new ASYNC_BUILDERBRACES(ITERABLES.wrap(iterable));
}
/**
* Maps the elements to something else
* @param mapper the mapping function
* @param <E> The return type.
* @return a new Builder Object with the mapped Iterable
*/
public <E> ObjectAsyncBuilder<E> map(TO_OBJECT_FUNCTION KKS_GENERIC_TYPE<E> mapper) {
return new ObjectAsyncBuilder<>(ITERABLES.map(iterable, mapper));
}
/**
* Maps the elements to something else
* @param mapper the flatMapping function
* @param <V> The return type supplier.
* @param <E> The return type.
* @return a new Builder Object with the mapped Iterable
*/
public <E, V extends Iterable<E>> ObjectAsyncBuilder<E> flatMap(TO_OBJECT_FUNCTION KKS_GENERIC_TYPE<V> mapper) {
return new ObjectAsyncBuilder<>(ITERABLES.flatMap(iterable, mapper));
}
/**
* Maps the elements to something else
* @param mapper the flatMapping function
* @param <E> The return type.
* @return a new Builder Object with the mapped Iterable
*/
public <E> ObjectAsyncBuilder<E> arrayflatMap(TO_OBJECT_FUNCTION KKS_GENERIC_TYPE<E[]> mapper) {
return new ObjectAsyncBuilder<>(ITERABLES.arrayFlatMap(iterable, mapper));
}
/**
* Filters out the unwanted elements out of the Iterable
* @param filter the elements that should be kept
* @return Self with a filter applied
*/
public ASYNC_BUILDER KEY_GENERIC_TYPE filter(PREDICATE KEY_GENERIC_TYPE filter) {
iterable = ITERABLES.filter(iterable, filter);
return this;
}
/**
* Removes duplicated elements out of the Iterable
* @return Self with a deduplicator applied
*/
public ASYNC_BUILDER KEY_GENERIC_TYPE distinct() {
iterable = ITERABLES.distinct(iterable);
return this;
}
/**
* Limits how many elements are inside of the Iterable
* @param limit how many elements should max be iterated through
* @return self with a limiter applied
*/
public ASYNC_BUILDER KEY_GENERIC_TYPE limit(long limit) {
iterable = ITERABLES.limit(iterable, limit);
return this;
}
/**
* Allows to preview elements before they are processed
* @param action the action that should be applied
* @return self with a preview applied
*/
public ASYNC_BUILDER KEY_GENERIC_TYPE peek(CONSUMER KEY_GENERIC_TYPE action) {
iterable = ITERABLES.peek(iterable, action);
return this;
}
/**
* Iterates over the Iterable with a desired action
* @param action that should be applied
* @return a new Builder with the forEach action applied.
*/
public ObjectAsyncBuilder<Void> forEach(CONSUMER KEY_GENERIC_TYPE action) {
return new ObjectAsyncBuilder<>(new ForEachTask<>(iterable.iterator(), action));
}
/**
* Reduces the elements inside of the Iterable down to one element
* @param operator that reduces the elements.
* @return self with the reduce action applied
*/
public ASYNC_BUILDER KEY_GENERIC_TYPE reduce(UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
task = new SimpleReduceTaskBRACES(iterable.iterator(), operator);
return this;
}
#if TYPE_OBJECT
/**
* Reduces the elements inside of the Iterable down to one element using a identity element.
* @param <E> the return type
* @param identity the element the reduce function should start with
* @param operator that reduces the elements.
* @return a new Builder with the reduce function applied
*/
public <KEY_SPECIAL_TYPE> ASYNC_BUILDER<KEY_SPECIAL_TYPE> reduce(KEY_SPECIAL_TYPE identity, BiFunction<KEY_SPECIAL_TYPE, KEY_TYPE, KEY_SPECIAL_TYPE> operator) {
return new ASYNC_BUILDERBRACES(new ReduceTaskBRACES(iterable.iterator(), operator, identity));
}
#else
/**
* Reduces the elements inside of the Iterable down to one element using a identity element.
* @param identity the element the reduce function should start with
* @param operator that reduces the elements.
* @return a new Builder with the reduce function applied
*/
public ASYNC_BUILDER reduce(KEY_TYPE identity, UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
return new ASYNC_BUILDERBRACES(new ReduceTaskBRACES(iterable.iterator(), operator, identity));
}
#endif
/**
* Pours all elements into a List that can be later
* @return a new Builder with the pour function applied
*/
public ObjectAsyncBuilder<LIST KEY_GENERIC_TYPE> pourAsList() {
return pour(new ARRAY_LISTBRACES());
}
#if !TYPE_BOOLEAN
/**
* Pours all elements into a Set that can be later
* @return a new Builder with the pour function applied
*/
public ObjectAsyncBuilder<SET KEY_GENERIC_TYPE> pourAsSet() {
return pour(new LINKED_HASH_SETBRACES());
}
#endif
/**
* Pours all elements into a collection that can be later
* @param <E> the return type
* @param collection the collection the elements
* @return a new Builder with the pour function applied
*/
public <E extends COLLECTION KEY_GENERIC_TYPE> ObjectAsyncBuilder<E> pour(E collection) {
return new ObjectAsyncBuilder<>(new CollectTask<>(iterable.iterator(), collection));
}
/**
* Searches through the elements of the Iterable to find if the desired element is present.
* @param filter that decides the desired elements
* @return a new Builder with the matchAny function applied
*/
public BooleanAsyncBuilder matchAny(PREDICATE KEY_GENERIC_TYPE filter) {
return new BooleanAsyncBuilder(new MatchTaskBRACES(iterable.iterator(), filter, 0));
}
/**
* Searches through the elements of the Iterable to find if unwanted elements are present.
* @param filter that decides the unwanted elements
* @return a new Builder with the matchNone function applied
*/
public BooleanAsyncBuilder matchNone(PREDICATE KEY_GENERIC_TYPE filter) {
return new BooleanAsyncBuilder(new MatchTaskBRACES(iterable.iterator(), filter, 1));
}
/**
* Searches through the elements of the Iterable to find if all the desired elements are present.
* @param filter that decides the desired elements
* @return a new Builder with the matchAll function applied
*/
public BooleanAsyncBuilder matchAll(PREDICATE KEY_GENERIC_TYPE filter) {
return new BooleanAsyncBuilder(new MatchTaskBRACES(iterable.iterator(), filter, 2));
}
/**
* Searches through the elements of the Iterable to find if the desired element.
* If not present it will return the default value of the type
* @param filter that decides the desired elements
* @return self with the findFirst function applied
*/
public ASYNC_BUILDER KEY_GENERIC_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) {
task = new FindFirstTaskBRACES(iterable.iterator(), filter);
return this;
}
/**
* Counts all desired elements inside the Iterable
* @param filter that decides the desired elements
* @return a new Builder with the count function applied
*/
public IntAsyncBuilder count(PREDICATE KEY_GENERIC_TYPE filter) {
return new IntAsyncBuilder(new CountTaskBRACES(iterable.iterator(), filter));
}
/**
* Optional way to add a custom executor that runs this offthread task.
* Can only be set after the action was decided on.
* @param executor that executes the task, defaults to {@link SanityChecks#invokeAsyncTask(Runnable) }
* @return self with the executor set
* @note has to be NonNull
*/
public ASYNC_BUILDER KEY_GENERIC_TYPE executor(Executor executor) {
if(task == null) throw new IllegalStateException("Action is missing");
task.withExecutor(executor);
return this;
}
/**
* Optional way to set a callback that allows to compute actions after the task was completed.
* The state of the task has to be validated by the callback.
* @param callback that should be notified after completion of the task
* @return self with the callback set
* @note can be null
*/
public ASYNC_BUILDER KEY_GENERIC_TYPE onCompletion(Consumer<TASK KEY_GENERIC_TYPE> callback) {
if(task == null) throw new IllegalStateException("Action is missing");
task.withCallback(callback);
return this;
}
/**
* Starts the Execution of the task without awaiting its result
* @return the task object that allow to trace it.
*/
public TASK KEY_GENERIC_TYPE execute() {
BASE_TASK KEY_GENERIC_TYPE toRun = task;
toRun.begin();
task = null;
return toRun;
}
/**
* Starts the Execution of the task and will await its completion, returning the result.
* @return the result of the task provided.
* @throws ExecutionException if the task threw a exception
* @throws InterruptedException if the caller thread was interrupted
*/
public KEY_TYPE join() throws ExecutionException, InterruptedException {
BASE_TASK KEY_GENERIC_TYPE toRun = task;
task = null;
toRun.begin();
return toRun.GET_KEY();
}
/**
* Starts the Execution of the task and will await its completion with a timeout, returning the result.
* @param timeout of how long the thread should wait the task to be completed
* @param unit of the desired waiting time.
* @return the result of the provided task
* @throws InterruptedException if the caller thread was interrupted
* @throws ExecutionException if the task threw a exception
* @throws TimeoutException if the timeout was reached before the task was finished
*/
public KEY_TYPE join(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
BASE_TASK KEY_GENERIC_TYPE toRun = task;
task = null;
toRun.begin();
return toRun.GET_KEY(timeout, unit);
}
#if !TYPE_OBJECT
private static class ReduceTask extends BASE_TASK
{
ITERATOR KEY_GENERIC_TYPE iter;
UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator;
KEY_TYPE value;
public ReduceTask(ITERATOR KEY_GENERIC_TYPE iter, UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator, KEY_TYPE value) {
this.iter = iter;
this.operator = operator;
this.value = value;
}
@Override
protected boolean execute() throws Exception {
while(shouldRun() && iter.hasNext()) {
value = operator.apply(value, iter.NEXT());
}
if(!iter.hasNext()) {
setResult(value);
return true;
}
return false;
}
@Override
protected void onCompletion() {
super.onCompletion();
iter = null;
operator = null;
#if TYPE_OBJECT
value = null;
#endif
}
}
#else
private static class ReduceTask<T, E> extends BaseObjectTask<E>
{
ObjectIterator<T> iter;
BiFunction<E, T, E> operator;
E value;
public ReduceTask(ITERATOR KEY_GENERIC_TYPE iter, BiFunction<E, T, E> operator, E value) {
this.iter = iter;
this.operator = operator;
this.value = value;
}
@Override
protected boolean execute() throws Exception {
while(shouldRun() && iter.hasNext()) {
value = operator.apply(value, iter.NEXT());
}
if(!iter.hasNext()) {
setResult(value);
return true;
}
return false;
}
@Override
protected void onCompletion() {
super.onCompletion();
iter = null;
operator = null;
#if TYPE_OBJECT
value = null;
#endif
}
}
#endif
private static class SimpleReduceTask KEY_GENERIC_TYPE extends BASE_TASK KEY_GENERIC_TYPE
{
ITERATOR KEY_GENERIC_TYPE iter;
UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator;
boolean first = true;
KEY_TYPE value;
public SimpleReduceTask(ITERATOR KEY_GENERIC_TYPE iter, UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
this.iter = iter;
this.operator = operator;
}
@Override
protected boolean execute() throws Exception {
while(shouldRun() && iter.hasNext()) {
if(first) {
first = false;
value = iter.NEXT();
}
else {
value = operator.APPLY_VALUE(value, iter.NEXT());
}
}
if(!iter.hasNext()) {
setResult(value);
return true;
}
return false;
}
@Override
protected void onCompletion() {
super.onCompletion();
iter = null;
operator = null;
#if TYPE_OBJECT
value = null;
#endif
}
}
private static class MatchTask KEY_GENERIC_TYPE extends BaseBooleanTask
{
ITERATOR KEY_GENERIC_TYPE iter;
PREDICATE KEY_GENERIC_TYPE filter;
int type;
public MatchTask(ITERATOR KEY_GENERIC_TYPE iter, PREDICATE KEY_GENERIC_TYPE filter, int type) {
this.iter = iter;
this.filter = filter;
this.type = type;
if(type < 0 || type > 2) throw new IllegalArgumentException("Type is not allowed has to be between 0-2");
}
@Override
protected boolean execute() throws Exception {
switch(type) {
case 0:
while(shouldRun() && iter.hasNext()) {
#if TYPE_OBJECT
if(filter.getBoolean(iter.NEXT())) {
#else
if(filter.GET_VALUE(iter.NEXT())) {
#endif
setResult(true);
return true;
}
}
break;
case 1:
while(shouldRun() && iter.hasNext()) {
#if TYPE_OBJECT
if(filter.getBoolean(iter.NEXT())) {
#else
if(filter.GET_VALUE(iter.NEXT())) {
#endif
setResult(false);
return true;
}
}
break;
case 2:
while(shouldRun() && iter.hasNext()) {
#if TYPE_OBJECT
if(!filter.getBoolean(iter.NEXT())) {
#else
if(!filter.GET_VALUE(iter.NEXT())) {
#endif
setResult(false);
return true;
}
}
break;
}
if(!iter.hasNext()) {
setResult(type >= 1);
return true;
}
return false;
}
@Override
protected void onCompletion() {
super.onCompletion();
iter = null;
filter = null;
}
}
private static class FindFirstTask KEY_GENERIC_TYPE extends BASE_TASK KEY_GENERIC_TYPE
{
ITERATOR KEY_GENERIC_TYPE iter;
PREDICATE KEY_GENERIC_TYPE filter;
public FindFirstTask(ITERATOR KEY_GENERIC_TYPE iter, PREDICATE KEY_GENERIC_TYPE filter) {
this.iter = iter;
this.filter = filter;
}
@Override
protected boolean execute() throws Exception {
while(shouldRun() && iter.hasNext()) {
KEY_TYPE entry = iter.NEXT();
#if TYPE_OBJECT
if(filter.getBoolean(iter.NEXT())) {
#else
if(filter.GET_VALUE(iter.NEXT())) {
#endif
setResult(entry);
return true;
}
}
return !iter.hasNext();
}
@Override
protected void onCompletion() {
super.onCompletion();
iter = null;
filter = null;
}
}
private static class CountTask KEY_GENERIC_TYPE extends BaseIntTask
{
ITERATOR KEY_GENERIC_TYPE iter;
PREDICATE KEY_GENERIC_TYPE filter;
int counted = 0;
public CountTask(ITERATOR KEY_GENERIC_TYPE iter, PREDICATE KEY_GENERIC_TYPE filter) {
this.iter = iter;
this.filter = filter;
}
@Override
protected boolean execute() throws Exception {
while(shouldRun() && iter.hasNext()) {
if(filter.TEST_VALUE(iter.NEXT())) {
counted++;
}
}
if(!iter.hasNext())
{
setResult(counted);
return true;
}
return false;
}
@Override
protected void onCompletion() {
super.onCompletion();
iter = null;
filter = null;
}
}
private static class CollectTask KSS_GENERIC_TYPE<V, T extends COLLECTION KEY_SPECIAL_GENERIC_TYPE<V>> extends BaseObjectTask<T>
{
ITERATOR KEY_SPECIAL_GENERIC_TYPE<V> iter;
T collection;
public CollectTask(ITERATOR KEY_SPECIAL_GENERIC_TYPE<V> iter, T collection) {
this.iter = iter;
this.collection = collection;
}
@Override
protected boolean execute() throws Exception {
while(shouldRun() && iter.hasNext()) {
collection.add(iter.NEXT());
}
if(!iter.hasNext()) {
setResult(collection);
collection = null;
return true;
}
return false;
}
@Override
protected void onCompletion() {
super.onCompletion();
iter = null;
}
}
private static class ForEachTask<T> extends BaseObjectTask<Void>
{
ITERATOR KEY_GENERIC_TYPE iter;
CONSUMER KEY_GENERIC_TYPE listener;
public ForEachTask(ITERATOR KEY_GENERIC_TYPE iter, CONSUMER KEY_GENERIC_TYPE listener) {
this.iter = iter;
this.listener = listener;
}
@Override
protected boolean execute() throws Exception {
while(shouldRun() && iter.hasNext()) {
listener.accept(iter.NEXT());
}
return !iter.hasNext();
}
@Override
protected void onCompletion() {
super.onCompletion();
iter = null;
listener = null;
}
}
/**
* Base Task of the Actions that can be performed.
* Allows to simplify the actions that get executed.
* @Type(T)
*/
public abstract static class BASE_TASK KEY_GENERIC_TYPE implements TASK KEY_GENERIC_TYPE
{
private static final int CREATED = 0;
private static final int RUNNING = 1;
private static final int PAUSING = 2;
private static final int PAUSED = 3;
private static final int FINISHING = 4;
private static final int FINISHED = 5;
private static final int EXCEPTIONALLY = 6;
private static final int CANCELLED = 7;
private volatile WaitNode waiter;
private volatile int state = CREATED;
Consumer<TASK KEY_GENERIC_TYPE> callback;
Executor executor = SanityChecks::invokeAsyncTask;
KEY_TYPE result;
Throwable excpetion;
void withCallback(Consumer<TASK KEY_GENERIC_TYPE> callback) {
this.callback = callback;
}
void withExecutor(Executor executor) {
this.executor = executor;
}
void begin() {
executor.execute(this);
}
protected abstract boolean execute() throws Exception;
protected void onCompletion() {
if(callback != null) {
callback.accept(this);
callback = null;
}
executor = null;
}
protected void setResult(KEY_TYPE result) {
this.result = result;
}
@Override
public void run() {
state = RUNNING;
try {
if(execute()) {
state = FINISHING;
finishCompletion(FINISHED);
}
else if(state == PAUSING) {
state = PAUSED;
}
}
catch(Exception e) {
state = EXCEPTIONALLY;
this.excpetion = e;
finishCompletion(EXCEPTIONALLY);
}
}
private void finishCompletion(int nextState) {
WaitNode current = waiter;
waiter = null;
while(current != null) {
Thread t = current.thread;
if (t != null) {
current.thread = null;
LockSupport.unpark(t);
}
WaitNode next = current.next;
if (next == null)
break;
current.next = null;
current = next;
}
state = nextState;
onCompletion();
}
@Override
public boolean cancel(boolean cancelIfRunnning) {
if(state == RUNNING && !cancelIfRunnning) return false;
state = CANCELLED;
finishCompletion(CANCELLED);
return true;
}
@Override
public KEY_TYPE GET_KEY() throws InterruptedException, ExecutionException {
int s = state;
return report(s <= FINISHING ? awaitDone(false, 0L) : s);
}
@Override
public KEY_TYPE GET_KEY(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
if (unit == null) throw new NullPointerException();
int s = state;
if (s <= FINISHING && (s = awaitDone(true, unit.toNanos(timeout))) <= FINISHING) throw new TimeoutException();
return report(s);
}
private KEY_TYPE report(int s) throws ExecutionException {
if (s == FINISHED) return result;
if (s >= CANCELLED) throw new CancellationException();
throw new ExecutionException(excpetion);
}
private int awaitDone(boolean timed, long nanos) throws InterruptedException {
final long deadline = timed ? System.nanoTime() + nanos : 0L;
WaitNode q = null;
boolean queued = false;
while(true) {
if(Thread.interrupted()) {
removeWaiter(q);
throw new InterruptedException();
}
int s = state;
if(s > FINISHING) {
if(q != null) q.thread = null;
return s;
}
else if(s == FINISHING) Thread.yield();
else if(q == null) q = new WaitNode();
else if(!queued) {
q.next = waiter;
waiter = q;
queued = true;
}
else if(timed) {
nanos = deadline - System.nanoTime();
if(nanos <= 0L) {
removeWaiter(q);
return state;
}
LockSupport.parkNanos(this, nanos);
}
else LockSupport.park(this);
}
}
private void removeWaiter(WaitNode node) {
if(node == null) return;
node.thread = null;
retry:
while(true) {
for(WaitNode prev = null, current = waiter, next = null; current != null; current = next) {
next = current.next;
if(current.thread != null) prev = current;
else if(prev != null) {
prev.next = next;
if(prev.thread == null) continue retry; //Previous element got removed which means another thread was editing this while we were editing.
}
else if(waiter == current) {
waiter = next;
continue retry;
}
}
break;
}
}
@Override
public boolean isCancelled() { return state >= CANCELLED; }
@Override
public boolean isDone() { return state >= FINISHING; }
@Override
public boolean isPaused() { return state == PAUSED; }
@Override
public boolean isSuccessful() { return state == FINISHED; }
protected boolean shouldRun() { return state == RUNNING; }
@Override
public void pause() {
if(state == PAUSED || state == PAUSING || state >= FINISHING) return;
state = PAUSING;
}
@Override
public void awaitPausing() {
if(state == PAUSED) return;
pause();
if(state == PAUSING) {
while(state == PAUSING) {
Thread.yield();
}
}
}
@Override
public void resume() {
if(state != PAUSED && state != PAUSING) return;
if(state == PAUSING) {
while(state == PAUSING) {
Thread.yield();
}
}
state = RUNNING;
executor.execute(this);
}
static final class WaitNode {
volatile Thread thread;
volatile WaitNode next;
WaitNode() {
thread = Thread.currentThread();
}
}
}
}
@@ -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(); } }
}
}
@@ -18,6 +18,7 @@ import speiger.src.collections.PACKAGE.collections.ITERATOR;
import speiger.src.collections.PACKAGE.sets.NAVIGABLE_SET; import speiger.src.collections.PACKAGE.sets.NAVIGABLE_SET;
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;
import speiger.src.collections.PACKAGE.sets.ORDERED_SET;
import speiger.src.collections.PACKAGE.sets.SORTED_SET; import speiger.src.collections.PACKAGE.sets.SORTED_SET;
import speiger.src.collections.PACKAGE.utils.COLLECTIONS.EmptyCollection; import speiger.src.collections.PACKAGE.utils.COLLECTIONS.EmptyCollection;
import speiger.src.collections.PACKAGE.utils.COLLECTIONS.SynchronizedCollection; import speiger.src.collections.PACKAGE.utils.COLLECTIONS.SynchronizedCollection;
@@ -56,7 +57,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 +69,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 +80,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,10 +92,33 @@ 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));
} }
/**
* Creates a Synchronized OrderedSet while preserving the ITrimmable interface
* @param s the set that should be synchronized
* @Type(T)
* @return a OrderedSet that is synchronized
* @note if the set is already synchronized then it will just self return it
*/
public static GENERIC_KEY_BRACES ORDERED_SET KEY_GENERIC_TYPE synchronize(ORDERED_SET KEY_GENERIC_TYPE s) {
return s instanceof SynchronizedOrderedSet ? s : (s instanceof ITrimmable ? new SynchronizedOrderedTrimSetBRACES(s) : new SynchronizedOrderedSetBRACES(s));
}
/**
* Creates a Synchronized OrderedSet while preserving the ITrimmable interface
* @param s the set that should be synchronized
* @param mutex controller for access
* @Type(T)
* @return a OrderedSet that is synchronized
* @note if the set is already synchronized then it will just self return it
*/
public static GENERIC_KEY_BRACES ORDERED_SET KEY_GENERIC_TYPE synchronize(ORDERED_SET KEY_GENERIC_TYPE s, Object mutex) {
return s instanceof SynchronizedOrderedSet ? s : (s instanceof ITrimmable ? new SynchronizedOrderedTrimSetBRACES(s, mutex) : new SynchronizedOrderedSetBRACES(s, mutex));
}
/** /**
* Creates a Synchronized NavigableSet while preserving the ITrimmable interface * Creates a Synchronized NavigableSet while preserving the ITrimmable interface
* @param s the set that should be synchronized * @param s the set that should be synchronized
@@ -102,7 +126,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 +138,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,19 +154,29 @@ 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);
} }
/** /**
* Creates Unmodifyable NavigableSet wrapper * Creates Unmodifyable OrderedSet wrapper
* @param s navigableSet that should be made unmodifyable * @param s OrderedSet that should be made unmodifiable
* @Type(T) * @Type(T)
* @return a UnmodifyableNavigableSet, if the set is already unmodifyable then it returns itself * @return a UnmodifyableOrderedSet, if the set is already unmodifiable then it returns itself
*/
public static GENERIC_KEY_BRACES ORDERED_SET KEY_GENERIC_TYPE unmodifiable(ORDERED_SET KEY_GENERIC_TYPE s) {
return s instanceof UnmodifiableOrderedSet ? s : new UnmodifiableOrderedSetBRACES(s);
}
/**
* Creates Unmodifyable NavigableSet wrapper
* @param s navigableSet that should be made unmodifiable
* @Type(T)
* @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 +189,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);
} }
@@ -173,6 +207,9 @@ public class SETS
#endif #endif
@Override @Override
public boolean add(KEY_TYPE o) { throw new UnsupportedOperationException(); } public boolean add(KEY_TYPE o) { throw new UnsupportedOperationException(); }
#if TYPE_OBJECT
public KEY_TYPE addOrGet(KEY_TYPE o) { throw new UnsupportedOperationException(); }
#endif
@Override @Override
public ITERATOR KEY_GENERIC_TYPE iterator() public ITERATOR KEY_GENERIC_TYPE iterator()
{ {
@@ -190,6 +227,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
@@ -197,7 +237,12 @@ public class SETS
#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(); }
#else
@Override
public KEY_TYPE addOrGet(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 +291,64 @@ 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 UnmodifiableOrderedSet KEY_GENERIC_TYPE extends UnmodifiableSet KEY_GENERIC_TYPE implements ORDERED_SET KEY_GENERIC_TYPE
{
ORDERED_SET KEY_GENERIC_TYPE s;
UnmodifiableOrderedSet(ORDERED_SET KEY_GENERIC_TYPE c)
{
super(c);
s = c;
}
@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 BI_ITERATOR KEY_GENERIC_TYPE iterator() { return ITERATORS.unmodifiable(s.iterator()); }
@Override
public BI_ITERATOR KEY_GENERIC_TYPE iterator(KEY_TYPE fromElement) { return ITERATORS.unmodifiable(s.iterator(fromElement)); }
@Override
public ORDERED_SET KEY_GENERIC_TYPE copy() { return s.copy(); }
@Override
public KEY_TYPE FIRST_KEY() { return s.FIRST_KEY(); }
@Override
public KEY_TYPE POLL_FIRST_KEY() { throw new UnsupportedOperationException(); }
@Override
public KEY_TYPE LAST_KEY() { return s.LAST_KEY(); }
@Override
public KEY_TYPE POLL_LAST_KEY() { throw new UnsupportedOperationException(); }
} }
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
@@ -279,45 +360,26 @@ public class SETS
s = c; s = c;
} }
@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 @Override
public COMPARATOR KEY_GENERIC_TYPE comparator() { return s.comparator(); } public COMPARATOR KEY_GENERIC_TYPE comparator() { return s.comparator(); }
@Override @Override
public BI_ITERATOR KEY_GENERIC_TYPE iterator() { return ITERATORS.unmodifiable(s.iterator()); } public BI_ITERATOR KEY_GENERIC_TYPE iterator() { return ITERATORS.unmodifiable(s.iterator()); }
@Override @Override
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(); }
@Override @Override
public KEY_TYPE POLL_FIRST_KEY() { throw new UnsupportedOperationException(); } public KEY_TYPE POLL_FIRST_KEY() { throw new UnsupportedOperationException(); }
@Override @Override
public KEY_TYPE LAST_KEY() { return s.LAST_KEY(); } public KEY_TYPE LAST_KEY() { return s.LAST_KEY(); }
@Override @Override
public KEY_TYPE POLL_LAST_KEY() { throw new UnsupportedOperationException(); } public KEY_TYPE POLL_LAST_KEY() { throw new UnsupportedOperationException(); }
} }
@@ -336,6 +398,14 @@ public class SETS
s = c; s = c;
} }
#if TYPE_OBJECT
@Override
public KEY_TYPE addOrGet(KEY_TYPE o) { throw new UnsupportedOperationException(); }
#endif
@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 +428,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 +483,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 +526,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
@@ -466,45 +545,85 @@ public class SETS
s = c; s = c;
} }
@Override
public boolean addAndMoveToFirst(KEY_TYPE o) { synchronized(mutex) { return s.addAndMoveToFirst(o); } }
@Override
public boolean addAndMoveToLast(KEY_TYPE o) { synchronized(mutex) { return s.addAndMoveToLast(o); } }
@Override
public boolean moveToFirst(KEY_TYPE o) { synchronized(mutex) { return s.moveToFirst(o); } }
@Override
public boolean moveToLast(KEY_TYPE o) { synchronized(mutex) { return s.moveToLast(o); } }
@Override @Override
public COMPARATOR KEY_GENERIC_TYPE comparator(){ synchronized(mutex) { return s.comparator(); } } public COMPARATOR KEY_GENERIC_TYPE comparator(){ synchronized(mutex) { return s.comparator(); } }
@Override @Override
public BI_ITERATOR KEY_GENERIC_TYPE iterator() { synchronized(mutex) { return s.iterator(); } } public BI_ITERATOR KEY_GENERIC_TYPE iterator() { synchronized(mutex) { return s.iterator(); } }
@Override @Override
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(); } }
@Override @Override
public KEY_TYPE POLL_FIRST_KEY() { synchronized(mutex) { return s.POLL_FIRST_KEY(); } } public KEY_TYPE POLL_FIRST_KEY() { synchronized(mutex) { return s.POLL_FIRST_KEY(); } }
@Override @Override
public KEY_TYPE LAST_KEY() { synchronized(mutex) { return s.LAST_KEY(); } } public KEY_TYPE LAST_KEY() { synchronized(mutex) { return s.LAST_KEY(); } }
@Override
public KEY_TYPE POLL_LAST_KEY() { synchronized(mutex) { return s.POLL_LAST_KEY(); } }
}
private static class SynchronizedOrderedTrimSet KEY_GENERIC_TYPE extends SynchronizedOrderedSet KEY_GENERIC_TYPE implements ITrimmable
{
ITrimmable trim;
SynchronizedOrderedTrimSet(ORDERED_SET KEY_GENERIC_TYPE c) {
super(c);
trim = (ITrimmable)c;
}
SynchronizedOrderedTrimSet(ORDERED_SET KEY_GENERIC_TYPE c, Object mutex) {
super(c, mutex);
trim = (ITrimmable)c;
}
@Override
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 SynchronizedOrderedSet KEY_GENERIC_TYPE extends SynchronizedSet KEY_GENERIC_TYPE implements ORDERED_SET KEY_GENERIC_TYPE
{
ORDERED_SET KEY_GENERIC_TYPE s;
SynchronizedOrderedSet(ORDERED_SET KEY_GENERIC_TYPE c) {
super(c);
s = c;
}
SynchronizedOrderedSet(ORDERED_SET KEY_GENERIC_TYPE c, Object mutex) {
super(c, mutex);
s = c;
}
@Override
public boolean addAndMoveToFirst(KEY_TYPE o) { synchronized(mutex) { return s.addAndMoveToFirst(o); } }
@Override
public boolean addAndMoveToLast(KEY_TYPE o) { synchronized(mutex) { return s.addAndMoveToLast(o); } }
@Override
public boolean moveToFirst(KEY_TYPE o) { synchronized(mutex) { return s.moveToFirst(o); } }
@Override
public boolean moveToLast(KEY_TYPE o) { synchronized(mutex) { return s.moveToLast(o); } }
@Override
public BI_ITERATOR KEY_GENERIC_TYPE iterator() { synchronized(mutex) { return s.iterator(); } }
@Override
public BI_ITERATOR KEY_GENERIC_TYPE iterator(KEY_TYPE fromElement) { synchronized(mutex) { return s.iterator(fromElement); } }
@Override
public ORDERED_SET KEY_GENERIC_TYPE copy() { synchronized(mutex) { return s.copy(); } }
@Override
public KEY_TYPE FIRST_KEY() { synchronized(mutex) { return s.FIRST_KEY(); } }
@Override
public KEY_TYPE POLL_FIRST_KEY() { synchronized(mutex) { return s.POLL_FIRST_KEY(); } }
@Override
public KEY_TYPE LAST_KEY() { synchronized(mutex) { return s.LAST_KEY(); } }
@Override @Override
public KEY_TYPE POLL_LAST_KEY() { synchronized(mutex) { return s.POLL_LAST_KEY(); } } public KEY_TYPE POLL_LAST_KEY() { synchronized(mutex) { return s.POLL_LAST_KEY(); } }
} }
@@ -525,28 +644,33 @@ 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
} }
#if TYPE_OBJECT
@Override
public KEY_TYPE addOrGet(KEY_TYPE o) { synchronized(mutex) { return s.addOrGet(o); } }
#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); } }
@@ -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
} }
@@ -32,6 +32,7 @@ import speiger.src.collections.PACKAGE.maps.interfaces.MAP;
#if !TYPE_BOOLEAN #if !TYPE_BOOLEAN
import speiger.src.collections.PACKAGE.maps.interfaces.NAVIGABLE_MAP; import speiger.src.collections.PACKAGE.maps.interfaces.NAVIGABLE_MAP;
import speiger.src.collections.PACKAGE.maps.interfaces.SORTED_MAP; import speiger.src.collections.PACKAGE.maps.interfaces.SORTED_MAP;
import speiger.src.collections.PACKAGE.maps.interfaces.ORDERED_MAP;
import speiger.src.collections.PACKAGE.sets.NAVIGABLE_SET; import speiger.src.collections.PACKAGE.sets.NAVIGABLE_SET;
#if !TYPE_OBJECT #if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.sets.SET; import speiger.src.collections.PACKAGE.sets.SET;
@@ -45,7 +46,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 +110,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 +127,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 +138,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 +149,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 +160,29 @@ 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 OrderedMap.
* @param map the OrderedMap that should be synchronized
* @Type(T)
* @ValueType(V)
* @return a synchronized OrderedMap
* @note if the inputted map is already synchronized then it will just return it instead
* @note iterators do not support synchronization
*/
public static GENERIC_KEY_VALUE_BRACES ORDERED_MAP KEY_VALUE_GENERIC_TYPE synchronize(ORDERED_MAP KEY_VALUE_GENERIC_TYPE map) { return map instanceof SynchronizedOrderedMap ? map : new SynchronizedOrderedMapKV_BRACES(map); }
/**
* Helper function that creates a Helper wrapper to synchronize access with custom access control into the OrderedMap.
* @param map the OrderedMap that should be synchronized
* @param mutex the object that controls access
* @Type(T)
* @ValueType(V)
* @return a synchronized OrderedMap
* @note if the inputted map is already synchronized then it will just return it instead
* @note iterators do not support synchronization
*/
public static GENERIC_KEY_VALUE_BRACES ORDERED_MAP KEY_VALUE_GENERIC_TYPE synchronize(ORDERED_MAP KEY_VALUE_GENERIC_TYPE map, Object mutex) { return map instanceof SynchronizedOrderedMap ? map : new SynchronizedOrderedMapKV_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 +193,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 +204,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 +214,18 @@ 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 OrderedMap
* @param map the OrderedMap that should be made Unmodifiable
* @Type(T)
* @ValueType(V)
* @return a unmodifiable OrderedMap
* @note if the inputted OrderedMap is already unmodifiable then it will just return it instead
*/
public static GENERIC_KEY_VALUE_BRACES ORDERED_MAP KEY_VALUE_GENERIC_TYPE unmodifiable(ORDERED_MAP KEY_VALUE_GENERIC_TYPE map) { return map instanceof UnmodifyableOrderedMap ? map : new UnmodifyableOrderedMapKV_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 +234,8 @@ 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 +244,24 @@ 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 +270,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
@@ -263,9 +298,13 @@ public class MAPS
#if VALUE_PRIMITIVES #if VALUE_PRIMITIVES
@Override @Override
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(); }
@Override
public VALUE_TYPE subFrom(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 +315,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;
} }
} }
@@ -307,9 +348,13 @@ public class MAPS
#if VALUE_PRIMITIVES #if VALUE_PRIMITIVES
@Override @Override
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(); }
@Override
public VALUE_TYPE subFrom(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 +368,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 +408,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,24 +452,26 @@ 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(); }
} }
/** /**
* The Unmodifyable Sorted Map implementation that is sued for the unmodifyableMap function * The Unmodifyable Ordered Map implementation that is sued for the unmodifyableMap function
* @Type(T) * @Type(T)
* @ValueType(V) * @ValueType(V)
*/ */
public static class UnmodifyableSortedMap KEY_VALUE_GENERIC_TYPE extends UnmodifyableMap KEY_VALUE_GENERIC_TYPE implements SORTED_MAP KEY_VALUE_GENERIC_TYPE { public static class UnmodifyableOrderedMap KEY_VALUE_GENERIC_TYPE extends UnmodifyableMap KEY_VALUE_GENERIC_TYPE implements ORDERED_MAP KEY_VALUE_GENERIC_TYPE {
SORTED_MAP KEY_VALUE_GENERIC_TYPE map; ORDERED_MAP KEY_VALUE_GENERIC_TYPE map;
UnmodifyableSortedMap(SORTED_MAP KEY_VALUE_GENERIC_TYPE map) { UnmodifyableOrderedMap(ORDERED_MAP KEY_VALUE_GENERIC_TYPE map) {
super(map); super(map);
this.map = map; this.map = map;
} }
@@ -439,14 +488,43 @@ public class MAPS
public VALUE_TYPE getAndMoveToFirst(KEY_TYPE key) { throw new UnsupportedOperationException(); } public VALUE_TYPE getAndMoveToFirst(KEY_TYPE key) { throw new UnsupportedOperationException(); }
@Override @Override
public VALUE_TYPE getAndMoveToLast(KEY_TYPE key) { throw new UnsupportedOperationException(); } public VALUE_TYPE getAndMoveToLast(KEY_TYPE key) { throw new UnsupportedOperationException(); }
@Override
public KEY_TYPE FIRST_ENTRY_KEY() { return map.FIRST_ENTRY_KEY(); }
@Override
public KEY_TYPE POLL_FIRST_ENTRY_KEY() { return map.POLL_FIRST_ENTRY_KEY(); }
@Override
public KEY_TYPE LAST_ENTRY_KEY() { return map.LAST_ENTRY_KEY(); }
@Override
public KEY_TYPE POLL_LAST_ENTRY_KEY() { return map.POLL_LAST_ENTRY_KEY(); }
@Override
public VALUE_TYPE FIRST_ENTRY_VALUE() { return map.FIRST_ENTRY_VALUE(); }
@Override
public VALUE_TYPE LAST_ENTRY_VALUE() { return map.LAST_ENTRY_VALUE(); }
@Override
public ORDERED_MAP KEY_VALUE_GENERIC_TYPE copy() { throw new UnsupportedOperationException(); }
}
/**
* The Unmodifyable Sorted Map implementation that is sued for the unmodifyableMap function
* @Type(T)
* @ValueType(V)
*/
public static class UnmodifyableSortedMap KEY_VALUE_GENERIC_TYPE extends UnmodifyableMap KEY_VALUE_GENERIC_TYPE implements SORTED_MAP KEY_VALUE_GENERIC_TYPE {
SORTED_MAP KEY_VALUE_GENERIC_TYPE map;
UnmodifyableSortedMap(SORTED_MAP KEY_VALUE_GENERIC_TYPE map) {
super(map);
this.map = map;
}
@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 +537,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(); }
} }
/** /**
@@ -483,9 +563,13 @@ public class MAPS
#if VALUE_PRIMITIVES #if VALUE_PRIMITIVES
@Override @Override
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(); }
@Override
public VALUE_TYPE subFrom(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 +580,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 +591,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 +619,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 +629,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 +654,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 +668,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 +695,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
@@ -663,6 +751,52 @@ public class MAPS
#endif #endif
} }
/**
* The Synchronized Ordered Map implementation used by the synchronizedMap helper function
* @Type(T)
* @ValueType(V)
*/
public static class SynchronizedOrderedMap KEY_VALUE_GENERIC_TYPE extends SynchronizedMap KEY_VALUE_GENERIC_TYPE implements ORDERED_MAP KEY_VALUE_GENERIC_TYPE {
ORDERED_MAP KEY_VALUE_GENERIC_TYPE map;
SynchronizedOrderedMap(ORDERED_MAP KEY_VALUE_GENERIC_TYPE map) {
super(map);
this.map = map;
}
SynchronizedOrderedMap(ORDERED_MAP KEY_VALUE_GENERIC_TYPE map, Object mutex) {
super(map, mutex);
this.map = map;
}
@Override
public VALUE_TYPE putAndMoveToFirst(KEY_TYPE key, VALUE_TYPE value) { synchronized(mutex) { return map.putAndMoveToFirst(key, value); } }
@Override
public VALUE_TYPE putAndMoveToLast(KEY_TYPE key, VALUE_TYPE value) { synchronized(mutex) { return map.putAndMoveToLast(key, value); } }
@Override
public boolean moveToFirst(KEY_TYPE key) { synchronized(mutex) { return map.moveToFirst(key); } }
@Override
public boolean moveToLast(KEY_TYPE key) { synchronized(mutex) { return map.moveToLast(key); } }
@Override
public VALUE_TYPE getAndMoveToFirst(KEY_TYPE key) { synchronized(mutex) { return map.getAndMoveToFirst(key); } }
@Override
public VALUE_TYPE getAndMoveToLast(KEY_TYPE key) { synchronized(mutex) { return map.getAndMoveToLast(key); } }
@Override
public KEY_TYPE FIRST_ENTRY_KEY() { synchronized(mutex) { return map.FIRST_ENTRY_KEY(); } }
@Override
public KEY_TYPE POLL_FIRST_ENTRY_KEY() { synchronized(mutex) { return map.POLL_FIRST_ENTRY_KEY(); } }
@Override
public KEY_TYPE LAST_ENTRY_KEY() { synchronized(mutex) { return map.LAST_ENTRY_KEY(); } }
@Override
public KEY_TYPE POLL_LAST_ENTRY_KEY() { synchronized(mutex) { return map.POLL_LAST_ENTRY_KEY(); } }
@Override
public VALUE_TYPE FIRST_ENTRY_VALUE() { synchronized(mutex) { return map.FIRST_ENTRY_VALUE(); } }
@Override
public VALUE_TYPE LAST_ENTRY_VALUE() { synchronized(mutex) { return map.LAST_ENTRY_VALUE(); } }
@Override
public ORDERED_MAP KEY_VALUE_GENERIC_TYPE copy() { throw new UnsupportedOperationException(); }
}
/** /**
* The Synchronized Sorted Map implementation used by the synchronizedMap helper function * The Synchronized Sorted Map implementation used by the synchronizedMap helper function
* @Type(T) * @Type(T)
@@ -681,26 +815,14 @@ public class MAPS
this.map = map; this.map = map;
} }
@Override
public VALUE_TYPE putAndMoveToFirst(KEY_TYPE key, VALUE_TYPE value) { synchronized(mutex) { return map.putAndMoveToFirst(key, value); } }
@Override
public VALUE_TYPE putAndMoveToLast(KEY_TYPE key, VALUE_TYPE value) { synchronized(mutex) { return map.putAndMoveToLast(key, value); } }
@Override
public boolean moveToFirst(KEY_TYPE key) { synchronized(mutex) { return map.moveToFirst(key); } }
@Override
public boolean moveToLast(KEY_TYPE key) { synchronized(mutex) { return map.moveToLast(key); } }
@Override
public VALUE_TYPE getAndMoveToFirst(KEY_TYPE key) { synchronized(mutex) { return map.getAndMoveToFirst(key); } }
@Override
public VALUE_TYPE getAndMoveToLast(KEY_TYPE key) { synchronized(mutex) { return map.getAndMoveToLast(key); } }
@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 +835,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 +846,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 +892,21 @@ 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); } }
@Override
public VALUE_TYPE subFrom(KEY_TYPE key, VALUE_TYPE value) { synchronized(mutex) { return map.subFrom(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 +918,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 +930,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 +941,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 +952,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;
} }
@@ -7,6 +7,8 @@ public class HashUtil
{ {
/** Minimum HashMap Capacity */ /** Minimum HashMap Capacity */
public static final int DEFAULT_MIN_CAPACITY = 16; public static final int DEFAULT_MIN_CAPACITY = 16;
/** Minimum ConcurrentHashMap Concurrency */
public static final int DEFAULT_MIN_CONCURRENCY = 4;
/** Default HashMap Load Factor */ /** Default HashMap Load Factor */
public static final float DEFAULT_LOAD_FACTOR = 0.75F; public static final float DEFAULT_LOAD_FACTOR = 0.75F;
/** HashMap Load Factor with reduced hash collisions but more memory usage */ /** HashMap Load Factor with reduced hash collisions but more memory usage */
@@ -79,6 +81,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 + ")");
} }
@@ -104,6 +104,14 @@ public class SanityChecks
getPool().execute(task); getPool().execute(task);
} }
/**
* A Helper method to start a Async Task. This method will not await the finalization of said task
* @param task the Task to invoke
*/
public static void invokeAsyncTask(Runnable task) {
getPool().execute(task);
}
/** /**
* Helper method to control what ForkJoinPool is being used for any given task. * Helper method to control what ForkJoinPool is being used for any given task.
* @note this method is not thread-save. It is only there to provide control over how Library specific Threaded tasks are handled. * @note this method is not thread-save. It is only there to provide control over how Library specific Threaded tasks are handled.
@@ -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
@@ -0,0 +1,75 @@
package speiger.src.collections.ints.base;
import java.util.EnumSet;
import org.junit.Assert;
import org.junit.Test;
import speiger.src.collections.ints.maps.interfaces.Int2IntOrderedMap;
import speiger.src.collections.tests.OrderedMapTests;
@SuppressWarnings("javadoc")
public abstract class BaseInt2IntOrderedMapTest extends BaseInt2IntMapTest
{
@Override
public abstract Int2IntOrderedMap createMap(int[] keys, int[] values);
@Override
public abstract Int2IntOrderedMap createEmptyMap();
public EnumSet<OrderedMapTests> getValidOrderedMapTests() { return EnumSet.allOf(OrderedMapTests.class); }
@Test
public void testPutMove()
{
if(!getValidOrderedMapTests().contains(OrderedMapTests.PUT_MOVE)) return;
Int2IntOrderedMap map = createMap(TEST_ARRAY, TEST_ARRAY);
Assert.assertEquals(0, map.putAndMoveToFirst(120, -1));
Assert.assertEquals(120, map.firstIntKey());
Assert.assertEquals(-1, map.firstIntValue());
Assert.assertEquals(0, map.putAndMoveToLast(121, -2));
Assert.assertEquals(121, map.lastIntKey());
Assert.assertEquals(-2, map.lastIntValue());
}
@Test
public void testMove()
{
if(!getValidOrderedMapTests().contains(OrderedMapTests.MOVE)) return;
Int2IntOrderedMap map = createMap(TEST_ARRAY, TEST_ARRAY);
Assert.assertTrue(map.moveToFirst(99));
Assert.assertFalse(map.moveToFirst(99));
Assert.assertEquals(99, map.firstIntKey());
Assert.assertTrue(map.moveToLast(0));
Assert.assertFalse(map.moveToLast(0));
Assert.assertEquals(0, map.lastIntKey());
}
@Test
public void testGetMove()
{
if(!getValidOrderedMapTests().contains(OrderedMapTests.GET_MOVE)) return;
Int2IntOrderedMap map = createMap(TEST_ARRAY, TEST_ARRAY);
Assert.assertNotEquals(99, map.firstIntValue());
Assert.assertEquals(99, map.getAndMoveToFirst(99));
Assert.assertEquals(99, map.firstIntValue());
Assert.assertNotEquals(0, map.lastIntValue());
Assert.assertEquals(0, map.getAndMoveToLast(0));
Assert.assertEquals(0, map.lastIntValue());
}
@Test
public void testFirst()
{
if(!getValidOrderedMapTests().contains(OrderedMapTests.FIRST)) return;
Int2IntOrderedMap map = createMap(TEST_ARRAY, TEST_ARRAY);
Assert.assertEquals(map.pollFirstIntKey(), 0);
}
@Test
public void testLast()
{
if(!getValidOrderedMapTests().contains(OrderedMapTests.LAST)) return;
Int2IntOrderedMap map = createMap(TEST_ARRAY, TEST_ARRAY);
Assert.assertEquals(map.pollLastIntKey(), 99);
}
}
@@ -18,55 +18,12 @@ public abstract class BaseInt2IntSortedMapTest extends BaseInt2IntMapTest
public EnumSet<SortedMapTests> getValidSortedMapTests() { return EnumSet.allOf(SortedMapTests.class); } public EnumSet<SortedMapTests> getValidSortedMapTests() { return EnumSet.allOf(SortedMapTests.class); }
@Test
public void testPutMove()
{
if(!getValidSortedMapTests().contains(SortedMapTests.PUT_MOVE)) return;
Int2IntSortedMap map = createMap(TEST_ARRAY, TEST_ARRAY);
Assert.assertEquals(0, map.putAndMoveToFirst(120, -1));
Assert.assertEquals(120, map.firstIntKey());
Assert.assertEquals(-1, map.firstIntValue());
Assert.assertEquals(0, map.putAndMoveToLast(121, -2));
Assert.assertEquals(121, map.lastIntKey());
Assert.assertEquals(-2, map.lastIntValue());
}
@Test
public void testMove()
{
if(!getValidSortedMapTests().contains(SortedMapTests.MOVE)) return;
Int2IntSortedMap map = createMap(TEST_ARRAY, TEST_ARRAY);
Assert.assertTrue(map.moveToFirst(99));
Assert.assertFalse(map.moveToFirst(99));
Assert.assertEquals(99, map.firstIntKey());
Assert.assertTrue(map.moveToLast(0));
Assert.assertFalse(map.moveToLast(0));
Assert.assertEquals(0, map.lastIntKey());
}
@Test
public void testGetMove()
{
if(!getValidSortedMapTests().contains(SortedMapTests.GET_MOVE)) return;
Int2IntSortedMap map = createMap(TEST_ARRAY, TEST_ARRAY);
Assert.assertNotEquals(99, map.firstIntValue());
Assert.assertEquals(99, map.getAndMoveToFirst(99));
Assert.assertEquals(99, map.firstIntValue());
Assert.assertNotEquals(0, map.lastIntValue());
Assert.assertEquals(0, map.getAndMoveToLast(0));
Assert.assertEquals(0, map.lastIntValue());
}
@Test @Test
public void testFirst() public void testFirst()
{ {
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 +31,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 +40,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 +52,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 +63,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::valueOf).toArray(Integer[]::new);
Integer[] actual = ObjectIterators.pour(create(TEST_ARRAY).map(Integer::valueOf).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;
@@ -0,0 +1,63 @@
package speiger.src.collections.ints.base;
import java.util.EnumSet;
import org.junit.Assert;
import org.junit.Test;
import speiger.src.collections.ints.sets.IntOrderedSet;
import speiger.src.collections.tests.OrderedSetTest;
@SuppressWarnings("javadoc")
public abstract class BaseIntOrderedSetTest extends BaseIntCollectionTest
{
@Override
protected abstract IntOrderedSet create(int[] data);
protected EnumSet<OrderedSetTest> getValidOrderedSetTests() { return EnumSet.allOf(OrderedSetTest.class); }
@Test
public void addMoveTest() {
if(getValidOrderedSetTests().contains(OrderedSetTest.ADD_MOVE)) {
IntOrderedSet set = create(TEST_ARRAY);
Assert.assertTrue(set.addAndMoveToFirst(1050));
Assert.assertFalse(set.addAndMoveToLast(5));
}
}
@Test
public void moveTest() {
if(getValidOrderedSetTests().contains(OrderedSetTest.MOVE)) {
IntOrderedSet set = create(TEST_ARRAY);
Assert.assertTrue(set.moveToFirst(5));
Assert.assertFalse(set.moveToFirst(5));
Assert.assertTrue(set.moveToLast(5));
Assert.assertFalse(set.moveToLast(5));
}
}
@Test
public void peekTest() {
if(getValidOrderedSetTests().contains(OrderedSetTest.PEEK)) {
IntOrderedSet set = create(TEST_ARRAY);
Assert.assertEquals(set.firstInt(), 0);
Assert.assertEquals(set.lastInt(), 99);
}
}
@Test
public void pollTest() {
if(getValidOrderedSetTests().contains(OrderedSetTest.POLL)) {
IntOrderedSet set = create(TEST_ARRAY);
for(int i = 0;i<100;i++)
{
Assert.assertEquals(i, set.pollFirstInt());
}
set = create(TEST_ARRAY);
for(int i = 99;i>=0;i--)
{
Assert.assertEquals(i, set.pollLastInt());
}
}
}
}
@@ -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,38 @@ 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());
}
}
}
@Test
public void testUnorderedPeek() {
EnumSet<PriorityQueueTest> valid = getValidPriorityQueueTests();
if(valid.contains(PriorityQueueTest.IN_OUT) && valid.contains(PriorityQueueTest.PEEK) && !isUnsortedRead()) {
IntPriorityQueue queue = create(EMPTY_ARRAY);
for(int i = 0;i<100;i++) {
queue.enqueue(i);
}
for(int i = 0;i<25;i++) {
queue.dequeue();
queue.enqueue(i);
}
for(int i = 0;i<100;i++) {
Assert.assertEquals((i+25) % 100, queue.peek(i));
} }
} }
} }
@@ -89,7 +107,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 +120,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);
}
} }
@@ -16,26 +16,6 @@ public abstract class BaseIntSortedSetTest extends BaseIntCollectionTest
protected EnumSet<SortedSetTest> getValidSortedSetTests() { return EnumSet.allOf(SortedSetTest.class); } protected EnumSet<SortedSetTest> getValidSortedSetTests() { return EnumSet.allOf(SortedSetTest.class); }
@Test
public void addMoveTest() {
if(getValidSortedSetTests().contains(SortedSetTest.ADD_MOVE)) {
IntSortedSet set = create(TEST_ARRAY);
Assert.assertTrue(set.addAndMoveToFirst(1050));
Assert.assertFalse(set.addAndMoveToLast(5));
}
}
@Test
public void moveTest() {
if(getValidSortedSetTests().contains(SortedSetTest.MOVE)) {
IntSortedSet set = create(TEST_ARRAY);
Assert.assertTrue(set.moveToFirst(5));
Assert.assertFalse(set.moveToFirst(5));
Assert.assertTrue(set.moveToLast(5));
Assert.assertFalse(set.moveToLast(5));
}
}
@Test @Test
public void peekTest() { public void peekTest() {
if(getValidSortedSetTests().contains(SortedSetTest.PEEK)) { if(getValidSortedSetTests().contains(SortedSetTest.PEEK)) {
@@ -49,9 +29,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);
}
}
}
@@ -1,18 +1,12 @@
package speiger.src.collections.ints.maps; package speiger.src.collections.ints.maps;
import java.util.EnumSet;
import speiger.src.collections.ints.base.BaseInt2IntNavigableMapTest; import speiger.src.collections.ints.base.BaseInt2IntNavigableMapTest;
import speiger.src.collections.ints.maps.impl.tree.Int2IntAVLTreeMap; import speiger.src.collections.ints.maps.impl.tree.Int2IntAVLTreeMap;
import speiger.src.collections.ints.maps.interfaces.Int2IntNavigableMap; import speiger.src.collections.ints.maps.interfaces.Int2IntNavigableMap;
import speiger.src.collections.tests.SortedMapTests;
@SuppressWarnings("javadoc") @SuppressWarnings("javadoc")
public class Int2IntAVLTreeMapTest extends BaseInt2IntNavigableMapTest public class Int2IntAVLTreeMapTest extends BaseInt2IntNavigableMapTest
{ {
@Override
public EnumSet<SortedMapTests> getValidSortedMapTests() { return EnumSet.complementOf(EnumSet.of(SortedMapTests.GET_MOVE, SortedMapTests.MOVE, SortedMapTests.PUT_MOVE)); }
@Override @Override
public Int2IntNavigableMap createMap(int[] keys, int[] values) public Int2IntNavigableMap createMap(int[] keys, int[] values)
{ {
@@ -1,20 +1,20 @@
package speiger.src.collections.ints.maps; package speiger.src.collections.ints.maps;
import speiger.src.collections.ints.base.BaseInt2IntSortedMapTest; import speiger.src.collections.ints.base.BaseInt2IntOrderedMapTest;
import speiger.src.collections.ints.maps.impl.misc.Int2IntArrayMap; import speiger.src.collections.ints.maps.impl.misc.Int2IntArrayMap;
import speiger.src.collections.ints.maps.interfaces.Int2IntSortedMap; import speiger.src.collections.ints.maps.interfaces.Int2IntOrderedMap;
@SuppressWarnings("javadoc") @SuppressWarnings("javadoc")
public class Int2IntArrayMapTest extends BaseInt2IntSortedMapTest public class Int2IntArrayMapTest extends BaseInt2IntOrderedMapTest
{ {
@Override @Override
public Int2IntSortedMap createMap(int[] keys, int[] values) public Int2IntOrderedMap createMap(int[] keys, int[] values)
{ {
return new Int2IntArrayMap(keys, values); return new Int2IntArrayMap(keys, values);
} }
@Override @Override
public Int2IntSortedMap createEmptyMap() public Int2IntOrderedMap createEmptyMap()
{ {
return new Int2IntArrayMap(); return new Int2IntArrayMap();
} }
@@ -1,26 +1,20 @@
package speiger.src.collections.ints.maps; package speiger.src.collections.ints.maps;
import java.util.EnumSet; import speiger.src.collections.ints.base.BaseInt2IntOrderedMapTest;
import speiger.src.collections.ints.base.BaseInt2IntSortedMapTest;
import speiger.src.collections.ints.maps.impl.customHash.Int2IntLinkedOpenCustomHashMap; import speiger.src.collections.ints.maps.impl.customHash.Int2IntLinkedOpenCustomHashMap;
import speiger.src.collections.ints.maps.interfaces.Int2IntSortedMap; import speiger.src.collections.ints.maps.interfaces.Int2IntOrderedMap;
import speiger.src.collections.tests.SortedMapTests;
@SuppressWarnings("javadoc") @SuppressWarnings("javadoc")
public class Int2IntLinkedOpenCustomHashMapTest extends BaseInt2IntSortedMapTest public class Int2IntLinkedOpenCustomHashMapTest extends BaseInt2IntOrderedMapTest
{ {
@Override @Override
public EnumSet<SortedMapTests> getValidSortedMapTests() { return EnumSet.complementOf(EnumSet.of(SortedMapTests.SUB_MAP, SortedMapTests.TAIL_MAP, SortedMapTests.HEAD_MAP)); } public Int2IntOrderedMap createMap(int[] keys, int[] values)
@Override
public Int2IntSortedMap createMap(int[] keys, int[] values)
{ {
return new Int2IntLinkedOpenCustomHashMap(keys, values, STRATEGY); return new Int2IntLinkedOpenCustomHashMap(keys, values, STRATEGY);
} }
@Override @Override
public Int2IntSortedMap createEmptyMap() public Int2IntOrderedMap createEmptyMap()
{ {
return new Int2IntLinkedOpenCustomHashMap(STRATEGY); return new Int2IntLinkedOpenCustomHashMap(STRATEGY);
} }
@@ -1,26 +1,20 @@
package speiger.src.collections.ints.maps; package speiger.src.collections.ints.maps;
import java.util.EnumSet; import speiger.src.collections.ints.base.BaseInt2IntOrderedMapTest;
import speiger.src.collections.ints.base.BaseInt2IntSortedMapTest;
import speiger.src.collections.ints.maps.impl.hash.Int2IntLinkedOpenHashMap; import speiger.src.collections.ints.maps.impl.hash.Int2IntLinkedOpenHashMap;
import speiger.src.collections.ints.maps.interfaces.Int2IntSortedMap; import speiger.src.collections.ints.maps.interfaces.Int2IntOrderedMap;
import speiger.src.collections.tests.SortedMapTests;
@SuppressWarnings("javadoc") @SuppressWarnings("javadoc")
public class Int2IntLinkedOpenHashMapTest extends BaseInt2IntSortedMapTest public class Int2IntLinkedOpenHashMapTest extends BaseInt2IntOrderedMapTest
{ {
@Override @Override
public EnumSet<SortedMapTests> getValidSortedMapTests() { return EnumSet.complementOf(EnumSet.of(SortedMapTests.SUB_MAP, SortedMapTests.TAIL_MAP, SortedMapTests.HEAD_MAP)); } public Int2IntOrderedMap createMap(int[] keys, int[] values)
@Override
public Int2IntSortedMap createMap(int[] keys, int[] values)
{ {
return new Int2IntLinkedOpenHashMap(keys, values); return new Int2IntLinkedOpenHashMap(keys, values);
} }
@Override @Override
public Int2IntSortedMap createEmptyMap() public Int2IntOrderedMap createEmptyMap()
{ {
return new Int2IntLinkedOpenHashMap(); return new Int2IntLinkedOpenHashMap();
} }
@@ -1,18 +1,12 @@
package speiger.src.collections.ints.maps; package speiger.src.collections.ints.maps;
import java.util.EnumSet;
import speiger.src.collections.ints.base.BaseInt2IntNavigableMapTest; import speiger.src.collections.ints.base.BaseInt2IntNavigableMapTest;
import speiger.src.collections.ints.maps.impl.tree.Int2IntRBTreeMap; import speiger.src.collections.ints.maps.impl.tree.Int2IntRBTreeMap;
import speiger.src.collections.ints.maps.interfaces.Int2IntNavigableMap; import speiger.src.collections.ints.maps.interfaces.Int2IntNavigableMap;
import speiger.src.collections.tests.SortedMapTests;
@SuppressWarnings("javadoc") @SuppressWarnings("javadoc")
public class Int2IntRBTreeMapTest extends BaseInt2IntNavigableMapTest public class Int2IntRBTreeMapTest extends BaseInt2IntNavigableMapTest
{ {
@Override
public EnumSet<SortedMapTests> getValidSortedMapTests() { return EnumSet.complementOf(EnumSet.of(SortedMapTests.GET_MOVE, SortedMapTests.MOVE, SortedMapTests.PUT_MOVE)); }
@Override @Override
public Int2IntNavigableMap createMap(int[] keys, int[] values) public Int2IntNavigableMap createMap(int[] keys, int[] values)
{ {
@@ -1,9 +1,6 @@
package speiger.src.collections.ints.sets; package speiger.src.collections.ints.sets;
import java.util.EnumSet;
import speiger.src.collections.ints.base.BaseIntNavigableSetTest; import speiger.src.collections.ints.base.BaseIntNavigableSetTest;
import speiger.src.collections.tests.SortedSetTest;
@SuppressWarnings("javadoc") @SuppressWarnings("javadoc")
public class IntAVLTreeSetTests extends BaseIntNavigableSetTest public class IntAVLTreeSetTests extends BaseIntNavigableSetTest
@@ -12,7 +9,4 @@ public class IntAVLTreeSetTests extends BaseIntNavigableSetTest
protected IntNavigableSet create(int[] data) { protected IntNavigableSet create(int[] data) {
return new IntAVLTreeSet(data); return new IntAVLTreeSet(data);
} }
@Override
protected EnumSet<SortedSetTest> getValidSortedSetTests() { return EnumSet.of(SortedSetTest.PEEK, SortedSetTest.POLL, SortedSetTest.HEAD_SET, SortedSetTest.SUB_SET, SortedSetTest.TAIL_SET);}
} }
@@ -1,10 +1,10 @@
package speiger.src.collections.ints.sets; package speiger.src.collections.ints.sets;
import speiger.src.collections.ints.base.BaseIntSortedSetTest; import speiger.src.collections.ints.base.BaseIntOrderedSetTest;
@SuppressWarnings("javadoc") @SuppressWarnings("javadoc")
public class IntArraySetTests extends BaseIntSortedSetTest public class IntArraySetTests extends BaseIntOrderedSetTest
{ {
@Override @Override
protected IntSortedSet create(int[] data) { return new IntArraySet(data.clone()); } protected IntOrderedSet create(int[] data) { return new IntArraySet(data.clone()); }
} }

Some files were not shown because too many files have changed in this diff Show More