83 Commits
Author SHA1 Message Date
KitsuneAlex 3f6ffea14e Add JetBrains annotations to common base classes 2021-09-25 20:23:01 +02:00
KitsuneAlex 9c09f2ee70 Clean up buildscript & add JB annotations as well as a proper build config 2021-09-25 20:22:25 +02:00
KitsuneAlex 3fc6bed79a Make Gradle wrapper executable on Linux and add IntelliJ .gitignore entries 2021-09-25 19:51:27 +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
82 changed files with 16135 additions and 1469 deletions
+11 -6
View File
@@ -1,28 +1,33 @@
# ---> Gradle # ---> Gradle
.gradle .gradle
/build/ /build/
gradle.properties
# Ignore Gradle GUI config # Ignore Gradle GUI config
gradle-app.setting gradle-app.setting
# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored)
!gradle-wrapper.jar
# Cache of project # Cache of project
.gradletasknamecache .gradletasknamecache
# # Work around https://youtrack.jetbrains.com/issue/IDEA-116898 # # Work around https://youtrack.jetbrains.com/issue/IDEA-116898
# gradle/wrapper/gradle-wrapper.properties # gradle/wrapper/gradle-wrapper.properties
.classpath .classpath
.project .project
gradle-wrapper.jar
---> Custom # IntelliJ
.idea/
out/
*.iws
*.ipr
*.iml
# ---> Custom
!/libs/ !/libs/
/.settings/ /.settings/
/bin/ /bin/
/storage/ /storage/
#Generated Code #Generated Code
/src/main/java/speiger/src/collections/booleans/* /src/main/java/speiger/src/collections/booleans/*
/src/main/java/speiger/src/collections/bytes/* /src/main/java/speiger/src/collections/bytes/*
+79
View File
@@ -0,0 +1,79 @@
# Changelog of versions
### 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
+89 -6
View File
@@ -1,22 +1,105 @@
# Primitive-Collections (To be Renamed) # Primitive-Collections
This is a Simple Primitive Collections Library i started as a hobby Project. This is a Simple Primitive Collections Library i started as a hobby Project.
It is based on Java's Collection Library and FastUtil. It is based on Java's Collection Library and FastUtil.
But its focus is a different one. But its focus is a different one.
## Main Features: ## Main Features:
ArraysList, HashSet/Map (Linked & HashControl), TreeSet/Map (RB & AVL), Priority Queue. - ArrayLists / LinkedLists
- HashSet/Map (Linked & HashControl)
- TreeSet/Map (RB & AVL)
- EnumMap
- Immutable Maps/Lists/Sets
- Priority Queue
- Streams
- SplitIterators
- Iterators
- Pairs
## 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.
- forEach: Allows to input a second element into a forEach move allowing for more flexibility for Method References
- Collection:
- containsAny: Allows to test if another collection contains an of the elements of the tested collection.
- primitiveStream: Provides access to the closest Java Stream Type.
- 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.
- SortedSet:
- addAndMoveToFirst/Last (From FastUtil but moved to Interface): Allows to add a element to the first/last position of a sorted set.
- moveToFirst/Last: Moves the desired element at the first/last position of the SortedSet.
- pollFirst/Last: Allows to poll the first/last element of the set.
- Map:
- putAll: putAll but in Array form.
- putAllIfAbsent: Puts only the elements that are absent.
- addTo (Only Primitives Values) (From FastUtil but moved to Interface): allows to add to the value of a given key. If not present it will be added. (Accumulator)
- addToAll: Same as addTo but bulkVersion.
- removeOrDefault: removes a Element and if not present returns the default value instead of the present value.
- mergeAll: BulkVersion of Merge function.
- 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: # How to install
Using Gradle:
```gradle
repositories {
maven {
url = "https://maven.speiger.com/repository/main"
}
}
dependencies {
compile 'de.speiger:Primitive-Collections:0.4.0'
}
```
Direct:
| Version | Jar | Sources | Java Doc |
|--------- |------------------------------------------------------------------------------------------------------------------------------ |-------------------------------------------------------------------------------------------------------------------------------------- |-------------------------------------------------------------------------------------------------------------------------------------- |
| 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) |
| 0.3.5 | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.3.5/Primitive-Collections-0.3.5.jar) | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.3.5/Primitive-Collections-0.3.5-sources.jar) | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.3.5/Primitive-Collections-0.3.5-javadoc.jar) |
| 0.3.4 | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.3.4/Primitive-Collections-0.3.4.jar) | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.3.4/Primitive-Collections-0.3.4-sources.jar) | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.3.4/Primitive-Collections-0.3.4-javadoc.jar) |
| 0.3.3 | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.3.3/Primitive-Collections-0.3.3.jar) | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.3.3/Primitive-Collections-0.3.3-sources.jar) | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.3.3/Primitive-Collections-0.3.3-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 - 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.
+70 -20
View File
@@ -1,34 +1,40 @@
plugins { buildscript {
id 'java-library' def config = new Properties()
} file('build.properties').withInputStream(config.&load)
project.ext.config = config
tasks.withType(JavaCompile) {
options.encoding = 'UTF-8'
} }
apply plugin: 'java' apply plugin: 'java'
apply plugin: 'eclipse' apply plugin: 'eclipse'
apply plugin: 'maven'
repositories { repositories {
jcenter() mavenCentral()
flatDir { google()
dirs 'libs'
maven {
url = "https://maven.speiger.com/repository/main"
} }
} }
archivesBaseName = 'Primitive Collections' archivesBaseName = config.project_name
version = 'Beta'; version = config.project_version
group = config.project_group
sourceCompatibility = targetCompatibility = compileJava.sourceCompatibility = compileJava.targetCompatibility = '1.8' sourceCompatibility = config.java_source_version
targetCompatibility = config.java_target_version
javadoc { javadoc {
options.tags = [ "implSpec", "note" ] options.tags = [ "implSpec", "note" ]
failOnError = false
options.memberLevel = JavadocMemberLevel.PUBLIC
options.quiet()
} }
eclipse { eclipse {
classpath { classpath {
downloadJavadoc = true downloadJavadoc = true
downloadSources = true downloadSources = true
file { file {
whenMerged { whenMerged {
//Enforce a custom container and allowing access to the sun.misc package which is nessesary for EnumMaps //Enforce a custom container and allowing access to the sun.misc package which is nessesary for EnumMaps
@@ -38,9 +44,15 @@ eclipse {
} }
} }
tasks.withType(JavaCompile) {
sourceCompatibility = config.java_source_version
targetCompatibility = config.java_target_version
options.encoding = 'UTF-8'
}
compileJava { compileJava {
options.compilerArgs << '-XDignore.symbol.file' options.compilerArgs << '-XDignore.symbol.file'
options.fork = true // may not needed on 1.8 options.fork = true
options.forkOptions.executable = 'javac' // may not needed on 1.8 options.forkOptions.executable = 'javac' // may not needed on 1.8
} }
@@ -53,7 +65,11 @@ configurations {
} }
dependencies { dependencies {
compile 'SimpleCodeGenerator:Simple Code Generator:1.0.1' implementation group: 'org.jetbrains', name: 'annotations', version: config.annotations_version
builderCompile group: 'de.speiger', name: 'Simple-Code-Generator', version: config.scg_version
runtimeOnly group: 'de.speiger', name: 'Simple-Code-Generator', version: config.scg_version
testImplementation 'junit:junit:4.12' testImplementation 'junit:junit:4.12'
} }
@@ -64,6 +80,14 @@ task generateSource(type: JavaExec) {
main = 'speiger.src.builder.PrimitiveCollectionsBuilder' main = 'speiger.src.builder.PrimitiveCollectionsBuilder'
} }
task forceGenerateSource(type: JavaExec) {
group = 'internal'
description = 'Builds the sourcecode forceful'
classpath = sourceSets.builder.runtimeClasspath
main = 'speiger.src.builder.PrimitiveCollectionsBuilder'
args = ['true']
}
task javadocJar(type: Jar) { task javadocJar(type: Jar) {
from javadoc from javadoc
classifier = 'javadoc' classifier = 'javadoc'
@@ -74,11 +98,6 @@ task srcJar(type: Jar) {
classifier = 'sources' classifier = 'sources'
} }
javadoc.failOnError = false
javadoc.options.memberLevel = JavadocMemberLevel.PUBLIC
//javadoc.options.showAll()
javadoc.options.quiet()
artifacts { artifacts {
archives javadocJar archives javadocJar
archives srcJar archives srcJar
@@ -87,3 +106,34 @@ artifacts {
test { test {
useJUnit() useJUnit()
} }
uploadArchives {
repositories.mavenDeployer {
repository(url: 'https://maven.speiger.com/repository/main') {
authentication(userName: project.properties.mavenUser, password: project.properties.mavenPassword)
}
snapshotRepository(url: 'https://maven.speiger.com/repository/main') {
authentication(userName: project.properties.mavenUser, password: project.properties.mavenPassword)
}
pom {
version = project.version
artifactId = config.artifact_id
groupId = config.artifact_group
project {
licenses {
license {
name = 'The Apache License, Version 2.0'
url = 'http://www.apache.org/licenses/LICENSE-2.0.txt'
}
}
developers {
developer {
id = 'speiger'
name = 'Speiger'
email = 'speiger@gmx.net'
}
}
}
}
}
}
+13
View File
@@ -0,0 +1,13 @@
project_name=PrimitiveCollections
project_id=primitivecollections
project_group=speiger.src.collections
project_version=0.4.0
artifact_group=de.speiger
artifact_id=Primitive-Collections
java_source_version=11
java_target_version=8
annotations_version=22.0.0
scg_version=1.0.4
Binary file not shown.
Vendored Regular → Executable
View File
Binary file not shown.
Binary file not shown.
@@ -35,28 +35,50 @@ 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("<>");
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 +100,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;
} }
@@ -109,6 +133,7 @@ public class GlobalVariables
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();
} }
@@ -130,21 +155,28 @@ public class GlobalVariables
//Final Classes //Final Classes
addClassMapper("ARRAY_LIST", "ArrayList"); addClassMapper("ARRAY_LIST", "ArrayList");
addClassMapper("LINKED_LIST", "LinkedList");
addAbstractMapper("IMMUTABLE_LIST", "Immutable%sList");
addClassMapper("ARRAY_FIFO_QUEUE", "ArrayFIFOQueue"); addClassMapper("ARRAY_FIFO_QUEUE", "ArrayFIFOQueue");
addClassMapper("ARRAY_PRIORITY_QUEUE", "ArrayPriorityQueue"); addClassMapper("ARRAY_PRIORITY_QUEUE", "ArrayPriorityQueue");
addClassMapper("HEAP_PRIORITY_QUEUE", "HeapPriorityQueue"); addClassMapper("HEAP_PRIORITY_QUEUE", "HeapPriorityQueue");
addClassMapper("LINKED_CUSTOM_HASH_SET", "LinkedOpenCustomHashSet"); addClassMapper("LINKED_CUSTOM_HASH_SET", "LinkedOpenCustomHashSet");
addClassMapper("LINKED_HASH_SET", "LinkedOpenHashSet"); addClassMapper("LINKED_HASH_SET", "LinkedOpenHashSet");
addAbstractMapper("IMMUTABLE_HASH_SET", "Immutable%sOpenHashSet");
addClassMapper("CUSTOM_HASH_SET", "OpenCustomHashSet"); addClassMapper("CUSTOM_HASH_SET", "OpenCustomHashSet");
addClassMapper("HASH_SET", "OpenHashSet"); addClassMapper("HASH_SET", "OpenHashSet");
addAbstractBiMapper("IMMUTABLE_HASH_MAP", "Immutable%sOpenHashMap", "2");
addBiClassMapper("LINKED_CUSTOM_HASH_MAP", "LinkedOpenCustomHashMap", "2"); addBiClassMapper("LINKED_CUSTOM_HASH_MAP", "LinkedOpenCustomHashMap", "2");
addBiClassMapper("LINKED_HASH_MAP", "LinkedOpenHashMap", "2"); addBiClassMapper("LINKED_HASH_MAP", "LinkedOpenHashMap", "2");
addBiClassMapper("CUSTOM_HASH_MAP", "OpenCustomHashMap", "2"); addBiClassMapper("CUSTOM_HASH_MAP", "OpenCustomHashMap", "2");
addBiClassMapper("AVL_TREE_MAP", "AVLTreeMap", "2"); addBiClassMapper("AVL_TREE_MAP", "AVLTreeMap", "2");
addBiClassMapper("RB_TREE_MAP", "RBTreeMap", "2"); addBiClassMapper("RB_TREE_MAP", "RBTreeMap", "2");
addFunctionValueMappers("LINKED_ENUM_MAP", valueType.isObject() ? "LinkedEnum2ObjectMap" : "LinkedEnum2%sMap");
addFunctionValueMappers("ENUM_MAP", valueType.isObject() ? "Enum2ObjectMap" : "Enum2%sMap"); addFunctionValueMappers("ENUM_MAP", valueType.isObject() ? "Enum2ObjectMap" : "Enum2%sMap");
addBiClassMapper("HASH_MAP", "OpenHashMap", "2"); addBiClassMapper("HASH_MAP", "OpenHashMap", "2");
addBiClassMapper("ARRAY_MAP", "ArrayMap", "2"); addBiClassMapper("ARRAY_MAP", "ArrayMap", "2");
addBiClassMapper("IMMUTABLE_PAIR", "ImmutablePair", "");
addBiClassMapper("MUTABLE_PAIR", "MutablePair", "");
addClassMapper("RB_TREE_SET", "RBTreeSet"); addClassMapper("RB_TREE_SET", "RBTreeSet");
addClassMapper("AVL_TREE_SET", "AVLTreeSet"); addClassMapper("AVL_TREE_SET", "AVLTreeSet");
addClassMapper("ARRAY_SET", "ArraySet"); addClassMapper("ARRAY_SET", "ArraySet");
@@ -161,18 +193,22 @@ public class GlobalVariables
addClassMapper("SETS", "Sets"); addClassMapper("SETS", "Sets");
addClassMapper("COLLECTIONS", "Collections"); addClassMapper("COLLECTIONS", "Collections");
addClassMapper("ARRAYS", "Arrays"); addClassMapper("ARRAYS", "Arrays");
addClassMapper("PRIORITY_QUEUES", "PriorityQueues");
addClassMapper("SPLIT_ITERATORS", "Splititerators"); addClassMapper("SPLIT_ITERATORS", "Splititerators");
addClassMapper("ITERATORS", "Iterators"); addClassMapper("ITERATORS", "Iterators");
addClassMapper("ITERABLES", "Iterables");
addBiClassMapper("MAPS", "Maps", "2"); addBiClassMapper("MAPS", "Maps", "2");
//Interfaces //Interfaces
addClassMapper("LIST_ITERATOR", "ListIterator"); addClassMapper("LIST_ITERATOR", "ListIterator");
addClassMapper("BI_ITERATOR", "BidirectionalIterator"); addClassMapper("BI_ITERATOR", "BidirectionalIterator");
addBiClassMapper("BI_CONSUMER", "Consumer", ""); addBiClassMapper("BI_CONSUMER", "Consumer", "");
addClassMapper("BI_OBJECT_CONSUMER", "ObjectConsumer");
addClassMapper("SPLIT_ITERATOR", "Splititerator"); addClassMapper("SPLIT_ITERATOR", "Splititerator");
addClassMapper("ITERATOR", "Iterator"); addClassMapper("ITERATOR", "Iterator");
addClassMapper("ITERABLE", "Iterable"); addClassMapper("ITERABLE", "Iterable");
addClassMapper("COLLECTION", "Collection"); addClassMapper("COLLECTION", "Collection");
addClassMapper("TO_OBJECT_FUNCTION", "2ObjectFunction");
addBiClassMapper("FUNCTION", "Function", "2"); addBiClassMapper("FUNCTION", "Function", "2");
addClassMapper("LIST_ITER", "ListIter"); addClassMapper("LIST_ITER", "ListIter");
addClassMapper("LIST", "List"); addClassMapper("LIST", "List");
@@ -180,8 +216,10 @@ public class GlobalVariables
addBiClassMapper("SORTED_MAP", "SortedMap", "2"); addBiClassMapper("SORTED_MAP", "SortedMap", "2");
addBiClassMapper("MAP", "Map", "2"); addBiClassMapper("MAP", "Map", "2");
addClassMapper("NAVIGABLE_SET", "NavigableSet"); addClassMapper("NAVIGABLE_SET", "NavigableSet");
addBiClassMapper("PAIR", "Pair", "");
addClassMapper("PRIORITY_QUEUE", "PriorityQueue"); addClassMapper("PRIORITY_QUEUE", "PriorityQueue");
addClassMapper("PRIORITY_DEQUEUE", "PriorityDequeue"); addClassMapper("PRIORITY_DEQUEUE", "PriorityDequeue");
addClassMapper("PREDICATE", "2BooleanFunction");
addClassMapper("SORTED_SET", "SortedSet"); addClassMapper("SORTED_SET", "SortedSet");
addClassMapper("SET", "Set"); addClassMapper("SET", "Set");
addClassMapper("STRATEGY", "Strategy"); addClassMapper("STRATEGY", "Strategy");
@@ -189,17 +227,20 @@ public class GlobalVariables
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");
} }
@@ -211,11 +252,10 @@ public class GlobalVariables
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 +269,28 @@ 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");
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"); if(type.isObject()) addFunctionMapper("REMOVE_VALUE", "rem");
addFunctionMapper("POP", "pop"); else addSimpleMapper("REMOVE_VALUE", "remove");
addFunctionMapper("PUSH", "push");
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");
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 +378,12 @@ public class GlobalVariables
else operators.add(new SimpleMapper(type.name()+"["+pattern+"]", pattern, value)); else operators.add(new SimpleMapper(type.name()+"["+pattern+"]", pattern, value));
} }
private void addValueAnnontion(String pattern, String value)
{
if(valueType == ClassType.OBJECT) operators.add(new LineMapper(valueType.name()+"["+pattern+"]", pattern));
else operators.add(new SimpleMapper(valueType.name()+"["+pattern+"]", pattern, value));
}
private void addComment(String pattern, String value) private void addComment(String pattern, String value)
{ {
if(type == ClassType.OBJECT) operators.add(new InjectMapper(type.name()+"["+pattern+"]", pattern, value).removeBraces()); if(type == ClassType.OBJECT) operators.add(new InjectMapper(type.name()+"["+pattern+"]", pattern, value).removeBraces());
@@ -67,9 +67,13 @@ public class PrimitiveCollectionsBuilder extends TemplateProcessor
} }
} }
enumRequired.add("EnumMap"); enumRequired.add("EnumMap");
enumRequired.add("LinkedEnumMap");
biRequired.put("BiConsumer", ""); biRequired.put("BiConsumer", "");
biRequired.put("UnaryOperator", ""); biRequired.put("UnaryOperator", "");
addBiClass("Function", "Maps", "Map", "SortedMap", "NavigableMap", "AbstractMap", "OpenHashMap", "LinkedOpenHashMap", "OpenCustomHashMap", "LinkedOpenCustomHashMap", "ArrayMap", "RBTreeMap", "AVLTreeMap"); biRequired.put("Pair", "");
biRequired.put("MutablePair", "");
biRequired.put("ImmutablePair", "");
addBiClass("Function", "Maps", "Map", "SortedMap", "NavigableMap", "AbstractMap", "ImmutableOpenHashMap", "OpenHashMap", "LinkedOpenHashMap", "OpenCustomHashMap", "LinkedOpenCustomHashMap", "ArrayMap", "RBTreeMap", "AVLTreeMap");
nameRemapper.put("BiConsumer", "%sConsumer"); nameRemapper.put("BiConsumer", "%sConsumer");
nameRemapper.put("IArray", "I%sArray"); nameRemapper.put("IArray", "I%sArray");
nameRemapper.put("AbstractMap", "Abstract%sMap"); nameRemapper.put("AbstractMap", "Abstract%sMap");
@@ -77,9 +81,14 @@ public class PrimitiveCollectionsBuilder extends TemplateProcessor
nameRemapper.put("AbstractSet", "Abstract%sSet"); nameRemapper.put("AbstractSet", "Abstract%sSet");
nameRemapper.put("AbstractList", "Abstract%sList"); nameRemapper.put("AbstractList", "Abstract%sList");
nameRemapper.put("EnumMap", "Enum2%sMap"); nameRemapper.put("EnumMap", "Enum2%sMap");
nameRemapper.put("LinkedEnumMap", "LinkedEnum2%sMap");
nameRemapper.put("ImmutableList", "Immutable%sList");
nameRemapper.put("ImmutableOpenHashSet", "Immutable%sOpenHashSet");
nameRemapper.put("ImmutableOpenHashMap", "Immutable%sOpenHashMap");
addBlockage(ClassType.OBJECT, "Consumer", "Comparator", "Stack"); addBlockage(ClassType.OBJECT, "Consumer", "Comparator", "Stack");
addBlockage(ClassType.BOOLEAN, "ArraySet", "AVLTreeSet", "RBTreeSet", "SortedSet", "NavigableSet", "OpenHashSet", "OpenCustomHashSet", "LinkedOpenHashSet", "LinkedOpenCustomHashSet"); addBlockage(ClassType.BOOLEAN, "ArraySet", "AVLTreeSet", "RBTreeSet", "SortedSet", "NavigableSet", "OpenHashSet", "OpenCustomHashSet", "LinkedOpenHashSet", "LinkedOpenCustomHashSet");
addBlockage(ClassType.BOOLEAN, "SortedMap", "NavigableMap", "OpenHashMap", "LinkedOpenHashMap", "OpenCustomHashMap", "LinkedOpenCustomHashMap", "ArrayMap", "RBTreeMap", "AVLTreeMap"); addBlockage(ClassType.BOOLEAN, "ImmutableOpenHashMap", "ImmutableOpenHashSet", "SortedMap", "NavigableMap", "OpenHashMap", "LinkedOpenHashMap", "OpenCustomHashMap", "LinkedOpenCustomHashMap", "ArrayMap", "RBTreeMap", "AVLTreeMap");
} }
protected void create(ClassType mainType, ClassType subType) protected void create(ClassType mainType, ClassType subType)
@@ -147,8 +156,12 @@ public class PrimitiveCollectionsBuilder extends TemplateProcessor
{ {
if(args.length == 0) { if(args.length == 0) {
new PrimitiveCollectionsBuilder().process(false); new PrimitiveCollectionsBuilder().process(false);
} else if(args.length == 1) {
new PrimitiveCollectionsBuilder().process(Boolean.parseBoolean(args[0]));
} else if(args.length == 3) { } else if(args.length == 3) {
new PrimitiveCollectionsBuilder(Paths.get(args[0]), Paths.get(args[1]), Paths.get(args[2])).process(false); new PrimitiveCollectionsBuilder(Paths.get(args[0]), Paths.get(args[1]), Paths.get(args[2])).process(false);
} else if(args.length == 4) {
new PrimitiveCollectionsBuilder(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);
@@ -55,8 +55,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 +65,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.
@@ -188,6 +188,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,18 @@
package speiger.src.collections.PACKAGE.collections; package speiger.src.collections.PACKAGE.collections;
#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;
import speiger.src.collections.objects.collections.ObjectIterable;
#endif #endif
import speiger.src.collections.PACKAGE.functions.function.TO_OBJECT_FUNCTION;
import speiger.src.collections.PACKAGE.functions.consumer.BI_OBJECT_CONSUMER;
import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
import speiger.src.collections.PACKAGE.collections.SPLIT_ITERATOR; import speiger.src.collections.PACKAGE.collections.SPLIT_ITERATOR;
import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS; import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS;
import speiger.src.collections.PACKAGE.utils.ITERABLES;
/** /**
* A Type-Specific {@link Iterable} that reduces (un)boxing * A Type-Specific {@link Iterable} that reduces (un)boxing
@@ -22,8 +27,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 +57,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_OBJECT_CONSUMER KKS_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 +77,97 @@ public interface ITERABLE KEY_GENERIC_TYPE extends Iterable<CLASS_TYPE>
*/ */
@Override @Override
default SPLIT_ITERATOR KEY_GENERIC_TYPE spliterator() { return SPLIT_ITERATORS.createUnknownSplititerator(iterator(), 0); } default SPLIT_ITERATOR KEY_GENERIC_TYPE spliterator() { return SPLIT_ITERATORS.createUnknownSplititerator(iterator(), 0); }
/**
* A Helper function to reduce the usage of Streams and allows to convert a Iterable to something else.
* @param mapper the mapping function
* @param <E> The return type.
* @return a new Iterable that returns the desired result
*/
default <E> ObjectIterable<E> map(TO_OBJECT_FUNCTION KKS_GENERIC_TYPE<E> mapper) {
return ITERABLES.map(this, mapper);
}
/**
* A Helper function to reduce the usage of Streams and allows to convert a Iterable to something else.
* @param mapper the flatMapping function
* @param <V> The return type supplier.
* @param <E> The return type.
* @return a new Iterable that returns the desired result
*/
default <E, V extends Iterable<E>> ObjectIterable<E> flatMap(TO_OBJECT_FUNCTION KKS_GENERIC_TYPE<V> mapper) {
return ITERABLES.flatMap(this, mapper);
}
/**
* A Helper function to reduce the usage of Streams and allows to convert a Iterable to something else.
* @param mapper the flatMapping function
* @param <E> The return type.
* @return a new Iterable that returns the desired result
*/
default <E> ObjectIterable<E> arrayflatMap(TO_OBJECT_FUNCTION KKS_GENERIC_TYPE<E[]> mapper) {
return ITERABLES.arrayFlatMap(this, mapper);
}
/**
* A Helper function to reduce the usage of Streams and allows to filter out unwanted elements
* @param filter the elements that should be kept.
* @return a Iterable that filtered out all unwanted elements
*/
default ITERABLE KEY_GENERIC_TYPE filter(PREDICATE KEY_GENERIC_TYPE filter) {
return ITERABLES.filter(this, filter);
}
/**
* 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;
}
} }
@@ -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.PACKAGE.functions.consumer.BI_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_OBJECT_CONSUMER KKS_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
while(hasNext()) { action.accept(NEXT(), input); }
}
/** /**
* 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
} }
@@ -43,9 +43,7 @@ public abstract class ABSTRACT_LIST KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION
*/ */
@Override @Override
public boolean addAll(COLLECTION KEY_GENERIC_TYPE c) { public boolean addAll(COLLECTION KEY_GENERIC_TYPE c) {
boolean modified = false; return addAll(size(), c);
for(ITERATOR KEY_GENERIC_TYPE iter = c.iterator();iter.hasNext();modified |= add(iter.NEXT()));
return modified;
} }
/** /**
@@ -55,9 +53,18 @@ public abstract class ABSTRACT_LIST KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION
*/ */
@Override @Override
public boolean addAll(LIST KEY_GENERIC_TYPE c) { public boolean addAll(LIST KEY_GENERIC_TYPE c) {
boolean modified = false; return addAll(size(), c);
for(ITERATOR KEY_GENERIC_TYPE iter = c.iterator();iter.hasNext();modified |= add(iter.NEXT())); }
return modified;
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
public boolean addAll(Collection<? extends CLASS_TYPE> c)
{
return c instanceof COLLECTION ? addAll((COLLECTION KEY_GENERIC_TYPE)c) : addAll(size(), c);
} }
/** /**
@@ -26,6 +26,8 @@ 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.PACKAGE.functions.consumer.BI_OBJECT_CONSUMER;
import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
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 +90,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 +119,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);
} }
@@ -201,7 +204,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 +229,6 @@ public class ARRAY_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
* @param index the index where to append the elements to * @param index the index where to append the elements to
* @param c the elements to append to the list * @param c the elements to append to the list
* @throws IndexOutOfBoundsException if index is outside of the lists range * @throws IndexOutOfBoundsException if index is outside of the lists range
* @deprecated if type is primitive
*/ */
@Override @Override
@Primitive @Primitive
@@ -238,7 +240,7 @@ public class ARRAY_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
if(index != size) System.arraycopy(data, index, data, index+add, size - index); if(index != size) System.arraycopy(data, index, data, index+add, size - index);
size+=add; size+=add;
Iterator<? extends CLASS_TYPE> iter = c.iterator(); Iterator<? extends CLASS_TYPE> iter = c.iterator();
while(add != 0) data[index++] = OBJ_TO_KEY(iter.next()); while(add-- != 0) data[index++] = OBJ_TO_KEY(iter.next());
return true; return true;
} }
@@ -248,7 +250,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 +269,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) {
@@ -289,7 +289,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 +313,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;
} }
@@ -385,7 +385,6 @@ public class ARRAY_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
* 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 +396,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 +419,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 +447,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 +458,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 +544,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 +590,49 @@ 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_OBJECT_CONSUMER KKS_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
for(int i = 0;i<size;i++)
action.accept(data[i], input);
}
@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;
}
/** /**
* 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 +678,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]));
@@ -680,6 +721,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 +737,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 +747,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 +771,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 +797,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
@@ -921,6 +968,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
@@ -935,7 +997,7 @@ public class ARRAY_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
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) {
@@ -0,0 +1,435 @@
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.Objects;
#if TYPE_OBJECT
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.PACKAGE.functions.consumer.BI_OBJECT_CONSUMER;
import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
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 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];
}
/**
* 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_OBJECT_CONSUMER KKS_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
for(int i = 0,m=data.length;i<m;i++)
action.accept(data[i], input);
}
@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;
}
@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(); }
#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(); }
#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]);
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);
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); }
}
@@ -152,7 +152,7 @@ public interface LIST KEY_GENERIC_TYPE extends COLLECTION KEY_GENERIC_TYPE, 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
@@ -223,7 +223,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 +239,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();
@@ -24,6 +24,7 @@ import speiger.src.collections.objects.collections.ObjectIterator;
#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 +46,22 @@ public abstract class ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE extends AbstractMap<CL
return this; return this;
} }
#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 +77,19 @@ 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]);
}
@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 +144,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);
@@ -178,6 +214,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) {
@@ -4,12 +4,19 @@ import java.util.Comparator;
import java.util.Map; import java.util.Map;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.Objects;
import speiger.src.collections.PACKAGE.collections.BI_ITERATOR; import speiger.src.collections.PACKAGE.collections.BI_ITERATOR;
#if !TYPE_OBJECT #if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.functions.COMPARATOR; import speiger.src.collections.PACKAGE.functions.COMPARATOR;
import speiger.src.collections.PACKAGE.functions.CONSUMER; import speiger.src.collections.PACKAGE.functions.CONSUMER;
#endif #endif
#if !TYPE_OBJECT && !VALUE_OBJECT
import speiger.src.collections.PACKAGE.functions.consumer.BI_OBJECT_CONSUMER;
#endif
#if !TYPE_OBJECT || VALUE_BOOLEAN
import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
#endif
import speiger.src.collections.PACKAGE.functions.consumer.BI_CONSUMER; import speiger.src.collections.PACKAGE.functions.consumer.BI_CONSUMER;
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;
@@ -25,6 +32,18 @@ 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;
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
import speiger.src.collections.VALUE_PACKAGE.functions.consumer.VALUE_BI_OBJECT_CONSUMER;
import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_PREDICATE;
#endif
#if !TYPE_OBJECT #if !TYPE_OBJECT
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;
@@ -423,6 +442,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 +518,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];
@@ -635,6 +672,73 @@ public class LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends CUSTOM_HASH_M
} }
} }
@Override
public <E> void forEach(E input, ObjectObjectConsumer<MAP.Entry KEY_VALUE_GENERIC_TYPE, E> action) {
Objects.requireNonNull(action);
if(size() <= 0) return;
int index = firstIndex;
while(index != -1) {
action.accept(new BasicEntryKV_BRACES(keys[index], values[index]), input);
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 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 @Override
@Deprecated @Deprecated
public boolean contains(Object o) { public boolean contains(Object o) {
@@ -771,17 +875,6 @@ public class LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends CUSTOM_HASH_M
return POLL_LAST_ENTRY_KEY(); return POLL_LAST_ENTRY_KEY();
} }
#if TYPE_OBJECT
@Override
public void forEach(Consumer KEY_SUPER_GENERIC_TYPE action) {
int index = firstIndex;
while(index != -1){
action.accept(keys[index]);
index = (int)links[index];
}
}
#else
@Override @Override
public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) { public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) {
int index = firstIndex; int index = firstIndex;
@@ -791,7 +884,65 @@ public class LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends CUSTOM_HASH_M
} }
} }
#endif @Override
public <E> void forEach(E input, BI_OBJECT_CONSUMER KKS_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
if(size() <= 0) return;
int index = firstIndex;
while(index != -1){
action.accept(keys[index], input);
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;
}
@Override
public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return EMPTY_KEY_VALUE;
int index = firstIndex;
while(index != -1){
if(filter.TEST_VALUE(keys[index])) return keys[index];
index = (int)links[index];
}
return EMPTY_KEY_VALUE;
}
@Override @Override
public COMPARATOR KEY_GENERIC_TYPE comparator() { return null; } public COMPARATOR KEY_GENERIC_TYPE comparator() { return null; }
@@ -840,16 +991,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 +999,65 @@ public class LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends CUSTOM_HASH_M
index = (int)links[index]; index = (int)links[index];
} }
} }
#endif
@Override
public <E> void forEach(E input, VALUE_BI_OBJECT_CONSUMER VVS_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
if(size() <= 0) return;
int index = firstIndex;
while(index != -1){
action.accept(values[index], input);
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;
}
@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;
}
} }
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> {
@@ -11,10 +11,19 @@ import speiger.src.collections.PACKAGE.collections.ITERATOR;
import speiger.src.collections.PACKAGE.functions.CONSUMER; import speiger.src.collections.PACKAGE.functions.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 !TYPE_OBJECT && !VALUE_OBJECT
import speiger.src.collections.PACKAGE.functions.consumer.BI_OBJECT_CONSUMER;
#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 +31,30 @@ 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 #if !SAME_TYPE
import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_UNARY_OPERATOR;
#if !VALUE_OBJECT
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
#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
import speiger.src.collections.VALUE_PACKAGE.functions.consumer.VALUE_BI_OBJECT_CONSUMER;
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 +62,7 @@ import speiger.src.collections.utils.HashUtil;
* @Type(T) * @Type(T)
* @ValueType(V) * @ValueType(V)
*/ */
public class CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE public class CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE implements ITrimmable
{ {
/** The Backing keys array */ /** The Backing keys array */
protected transient KEY_TYPE[] keys; protected transient KEY_TYPE[] keys;
@@ -256,7 +281,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;
@@ -276,7 +301,7 @@ public class CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VAL
#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 == null && VALUE_EQUALS(values[nullIndex], getDefaultReturnValue())) || EQUALS_VALUE_TYPE(values[nullIndex], value)) return true;
for(int i = nullIndex-1;i >= 0;i--) for(int i = nullIndex-1;i >= 0;i--)
@@ -285,12 +310,19 @@ public class CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VAL
} }
@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
public VALUE_TYPE REMOVE_VALUEOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) {
int slot = findIndex(key);
if(slot < 0) return defaultValue;
return removeIndex(slot);
}
@Override @Override
@Deprecated @Deprecated
public CLASS_VALUE_TYPE remove(Object key) { public CLASS_VALUE_TYPE remove(Object key) {
@@ -416,6 +448,95 @@ 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) {
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) {
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;
}
return values[index];
}
@Override
public VALUE_TYPE COMPUTE_IF_PRESENT(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) {
int index = findIndex(key);
if(index < 0) 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) {
int index = findIndex(key);
VALUE_TYPE newValue = index < 0 ? 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 ? 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 +549,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 +604,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);
@@ -620,13 +771,95 @@ 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<MAP.Entry KEY_VALUE_GENERIC_TYPE, E> action) {
Objects.requireNonNull(action);
if(size() <= 0) return;
if(containsNull) action.accept(new BasicEntryKV_BRACES(keys[nullIndex], values[nullIndex]), input);
for(int i = nullIndex-1;i>=0;i--) {
if(!strategy.equals(keys[i], EMPTY_KEY_VALUE)) action.accept(new BasicEntryKV_BRACES(keys[i], values[i]), input);
}
}
@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 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 @Override
public int size() { public int size() {
return CUSTOM_HASH_MAP.this.size(); return CUSTOM_HASH_MAP.this.size();
@@ -708,22 +941,66 @@ 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
public void forEach(Consumer KEY_SUPER_GENERIC_TYPE action) {
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]);
}
#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(strategy.equals(keys[i], EMPTY_KEY_VALUE)) action.accept(keys[i]); if(strategy.equals(keys[i], EMPTY_KEY_VALUE)) action.accept(keys[i]);
} }
#endif
@Override
public <E> void forEach(E input, BI_OBJECT_CONSUMER KKS_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
if(size() <= 0) return;
if(containsNull) action.accept(keys[nullIndex], input);
for(int i = nullIndex-1;i>=0;i--) {
if(!strategy.equals(keys[i], EMPTY_KEY_VALUE)) action.accept(keys[i], input);
}
}
@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;
}
@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;
}
} }
private class Values extends VALUE_ABSTRACT_COLLECTION VALUE_GENERIC_TYPE { private class Values extends VALUE_ABSTRACT_COLLECTION VALUE_GENERIC_TYPE {
@@ -760,21 +1037,66 @@ 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]);
} }
#endif
@Override
public <E> void forEach(E input, VALUE_BI_OBJECT_CONSUMER VVS_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
if(size() <= 0) return;
if(containsNull) action.accept(values[nullIndex], input);
for(int i = nullIndex-1;i>=0;i--) {
if(!strategy.equals(keys[i], EMPTY_KEY_VALUE)) action.accept(values[i], input);
}
}
@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;
}
@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;
}
} }
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> {
@@ -4,15 +4,19 @@ import java.util.Comparator;
import java.util.Map; import java.util.Map;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import java.util.function.Consumer; import java.util.function.Consumer;
#if TYPE_OBJECT
import java.util.Objects; import java.util.Objects;
#endif
import speiger.src.collections.PACKAGE.collections.BI_ITERATOR; import speiger.src.collections.PACKAGE.collections.BI_ITERATOR;
#if !TYPE_OBJECT #if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.functions.COMPARATOR; import speiger.src.collections.PACKAGE.functions.COMPARATOR;
import speiger.src.collections.PACKAGE.functions.CONSUMER; import speiger.src.collections.PACKAGE.functions.CONSUMER;
#endif #endif
#if !TYPE_OBJECT && !VALUE_OBJECT
import speiger.src.collections.PACKAGE.functions.consumer.BI_OBJECT_CONSUMER;
#endif
#if !TYPE_OBJECT || VALUE_BOOLEAN
import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
#endif
import speiger.src.collections.PACKAGE.functions.consumer.BI_CONSUMER; import speiger.src.collections.PACKAGE.functions.consumer.BI_CONSUMER;
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;
@@ -27,6 +31,18 @@ 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;
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
import speiger.src.collections.VALUE_PACKAGE.functions.consumer.VALUE_BI_OBJECT_CONSUMER;
import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_PREDICATE;
#endif
#if !TYPE_OBJECT #if !TYPE_OBJECT
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;
@@ -46,7 +62,7 @@ import speiger.src.collections.utils.HashUtil;
public class LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE extends HASH_MAP KEY_VALUE_GENERIC_TYPE implements SORTED_MAP KEY_VALUE_GENERIC_TYPE public class LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE extends HASH_MAP KEY_VALUE_GENERIC_TYPE implements SORTED_MAP KEY_VALUE_GENERIC_TYPE
{ {
/** The Backing array for links between nodes. Left 32 Bits => Previous Entry, Right 32 Bits => Next Entry */ /** The Backing array for links between nodes. Left 32 Bits => Previous Entry, Right 32 Bits => Next Entry */
protected long[] links; protected transient long[] links;
/** The First Index in the Map */ /** The First Index in the Map */
protected int firstIndex = -1; protected int firstIndex = -1;
/** The Last Index in the Map */ /** The Last Index in the Map */
@@ -403,6 +419,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 +495,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];
@@ -615,6 +649,73 @@ public class LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE extends HASH_MAP KEY_VALUE_G
} }
} }
@Override
public <E> void forEach(E input, ObjectObjectConsumer<MAP.Entry KEY_VALUE_GENERIC_TYPE, E> action) {
Objects.requireNonNull(action);
if(size() <= 0) return;
int index = firstIndex;
while(index != -1) {
action.accept(new BasicEntryKV_BRACES(keys[index], values[index]), input);
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 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 @Override
@Deprecated @Deprecated
public boolean contains(Object o) { public boolean contains(Object o) {
@@ -751,17 +852,6 @@ public class LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE extends HASH_MAP KEY_VALUE_G
return POLL_LAST_ENTRY_KEY(); return POLL_LAST_ENTRY_KEY();
} }
#if TYPE_OBJECT
@Override
public void forEach(Consumer KEY_SUPER_GENERIC_TYPE action) {
int index = firstIndex;
while(index != -1){
action.accept(keys[index]);
index = (int)links[index];
}
}
#else
@Override @Override
public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) { public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) {
int index = firstIndex; int index = firstIndex;
@@ -771,7 +861,65 @@ public class LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE extends HASH_MAP KEY_VALUE_G
} }
} }
#endif @Override
public <E> void forEach(E input, BI_OBJECT_CONSUMER KKS_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
if(size() <= 0) return;
int index = firstIndex;
while(index != -1){
action.accept(keys[index], input);
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;
}
@Override
public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return EMPTY_KEY_VALUE;
int index = firstIndex;
while(index != -1){
if(filter.TEST_VALUE(keys[index])) return keys[index];
index = (int)links[index];
}
return EMPTY_KEY_VALUE;
}
@Override @Override
public COMPARATOR KEY_GENERIC_TYPE comparator() { return null; } public COMPARATOR KEY_GENERIC_TYPE comparator() { return null; }
@@ -820,25 +968,74 @@ 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];
} }
} }
#endif
@Override
public <E> void forEach(E input, VALUE_BI_OBJECT_CONSUMER VVS_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
if(size() <= 0) return;
int index = firstIndex;
while(index != -1){
action.accept(values[index], input);
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;
}
@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;
}
} }
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> {
@@ -11,24 +11,49 @@ import speiger.src.collections.PACKAGE.collections.ITERATOR;
import speiger.src.collections.PACKAGE.functions.CONSUMER; import speiger.src.collections.PACKAGE.functions.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 !TYPE_OBJECT && !VALUE_OBJECT
import speiger.src.collections.PACKAGE.functions.consumer.BI_OBJECT_CONSUMER;
#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 #if !SAME_TYPE
import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_UNARY_OPERATOR;
#if !VALUE_OBJECT
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
#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
import speiger.src.collections.VALUE_PACKAGE.functions.consumer.VALUE_BI_OBJECT_CONSUMER;
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 +62,7 @@ import speiger.src.collections.utils.HashUtil;
* @Type(T) * @Type(T)
* @ValueType(V) * @ValueType(V)
*/ */
public class HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE public class HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE implements ITrimmable
{ {
/** The Backing keys array */ /** The Backing keys array */
protected transient KEY_TYPE[] keys; protected transient KEY_TYPE[] keys;
@@ -231,7 +256,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;
} }
@@ -247,7 +272,7 @@ 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 == null && VALUE_EQUALS(values[nullIndex], getDefaultReturnValue())) || EQUALS_VALUE_TYPE(values[nullIndex], value)) return true;
for(int i = nullIndex-1;i >= 0;i--) for(int i = nullIndex-1;i >= 0;i--)
@@ -256,12 +281,19 @@ public class HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENE
} }
@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
public VALUE_TYPE REMOVE_VALUEOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) {
int slot = findIndex(key);
if(slot < 0) return defaultValue;
return removeIndex(slot);
}
@Override @Override
@Deprecated @Deprecated
public CLASS_VALUE_TYPE remove(Object key) { public CLASS_VALUE_TYPE remove(Object key) {
@@ -377,6 +409,95 @@ 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) {
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) {
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;
}
return values[index];
}
@Override
public VALUE_TYPE COMPUTE_IF_PRESENT(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) {
int index = findIndex(key);
if(index < 0) 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) {
int index = findIndex(key);
VALUE_TYPE newValue = index < 0 ? 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 ? 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 +510,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 +564,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);
@@ -587,6 +738,88 @@ public class HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENE
} }
} }
@Override
public <E> void forEach(E input, ObjectObjectConsumer<MAP.Entry KEY_VALUE_GENERIC_TYPE, E> action) {
Objects.requireNonNull(action);
if(size() <= 0) return;
if(containsNull) action.accept(new BasicEntryKV_BRACES(keys[nullIndex], values[nullIndex]), input);
for(int i = nullIndex-1;i>=0;i--) {
if(KEY_EQUALS_NOT_NULL(keys[i])) action.accept(new BasicEntryKV_BRACES(keys[i], values[i]), input);
}
}
@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 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 @Override
public int size() { public int size() {
return HASH_MAP.this.size(); return HASH_MAP.this.size();
@@ -668,22 +901,66 @@ 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
public void forEach(Consumer KEY_SUPER_GENERIC_TYPE action) {
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]);
} }
#endif
@Override
public <E> void forEach(E input, BI_OBJECT_CONSUMER KKS_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
if(size() <= 0) return;
if(containsNull) action.accept(keys[nullIndex], input);
for(int i = nullIndex-1;i>=0;i--) {
if(KEY_EQUALS_NOT_NULL(keys[i])) action.accept(keys[i], input);
}
}
@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;
}
@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;
}
} }
private class Values extends VALUE_ABSTRACT_COLLECTION VALUE_GENERIC_TYPE { private class Values extends VALUE_ABSTRACT_COLLECTION VALUE_GENERIC_TYPE {
@@ -720,21 +997,66 @@ 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]);
} }
#endif
@Override
public <E> void forEach(E input, VALUE_BI_OBJECT_CONSUMER VVS_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
if(size() <= 0) return;
if(containsNull) action.accept(values[nullIndex], input);
for(int i = nullIndex-1;i>=0;i--) {
if(KEY_EQUALS_NOT_NULL(keys[i])) action.accept(values[i], input);
}
}
@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;
}
@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;
}
} }
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> {
@@ -12,7 +12,15 @@ import speiger.src.collections.PACKAGE.collections.BI_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
#if !TYPE_OBJECT && !VALUE_OBJECT
import speiger.src.collections.PACKAGE.functions.consumer.BI_OBJECT_CONSUMER;
#endif
#if !TYPE_OBJECT && !VALUE_BOOLEAN
import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
#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;
import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR; import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR;
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;
@@ -24,10 +32,25 @@ import speiger.src.collections.PACKAGE.utils.maps.MAPS;
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 && !VALUE_OBJECT #if !SAME_TYPE
import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_UNARY_OPERATOR;
#if !VALUE_OBJECT
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
#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
import speiger.src.collections.VALUE_PACKAGE.functions.consumer.VALUE_BI_OBJECT_CONSUMER;
import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_PREDICATE;
#endif
#if !VALUE_OBJECT #if !VALUE_OBJECT
import speiger.src.collections.objects.collections.ObjectIterator; import speiger.src.collections.objects.collections.ObjectIterator;
#endif #endif
@@ -347,7 +370,7 @@ public class ARRAY_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GEN
} }
@Override @Override
public VALUE_TYPE REMOVE_KEY(KEY_TYPE key) { public VALUE_TYPE REMOVE_VALUE(KEY_TYPE key) {
int index = findIndex(key); int index = findIndex(key);
if(index < 0) return getDefaultReturnValue(); if(index < 0) return getDefaultReturnValue();
VALUE_TYPE value = values[index]; VALUE_TYPE value = values[index];
@@ -355,6 +378,15 @@ public class ARRAY_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GEN
return value; return value;
} }
@Override
public VALUE_TYPE REMOVE_VALUEOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) {
int index = findIndex(key);
if(index < 0) return defaultValue;
VALUE_TYPE value = values[index];
removeIndex(index);
return value;
}
#if !TYPE_OBJECT || !VALUE_OBJECT #if !TYPE_OBJECT || !VALUE_OBJECT
@Override @Override
public boolean remove(KEY_TYPE key, VALUE_TYPE value) { public boolean remove(KEY_TYPE key, VALUE_TYPE value) {
@@ -407,6 +439,95 @@ public class ARRAY_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GEN
return entrySet; return entrySet;
} }
@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) {
int index = findIndex(key);
if(index == -1) {
VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, getDefaultReturnValue());
if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue;
insertIndex(size++, 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) {
int index = findIndex(key);
if(index == -1) {
VALUE_TYPE newValue = mappingFunction.GET_VALUE(key);
if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue;
insertIndex(size++, key, newValue);
return newValue;
}
return values[index];
}
@Override
public VALUE_TYPE COMPUTE_IF_PRESENT(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) {
int index = findIndex(key);
if(index == -1) 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) {
int index = findIndex(key);
VALUE_TYPE newValue = index == -1 ? value : mappingFunction.APPLY_VALUE(values[index], value);
if(VALUE_EQUALS(newValue, getDefaultReturnValue())) {
if(index >= 0)
removeIndex(index);
}
else if(index == -1) insertIndex(size++, 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 == -1 ? entry.ENTRY_VALUE() : mappingFunction.APPLY_VALUE(values[index], entry.ENTRY_VALUE());
if(VALUE_EQUALS(newValue, getDefaultReturnValue())) {
if(index >= 0)
removeIndex(index);
}
else if(index == -1) insertIndex(size++, key, newValue);
else values[index] = newValue;
}
}
@Override @Override
public int size() { public int size() {
return size; return size;
@@ -768,7 +889,7 @@ public class ARRAY_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GEN
} }
@Override @Override
public VALUE_TYPE REMOVE_KEY(KEY_TYPE key) { public VALUE_TYPE REMOVE_VALUE(KEY_TYPE key) {
int index = findIndex(key); int index = findIndex(key);
if(index < 0) return getDefaultReturnValue(); if(index < 0) return getDefaultReturnValue();
VALUE_TYPE value = values[index]; VALUE_TYPE value = values[index];
@@ -777,6 +898,16 @@ public class ARRAY_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GEN
return value; return value;
} }
@Override
public VALUE_TYPE REMOVE_VALUEOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) {
int index = findIndex(key);
if(index < 0) return defaultValue;
VALUE_TYPE value = values[index];
removeIndex(index);
length--;
return value;
}
#if !TYPE_OBJECT || !VALUE_OBJECT #if !TYPE_OBJECT || !VALUE_OBJECT
@Override @Override
public boolean remove(KEY_TYPE key, VALUE_TYPE value) { public boolean remove(KEY_TYPE key, VALUE_TYPE value) {
@@ -990,12 +1121,15 @@ public class ARRAY_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GEN
@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) {
Objects.requireNonNull(action);
for(int i = 0;i<length;i++) for(int i = 0;i<length;i++)
action.accept(new BasicEntryKV_BRACES(keys[offset+i], values[offset+i])); action.accept(new BasicEntryKV_BRACES(keys[offset+i], values[offset+i]));
} }
@Override @Override
public void fastForEach(Consumer<? super MAP.Entry KEY_VALUE_GENERIC_TYPE> action) { public void fastForEach(Consumer<? super MAP.Entry KEY_VALUE_GENERIC_TYPE> action) {
Objects.requireNonNull(action);
if(size() <= 0) return;
BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES();
for(int i = 0;i<length;i++) { for(int i = 0;i<length;i++) {
entry.set(keys[offset+i], values[offset+i]); entry.set(keys[offset+i], values[offset+i]);
@@ -1003,6 +1137,61 @@ public class ARRAY_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GEN
} }
} }
@Override
public <E> void forEach(E input, ObjectObjectConsumer<MAP.Entry KEY_VALUE_GENERIC_TYPE, E> action) {
Objects.requireNonNull(action);
for(int i = 0;i<length;i++)
action.accept(new BasicEntryKV_BRACES(keys[offset+i], values[offset+i]), input);
}
@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();
for(int i = 0;i<length;i++) {
entry.set(keys[offset+i], values[offset+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();
for(int i = 0;i<length;i++) {
entry.set(keys[offset+i], values[offset+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();
for(int i = 0;i<length;i++) {
entry.set(keys[offset+i], values[offset+i]);
if(!filter.getBoolean(entry)) return false;
}
return true;
}
@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();
for(int i = 0;i<length;i++) {
entry.set(keys[offset+i], values[offset+i]);
if(filter.getBoolean(entry)) return entry;
}
return null;
}
@Override @Override
@Deprecated @Deprecated
public boolean contains(Object o) { public boolean contains(Object o) {
@@ -1100,19 +1289,60 @@ public class ARRAY_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GEN
@Override @Override
public KEY_TYPE POLL_LAST_KEY() { return POLL_LAST_ENTRY_KEY(); } public KEY_TYPE POLL_LAST_KEY() { return POLL_LAST_ENTRY_KEY(); }
#if TYPE_OBJECT
@Override @Override
public void forEach(Consumer<? super CLASS_TYPE> action) { public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) {
Objects.requireNonNull(action);
for(int i = 0;i<length;action.accept(keys[offset+i])); for(int i = 0;i<length;action.accept(keys[offset+i]));
} }
#else
@Override @Override
public void forEach(CONSUMER KEY_GENERIC_TYPE action) { public <E> void forEach(E input, BI_OBJECT_CONSUMER KKS_GENERIC_TYPE<E> action) {
for(int i = 0;i<length;action.accept(keys[offset+i])); Objects.requireNonNull(action);
if(size() <= 0) return;
for(int i = 0;i<length;action.accept(keys[offset+i], input));
}
@Override
public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return false;
for(int i = 0;i<length;i++) {
if(filter.TEST_VALUE(keys[i+offset])) return true;
}
return false;
}
@Override
public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return true;
for(int i = 0;i<length;i++) {
if(filter.TEST_VALUE(keys[i+offset])) return false;
}
return true;
}
@Override
public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return true;
for(int i = 0;i<length;i++) {
if(!filter.TEST_VALUE(keys[i+offset])) return false;
}
return true;
}
@Override
public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return EMPTY_KEY_VALUE;
for(int i = 0;i<length;i++) {
if(filter.TEST_VALUE(keys[i+offset])) return keys[i+offset];
}
return EMPTY_KEY_VALUE;
} }
#endif
@Override @Override
public COMPARATOR KEY_GENERIC_TYPE comparator() { return null; } public COMPARATOR KEY_GENERIC_TYPE comparator() { return null; }
@Override @Override
@@ -1157,17 +1387,54 @@ public class ARRAY_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GEN
SubMap.this.clear(); SubMap.this.clear();
} }
#if VALUE_OBJECT
@Override @Override
public void forEach(Consumer<? super CLASS_VALUE_TYPE> action) { public void forEach(VALUE_CONSUMER VALUE_SUPER_GENERIC_TYPE action) {
Objects.requireNonNull(action);
for(int i = 0;i<length;action.accept(values[offset+i])); for(int i = 0;i<length;action.accept(values[offset+i]));
} }
#else
@Override @Override
public void forEach(VALUE_CONSUMER VALUE_GENERIC_TYPE action) { public <E> void forEach(E input, VALUE_BI_OBJECT_CONSUMER VVS_GENERIC_TYPE<E> action) {
for(int i = 0;i<length;action.accept(values[offset+i])); Objects.requireNonNull(action);
for(int i = 0;i<length;action.accept(values[offset+i], input));
}
@Override
public boolean matchesAny(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(int i = 0;i<length;i++) {
if(filter.VALUE_TEST_VALUE(values[offset+i])) return true;
}
return false;
}
@Override
public boolean matchesNone(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(int i = 0;i<length;i++) {
if(filter.VALUE_TEST_VALUE(values[offset+i])) return false;
}
return true;
}
@Override
public boolean matchesAll(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(int i = 0;i<length;i++) {
if(!filter.VALUE_TEST_VALUE(values[offset+i])) return false;
}
return true;
}
@Override
public VALUE_TYPE findFirst(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(int i = 0;i<length;i++) {
if(filter.VALUE_TEST_VALUE(values[offset+i])) return values[offset+i];
}
return EMPTY_VALUE;
} }
#endif
} }
private class SubFastEntryIterator extends SubMapIterator implements ObjectListIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> { private class SubFastEntryIterator extends SubMapIterator implements ObjectListIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> {
@@ -1385,12 +1652,15 @@ public class ARRAY_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GEN
@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) {
Objects.requireNonNull(action);
for(int i = 0;i<size;i++) for(int i = 0;i<size;i++)
action.accept(new BasicEntryKV_BRACES(keys[i], values[i])); action.accept(new BasicEntryKV_BRACES(keys[i], values[i]));
} }
@Override @Override
public void fastForEach(Consumer<? super MAP.Entry KEY_VALUE_GENERIC_TYPE> action) { public void fastForEach(Consumer<? super MAP.Entry KEY_VALUE_GENERIC_TYPE> action) {
Objects.requireNonNull(action);
if(size() <= 0) return;
BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES(); BasicEntry KEY_VALUE_GENERIC_TYPE entry = new BasicEntryKV_BRACES();
for(int i = 0;i<size;i++) { for(int i = 0;i<size;i++) {
entry.set(keys[i], values[i]); entry.set(keys[i], values[i]);
@@ -1398,6 +1668,62 @@ public class ARRAY_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GEN
} }
} }
@Override
public <E> void forEach(E input, ObjectObjectConsumer<MAP.Entry KEY_VALUE_GENERIC_TYPE, E> action) {
Objects.requireNonNull(action);
for(int i = 0;i<size;i++) {
action.accept(new BasicEntryKV_BRACES(keys[i], values[i]), input);
}
}
@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();
for(int i = 0;i<size;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();
for(int i = 0;i<size;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();
for(int i = 0;i<size;i++) {
entry.set(keys[i], values[i]);
if(!filter.getBoolean(entry)) return false;
}
return true;
}
@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();
for(int i = 0;i<size;i++) {
entry.set(keys[i], values[i]);
if(filter.getBoolean(entry)) return entry;
}
return null;
}
@Override @Override
@Deprecated @Deprecated
public boolean contains(Object o) { public boolean contains(Object o) {
@@ -1495,19 +1821,56 @@ public class ARRAY_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GEN
@Override @Override
public KEY_TYPE POLL_LAST_KEY() { return POLL_LAST_ENTRY_KEY(); } public KEY_TYPE POLL_LAST_KEY() { return POLL_LAST_ENTRY_KEY(); }
#if TYPE_OBJECT
@Override @Override
public void forEach(Consumer<? super CLASS_TYPE> action) { public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) {
Objects.requireNonNull(action);
for(int i = 0;i<size;action.accept(keys[i++])); for(int i = 0;i<size;action.accept(keys[i++]));
} }
#else
@Override @Override
public void forEach(CONSUMER KEY_GENERIC_TYPE action) { public <E> void forEach(E input, BI_OBJECT_CONSUMER KKS_GENERIC_TYPE<E> action) {
for(int i = 0;i<size;action.accept(keys[i++])); Objects.requireNonNull(action);
for(int i = 0;i<size;action.accept(keys[i++], input));
}
@Override
public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
if(size() <= 0) return false;
for(int i = 0;i<size;i++) {
if(filter.TEST_VALUE(keys[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(keys[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(keys[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(keys[i])) return keys[i];
}
return EMPTY_KEY_VALUE;
} }
#endif
@Override @Override
public COMPARATOR KEY_GENERIC_TYPE comparator() { return null; } public COMPARATOR KEY_GENERIC_TYPE comparator() { return null; }
@Override @Override
@@ -1552,17 +1915,47 @@ public class ARRAY_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GEN
ARRAY_MAP.this.clear(); ARRAY_MAP.this.clear();
} }
#if VALUE_OBJECT
@Override @Override
public void forEach(Consumer<? super CLASS_VALUE_TYPE> action) { public void forEach(VALUE_CONSUMER VALUE_SUPER_GENERIC_TYPE action) {
Objects.requireNonNull(action);
for(int i = 0;i<size;action.accept(values[i++])); for(int i = 0;i<size;action.accept(values[i++]));
} }
#else
@Override @Override
public void forEach(VALUE_CONSUMER VALUE_GENERIC_TYPE action) { public boolean matchesAny(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) {
for(int i = 0;i<size;action.accept(values[i++])); Objects.requireNonNull(filter);
for(int i = 0;i<size;i++) {
if(filter.VALUE_TEST_VALUE(values[i])) return true;
}
return false;
}
@Override
public boolean matchesNone(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(int i = 0;i<size;i++) {
if(filter.VALUE_TEST_VALUE(values[i])) return false;
}
return true;
}
@Override
public boolean matchesAll(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(int i = 0;i<size;i++) {
if(!filter.VALUE_TEST_VALUE(values[i])) return false;
}
return true;
}
@Override
public VALUE_TYPE findFirst(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(int i = 0;i<size;i++) {
if(filter.VALUE_TEST_VALUE(values[i])) return values[i];
}
return EMPTY_VALUE;
} }
#endif
} }
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,5 +1,6 @@
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 #if VALUE_OBJECT
@@ -16,7 +17,6 @@ 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.
@@ -124,6 +124,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) {
@@ -184,6 +194,14 @@ public class ENUM_MAP KEY_ENUM_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE
return valuesC; return valuesC;
} }
@Override
public void clear() {
if(size == 0) return;
size = 0;
Arrays.fill(present, 0L);
Arrays.fill(values, EMPTY_VALUE);
}
protected void onNodeAdded(int index) { protected void onNodeAdded(int index) {
} }
@@ -201,9 +219,9 @@ public class ENUM_MAP KEY_ENUM_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE
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) { private static <K extends Enum<K>> K[] getKeyUniverse(Class<K> keyType) {
// return keyType.getEnumConstants(); return keyType.getEnumConstants();
return SharedSecrets.getJavaLangAccess().getEnumConstantsShared(keyType);
} }
class EntrySet extends AbstractObjectSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> { class EntrySet extends AbstractObjectSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> {
@@ -0,0 +1,845 @@
package speiger.src.collections.PACKAGE.maps.impl.misc;
import java.util.Comparator;
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.COMPARATOR;
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.SORTED_MAP;
import speiger.src.collections.PACKAGE.sets.ABSTRACT_SET;
import speiger.src.collections.PACKAGE.sets.SORTED_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.ObjectSortedSet;
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 SORTED_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];
}
@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 COMPARATOR KEY_GENERIC_TYPE comparator() {
return null;
}
@Override
public SORTED_MAP KEY_VALUE_GENERIC_TYPE subMap(T fromKey, T toKey) { throw new UnsupportedOperationException(); }
@Override
public SORTED_MAP KEY_VALUE_GENERIC_TYPE headMap(T toKey) { throw new UnsupportedOperationException(); }
@Override
public SORTED_MAP KEY_VALUE_GENERIC_TYPE tailMap(T fromKey) { throw new UnsupportedOperationException(); }
@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 SORTED_MAP.FastSortedSet 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);
}
@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) return LINKED_ENUM_MAP.this.containsKey(((MAP.Entry KEY_VALUE_GENERIC_TYPE)o).ENTRY_KEY());
return LINKED_ENUM_MAP.this.containsKey(((Map.Entry<?, ?>)o).getKey());
}
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();
}
@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 {
#if TYPE_OBJECT
@Override
@Deprecated
public boolean contains(Object e) {
return containsKey(e);
}
@Override
public boolean remove(Object o) {
int oldSize = size;
remove(o);
return size != oldSize;
}
#else
@Override
public boolean contains(T e) {
return containsKey(e);
}
@Override
public boolean remove(T o) {
int oldSize = size;
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);
}
@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
@Override
public COMPARATOR KEY_GENERIC_TYPE comparator() { return null; }
@Override
public SORTED_SET KEY_GENERIC_TYPE subSet(T fromElement, T toElement) { throw new UnsupportedOperationException(); }
@Override
public SORTED_SET KEY_GENERIC_TYPE headSet(T toElement) { throw new UnsupportedOperationException(); }
@Override
public SORTED_SET KEY_GENERIC_TYPE tailSet(T fromElement) { throw new UnsupportedOperationException(); }
}
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;
}
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]);
}
}
}
@@ -3,14 +3,25 @@ package speiger.src.collections.PACKAGE.maps.impl.tree;
import java.util.Map; import java.util.Map;
#if TYPE_OBJECT #if TYPE_OBJECT
import java.util.Comparator; import java.util.Comparator;
import java.util.Objects;
#endif #endif
import java.util.function.Consumer;
import java.util.Objects;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import speiger.src.collections.PACKAGE.collections.BI_ITERATOR; import speiger.src.collections.PACKAGE.collections.BI_ITERATOR;
#if !TYPE_OBJECT #if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.functions.COMPARATOR; import speiger.src.collections.PACKAGE.functions.COMPARATOR;
import speiger.src.collections.PACKAGE.functions.CONSUMER;
#endif #endif
#if !TYPE_OBJECT && !VALUE_OBJECT
import speiger.src.collections.PACKAGE.functions.consumer.BI_OBJECT_CONSUMER;
#endif
#if !TYPE_OBJECT && !VALUE_BOOLEAN
import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
#endif
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;
import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR; import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR;
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;
@@ -20,13 +31,30 @@ import speiger.src.collections.PACKAGE.sets.NAVIGABLE_SET;
import speiger.src.collections.PACKAGE.sets.SET; import speiger.src.collections.PACKAGE.sets.SET;
import speiger.src.collections.PACKAGE.sets.SORTED_SET; import speiger.src.collections.PACKAGE.sets.SORTED_SET;
import speiger.src.collections.PACKAGE.utils.ITERATORS; import speiger.src.collections.PACKAGE.utils.ITERATORS;
import speiger.src.collections.PACKAGE.utils.maps.MAPS;
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 #if !SAME_TYPE
import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_UNARY_OPERATOR;
import speiger.src.collections.VALUE_PACKAGE.lists.VALUE_LIST_ITERATOR; import speiger.src.collections.VALUE_PACKAGE.lists.VALUE_LIST_ITERATOR;
import speiger.src.collections.VALUE_PACKAGE.utils.VALUE_ITERATORS; import speiger.src.collections.VALUE_PACKAGE.utils.VALUE_ITERATORS;
#endif #endif
#if !VALUE_OBJECT && !SAME_TYPE
import speiger.src.collections.VALUE_PACKAGE.functions.VALUE_CONSUMER;
#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
import speiger.src.collections.VALUE_PACKAGE.functions.consumer.VALUE_BI_OBJECT_CONSUMER;
import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_PREDICATE;
#endif
#if !TYPE_OBJECT && !VALUE_OBJECT #if !TYPE_OBJECT && !VALUE_OBJECT
import speiger.src.collections.objects.lists.ObjectListIterator; import speiger.src.collections.objects.lists.ObjectListIterator;
import speiger.src.collections.objects.utils.ObjectIterators; import speiger.src.collections.objects.utils.ObjectIterators;
@@ -417,7 +445,7 @@ public class AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_
} }
@Override @Override
public VALUE_TYPE REMOVE_KEY(KEY_TYPE key) { public VALUE_TYPE REMOVE_VALUE(KEY_TYPE key) {
Entry KEY_VALUE_GENERIC_TYPE entry = findNode(key); Entry KEY_VALUE_GENERIC_TYPE entry = findNode(key);
if(entry == null) return getDefaultReturnValue(); if(entry == null) return getDefaultReturnValue();
VALUE_TYPE value = entry.value; VALUE_TYPE value = entry.value;
@@ -425,6 +453,15 @@ public class AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_
return value; return value;
} }
@Override
public VALUE_TYPE REMOVE_VALUEOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) {
Entry KEY_VALUE_GENERIC_TYPE entry = findNode(key);
if(entry == null) return defaultValue;
VALUE_TYPE value = entry.value;
removeNode(entry);
return value;
}
#if TYPE_OBJECT && VALUE_OBJECT #if TYPE_OBJECT && VALUE_OBJECT
@Override @Override
public boolean remove(Object key, Object value) { public boolean remove(Object key, Object value) {
@@ -444,6 +481,101 @@ public class AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_
} }
#endif #endif
@Override
public boolean replace(KEY_TYPE key, VALUE_TYPE oldValue, VALUE_TYPE newValue) {
Entry KEY_VALUE_GENERIC_TYPE entry = findNode(key);
if(entry == null || entry.value != oldValue) return false;
entry.value = newValue;
return true;
}
@Override
public VALUE_TYPE replace(KEY_TYPE key, VALUE_TYPE value) {
Entry KEY_VALUE_GENERIC_TYPE entry = findNode(key);
if(entry == null) return getDefaultReturnValue();
VALUE_TYPE oldValue = entry.value;
entry.value = value;
return oldValue;
}
@Override
public VALUE_TYPE COMPUTE(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) {
Entry KEY_VALUE_GENERIC_TYPE entry = findNode(key);
if(entry == null) {
VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, getDefaultReturnValue());
if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue;
put(key, newValue);
return newValue;
}
VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, entry.value);
if(VALUE_EQUALS(newValue, getDefaultReturnValue())) {
removeNode(entry);
return newValue;
}
entry.value = newValue;
return newValue;
}
@Override
public VALUE_TYPE COMPUTE_IF_ABSENT(KEY_TYPE key, FUNCTION KEY_VALUE_GENERIC_TYPE mappingFunction) {
Entry KEY_VALUE_GENERIC_TYPE entry = findNode(key);
if(entry == null) {
VALUE_TYPE newValue = mappingFunction.GET_VALUE(key);
if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue;
put(key, newValue);
return newValue;
}
return entry.value;
}
@Override
public VALUE_TYPE COMPUTE_IF_PRESENT(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) {
Entry KEY_VALUE_GENERIC_TYPE entry = findNode(key);
if(entry == null) return getDefaultReturnValue();
VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, entry.value);
if(VALUE_EQUALS(newValue, getDefaultReturnValue())) {
removeNode(entry);
return newValue;
}
entry.value = newValue;
return newValue;
}
@Override
public VALUE_TYPE MERGE(KEY_TYPE key, VALUE_TYPE value, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) {
Entry KEY_VALUE_GENERIC_TYPE entry = findNode(key);
VALUE_TYPE newValue = entry == null ? value : mappingFunction.APPLY_VALUE(entry.value, value);
if(VALUE_EQUALS(newValue, getDefaultReturnValue())) {
if(entry != null)
removeNode(entry);
}
else if(entry == null) put(key, newValue);
else entry.value = 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();
Entry KEY_VALUE_GENERIC_TYPE subEntry = findNode(key);
VALUE_TYPE newValue = subEntry == null ? entry.ENTRY_VALUE() : mappingFunction.APPLY_VALUE(subEntry.value, entry.ENTRY_VALUE());
if(VALUE_EQUALS(newValue, getDefaultReturnValue())) {
if(subEntry != null)
removeNode(subEntry);
}
else if(subEntry == null) put(key, newValue);
else subEntry.value = newValue;
}
}
@Override
public void forEach(BI_CONSUMER KEY_VALUE_GENERIC_TYPE action) {
for(Entry KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next())
action.accept(entry.key, entry.value);
}
@Override @Override
public int size() { return size; } public int size() { return size; }
@@ -675,11 +807,11 @@ public class AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_
entry.value = successor.value; entry.value = successor.value;
entry = successor; entry = successor;
} }
if(entry.previous() == null) first = entry.next();
if(entry.next() == null) last = entry.previous();
Entry KEY_VALUE_GENERIC_TYPE replacement = entry.left != null ? entry.left : entry.right; Entry KEY_VALUE_GENERIC_TYPE replacement = entry.left != null ? entry.left : entry.right;
if(replacement != null) { if(replacement != null) {
if(entry.replace(replacement)) tree = replacement; if(entry.replace(replacement)) tree = replacement;
if(entry == first) first = replacement;
if(entry == last) last = entry.right != null ? entry.right : replacement;
entry.left = entry.right = entry.parent = null; entry.left = entry.right = entry.parent = null;
fixAfterDeletion(replacement); fixAfterDeletion(replacement);
} }
@@ -687,17 +819,13 @@ public class AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_
else { else {
fixAfterDeletion(entry); fixAfterDeletion(entry);
entry.replace(null); entry.replace(null);
if(entry.parent != null) {
Entry KEY_VALUE_GENERIC_TYPE parent = entry.parent;
if(entry == first) first = parent.left != null ? parent.left : parent;
if(entry == last) last = entry.right != null ? parent.right : parent;
}
entry.parent = null; entry.parent = null;
} }
} }
protected int compare(KEY_TYPE k, KEY_TYPE v) { return comparator != null ? comparator.compare(k, v) : COMPAREABLE_TO_KEY(k, v);} protected int compare(KEY_TYPE k, KEY_TYPE v) { return comparator != null ? comparator.compare(k, v) : COMPAREABLE_TO_KEY(k, v);}
/** From CLR */
protected void rotateLeft(Entry KEY_VALUE_GENERIC_TYPE entry) { protected void rotateLeft(Entry KEY_VALUE_GENERIC_TYPE entry) {
if(entry != null) { if(entry != null) {
Entry KEY_VALUE_GENERIC_TYPE right = entry.right; Entry KEY_VALUE_GENERIC_TYPE right = entry.right;
@@ -709,9 +837,12 @@ public class AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_
else entry.parent.right = right; else entry.parent.right = right;
right.left = entry; right.left = entry;
entry.parent = right; entry.parent = right;
entry.updateHeight();
right.updateHeight();
} }
} }
/** From CLR */
protected void rotateRight(Entry KEY_VALUE_GENERIC_TYPE entry) { protected void rotateRight(Entry KEY_VALUE_GENERIC_TYPE entry) {
if(entry != null) { if(entry != null) {
Entry KEY_VALUE_GENERIC_TYPE left = entry.left; Entry KEY_VALUE_GENERIC_TYPE left = entry.left;
@@ -723,9 +854,12 @@ public class AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_
else entry.parent.left = left; else entry.parent.left = left;
left.right = entry; left.right = entry;
entry.parent = left; entry.parent = left;
entry.updateHeight();
left.updateHeight();
} }
} }
/** From CLR */
protected void fixAfterInsertion(Entry KEY_VALUE_GENERIC_TYPE entry) { protected void fixAfterInsertion(Entry KEY_VALUE_GENERIC_TYPE entry) {
while(entry != null) { while(entry != null) {
entry.updateHeight(); entry.updateHeight();
@@ -750,6 +884,7 @@ public class AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_
} }
} }
/** From CLR */
protected void fixAfterDeletion(Entry KEY_VALUE_GENERIC_TYPE entry) { protected void fixAfterDeletion(Entry KEY_VALUE_GENERIC_TYPE entry) {
if(entry != null) { if(entry != null) {
entry.updateHeight(); entry.updateHeight();
@@ -799,6 +934,14 @@ public class AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_
return descendingMap; return descendingMap;
} }
AVL_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE next(AVL_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry) {
return entry.next();
}
AVL_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE previous(AVL_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry) {
return entry.previous();
}
@Override @Override
public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE subMap(KEY_TYPE fromKey, boolean fromInclusive, KEY_TYPE toKey, boolean toInclusive) { public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE subMap(KEY_TYPE fromKey, boolean fromInclusive, KEY_TYPE toKey, boolean toInclusive) {
if (!inRange(fromKey, fromInclusive)) throw new IllegalArgumentException("fromKey out of range"); if (!inRange(fromKey, fromInclusive)) throw new IllegalArgumentException("fromKey out of range");
@@ -879,6 +1022,18 @@ public class AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_
@Override @Override
public MAP.Entry KEY_VALUE_GENERIC_TYPE higherEntry(KEY_TYPE e) { return super.lowerEntry(e); } public MAP.Entry KEY_VALUE_GENERIC_TYPE higherEntry(KEY_TYPE e) { return super.lowerEntry(e); }
protected AVL_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE findLowest() {
if(fromStart) return m.first;
AVL_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = loInclusive ? m.findFloorNode(high) : m.findLowerNode(high);
return entry == null || tooHigh(entry.key) ? null : entry;
}
protected AVL_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE findHighest() {
if(toEnd) return m.last;
AVL_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = hiInclusive ? m.findCeilingNode(low) : m.findHigherNode(low);
return entry == null || tooLow(entry.key) ? null : entry;
}
@Override @Override
LIST_ITERATOR KEY_GENERIC_TYPE keyIterator(boolean descending) { LIST_ITERATOR KEY_GENERIC_TYPE keyIterator(boolean descending) {
LIST_ITERATOR KEY_GENERIC_TYPE iter = new SubMapKeyIterator(!descending); LIST_ITERATOR KEY_GENERIC_TYPE iter = new SubMapKeyIterator(!descending);
@@ -891,6 +1046,14 @@ public class AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_
return entry == null || !inClosedRange(key) ? null : ITERATORS.invert(new SubMapKeyIterator(entry, fromStart ? null : findLowest(), toEnd ? null : findHighest())); return entry == null || !inClosedRange(key) ? null : ITERATORS.invert(new SubMapKeyIterator(entry, fromStart ? null : findLowest(), toEnd ? null : findHighest()));
} }
AVL_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE next(AVL_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry) {
return entry.previous();
}
AVL_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE previous(AVL_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry) {
return entry.next();
}
@Override @Override
public COMPARATOR KEY_GENERIC_TYPE comparator() { return m.comparator() == null ? null : m.comparator().reversed(); } public COMPARATOR KEY_GENERIC_TYPE comparator() { return m.comparator() == null ? null : m.comparator().reversed(); }
@@ -953,6 +1116,9 @@ public class AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_
abstract LIST_ITERATOR KEY_GENERIC_TYPE keyIterator(KEY_TYPE key); abstract LIST_ITERATOR KEY_GENERIC_TYPE keyIterator(KEY_TYPE key);
abstract VALUE_LIST_ITERATOR VALUE_GENERIC_TYPE valueIterator(); abstract VALUE_LIST_ITERATOR VALUE_GENERIC_TYPE valueIterator();
abstract ObjectListIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> entryIterator(); abstract ObjectListIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> entryIterator();
abstract AVL_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE next(AVL_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry);
abstract AVL_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE previous(AVL_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry);
@Override @Override
public abstract NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE descendingMap(); public abstract NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE descendingMap();
@@ -1113,8 +1279,13 @@ public class AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_
#endif #endif
@Override @Override
public VALUE_TYPE REMOVE_KEY(KEY_TYPE key) { public VALUE_TYPE REMOVE_VALUE(KEY_TYPE key) {
return inRange(key) ? m.REMOVE_KEY(key) : getDefaultReturnValue(); return inRange(key) ? m.REMOVE_VALUE(key) : getDefaultReturnValue();
}
@Override
public VALUE_TYPE REMOVE_VALUEOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) {
return inRange(key) ? m.REMOVE_VALUE(key) : defaultValue;
} }
#if TYPE_OBJECT && VALUE_OBJECT #if TYPE_OBJECT && VALUE_OBJECT
@@ -1156,6 +1327,12 @@ public class AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_
return values; return values;
} }
@Override
public void forEach(BI_CONSUMER KEY_VALUE_GENERIC_TYPE action) {
for(AVL_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = findLowest(), last = findHighest();entry != null && (last == null || last != previous(entry));entry = next(entry))
action.accept(entry.key, entry.value);
}
@Override @Override
public int size() { public int size() {
return (fromStart && toEnd) ? m.size() : entrySet().size(); return (fromStart && toEnd) ? m.size() : entrySet().size();
@@ -1301,6 +1478,68 @@ public class AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_
public int size() { return NavigableSubMap.this.size(); } public int size() { return NavigableSubMap.this.size(); }
@Override @Override
public void clear() { NavigableSubMap.this.clear(); } public void clear() { NavigableSubMap.this.clear(); }
@Override
public void forEach(Consumer<? super MAP.Entry KEY_VALUE_GENERIC_TYPE> action) {
Objects.requireNonNull(action);
for(AVL_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = findLowest(), last = findHighest();entry != null && (last == null || last != previous(entry));entry = next(entry))
action.accept(new BasicEntryKV_BRACES(entry.key, entry.value));
}
@Override
public <E> void forEach(E input, ObjectObjectConsumer<MAP.Entry KEY_VALUE_GENERIC_TYPE, E> action) {
Objects.requireNonNull(action);
for(AVL_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = findLowest(), last = findHighest();entry != null && (last == null || last != previous(entry));entry = next(entry))
action.accept(new BasicEntryKV_BRACES(entry.key, entry.value), input);
}
@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 subEntry = new BasicEntryKV_BRACES();
for(AVL_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = findLowest(), last = findHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) {
subEntry.set(entry.key, entry.value);
if(filter.getBoolean(subEntry)) 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 subEntry = new BasicEntryKV_BRACES();
for(AVL_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = findLowest(), last = findHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) {
subEntry.set(entry.key, entry.value);
if(filter.getBoolean(subEntry)) 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 subEntry = new BasicEntryKV_BRACES();
for(AVL_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = findLowest(), last = findHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) {
subEntry.set(entry.key, entry.value);
if(!filter.getBoolean(subEntry)) return false;
}
return true;
}
@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 subEntry = new BasicEntryKV_BRACES();
for(AVL_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = findLowest(), last = findHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) {
subEntry.set(entry.key, entry.value);
if(filter.getBoolean(subEntry)) return subEntry;
}
return null;
}
} }
final class SubMapValues extends VALUE_ABSTRACT_COLLECTION VALUE_GENERIC_TYPE { final class SubMapValues extends VALUE_ABSTRACT_COLLECTION VALUE_GENERIC_TYPE {
@@ -1332,6 +1571,52 @@ public class AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_
public void clear() { public void clear() {
NavigableSubMap.this.clear(); NavigableSubMap.this.clear();
} }
@Override
public void forEach(VALUE_CONSUMER VALUE_SUPER_GENERIC_TYPE action) {
Objects.requireNonNull(action);
for(AVL_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = findLowest(), last = findHighest();entry != null && (last == null || last != previous(entry));entry = next(entry))
action.accept(entry.value);
}
@Override
public <E> void forEach(E input, VALUE_BI_OBJECT_CONSUMER VVS_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
for(AVL_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = findLowest(), last = findHighest();entry != null && (last == null || last != previous(entry));entry = next(entry))
action.accept(entry.value, input);
}
@Override
public boolean matchesAny(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(AVL_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = findLowest(), last = findHighest();entry != null && (last == null || last != previous(entry));entry = next(entry))
if(filter.VALUE_TEST_VALUE(entry.value)) return true;
return false;
}
@Override
public boolean matchesNone(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(AVL_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = findLowest(), last = findHighest();entry != null && (last == null || last != previous(entry));entry = next(entry))
if(filter.VALUE_TEST_VALUE(entry.value)) return false;
return true;
}
@Override
public boolean matchesAll(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(AVL_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = findLowest(), last = findHighest();entry != null && (last == null || last != previous(entry));entry = next(entry))
if(!filter.VALUE_TEST_VALUE(entry.value)) return false;
return true;
}
@Override
public VALUE_TYPE findFirst(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(AVL_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = findLowest(), last = findHighest();entry != null && (last == null || last != previous(entry));entry = next(entry))
if(filter.VALUE_TEST_VALUE(entry.value)) return entry.value;
return EMPTY_VALUE;
}
} }
final class SubMapEntrySetIterator extends SubMapEntryIterator implements ObjectListIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> { final class SubMapEntrySetIterator extends SubMapEntryIterator implements ObjectListIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> {
@@ -1505,6 +1790,68 @@ public class AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_
public void clear() { public void clear() {
AVL_TREE_MAP.this.clear(); AVL_TREE_MAP.this.clear();
} }
@Override
public void forEach(Consumer<? super MAP.Entry KEY_VALUE_GENERIC_TYPE> action) {
Objects.requireNonNull(action);
for(AVL_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next())
action.accept(new BasicEntryKV_BRACES(entry.key, entry.value));
}
@Override
public <E> void forEach(E input, ObjectObjectConsumer<MAP.Entry KEY_VALUE_GENERIC_TYPE, E> action) {
Objects.requireNonNull(action);
for(AVL_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next())
action.accept(new BasicEntryKV_BRACES(entry.key, entry.value), input);
}
@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 subEntry = new BasicEntryKV_BRACES();
for(AVL_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) {
subEntry.set(entry.key, entry.value);
if(filter.getBoolean(subEntry)) 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 subEntry = new BasicEntryKV_BRACES();
for(AVL_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) {
subEntry.set(entry.key, entry.value);
if(filter.getBoolean(subEntry)) 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 subEntry = new BasicEntryKV_BRACES();
for(AVL_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) {
subEntry.set(entry.key, entry.value);
if(!filter.getBoolean(subEntry)) return false;
}
return true;
}
@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 subEntry = new BasicEntryKV_BRACES();
for(AVL_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) {
subEntry.set(entry.key, entry.value);
if(filter.getBoolean(subEntry)) return subEntry;
}
return null;
}
} }
static final class KeySet KEY_VALUE_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE implements NAVIGABLE_SET KEY_GENERIC_TYPE { static final class KeySet KEY_VALUE_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE implements NAVIGABLE_SET KEY_GENERIC_TYPE {
@@ -1616,6 +1963,72 @@ public class AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_
public void clear() { public void clear() {
m.clear(); m.clear();
} }
protected AVL_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE start() {
if(m instanceof AVL_TREE_MAP) return ((AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE)m).first;
return ((NavigableSubMap KEY_VALUE_GENERIC_TYPE)m).findLowest();
}
protected AVL_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE end() {
if(m instanceof AVL_TREE_MAP) return null;
return ((NavigableSubMap KEY_VALUE_GENERIC_TYPE)m).findLowest();
}
protected AVL_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE next(AVL_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry) {
if(m instanceof AVL_TREE_MAP) return entry.next();
return ((NavigableSubMap KEY_VALUE_GENERIC_TYPE)m).next(entry);
}
protected AVL_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE previous(AVL_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry) {
if(m instanceof AVL_TREE_MAP) return entry.previous();
return ((NavigableSubMap KEY_VALUE_GENERIC_TYPE)m).previous(entry);
}
@Override
public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) {
Objects.requireNonNull(action);
for(AVL_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = start(), end = end();entry != null && (end == null || (end != previous(entry)));entry = next(entry))
action.accept(entry.key);
}
@Override
public <E> void forEach(E input, BI_OBJECT_CONSUMER KKS_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
for(AVL_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = start(), end = end();entry != null && (end == null || (end != previous(entry)));entry = next(entry))
action.accept(entry.key, input);
}
@Override
public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(AVL_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = start(), end = end();entry != null && (end == null || (end != previous(entry)));entry = next(entry))
if(filter.TEST_VALUE(entry.key)) return true;
return false;
}
@Override
public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(AVL_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = start(), end = end();entry != null && (end == null || (end != previous(entry)));entry = next(entry))
if(filter.TEST_VALUE(entry.key)) return false;
return true;
}
@Override
public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(AVL_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = start(), end = end();entry != null && (end == null || (end != previous(entry)));entry = next(entry))
if(!filter.TEST_VALUE(entry.key)) return false;
return true;
}
@Override
public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(AVL_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = start(), end = end();entry != null && (end == null || (end != previous(entry)));entry = next(entry))
if(filter.TEST_VALUE(entry.key)) return entry.key;
return EMPTY_KEY_VALUE;
}
} }
final class Values extends VALUE_ABSTRACT_COLLECTION VALUE_GENERIC_TYPE { final class Values extends VALUE_ABSTRACT_COLLECTION VALUE_GENERIC_TYPE {
@@ -1648,6 +2061,52 @@ public class AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_
public void clear() { public void clear() {
AVL_TREE_MAP.this.clear(); AVL_TREE_MAP.this.clear();
} }
@Override
public void forEach(VALUE_CONSUMER VALUE_SUPER_GENERIC_TYPE action) {
Objects.requireNonNull(action);
for(AVL_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next())
action.accept(entry.value);
}
@Override
public <E> void forEach(E input, VALUE_BI_OBJECT_CONSUMER VVS_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
for(AVL_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next())
action.accept(entry.value, input);
}
@Override
public boolean matchesAny(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(AVL_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next())
if(filter.VALUE_TEST_VALUE(entry.value)) return true;
return false;
}
@Override
public boolean matchesNone(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(AVL_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next())
if(filter.VALUE_TEST_VALUE(entry.value)) return false;
return true;
}
@Override
public boolean matchesAll(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(AVL_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next())
if(!filter.VALUE_TEST_VALUE(entry.value)) return false;
return true;
}
@Override
public VALUE_TYPE findFirst(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(AVL_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next())
if(filter.VALUE_TEST_VALUE(entry.value)) return entry.value;
return EMPTY_VALUE;
}
} }
final class EntryIterator extends MapEntryIterator implements ObjectListIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> { final class EntryIterator extends MapEntryIterator implements ObjectListIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> {
@@ -1834,9 +2293,9 @@ public class AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_
#endif #endif
int getHeight() { return state; } int getHeight() { return state; }
void updateHeight() { state = (1 + Math.max(left == null ? 0 : left.getHeight(), right == null ? 0 : right.getHeight())); } void updateHeight() { state = (1 + Math.max(left == null ? -1 : left.getHeight(), right == null ? -1 : right.getHeight())); }
int getBalance() { return (left == null ? 0 : left.getHeight()) - (right == null ? 0 : right.getBalance()); } int getBalance() { return (left == null ? -1 : left.getHeight()) - (right == null ? -1 : right.getHeight()); }
boolean needsSuccessor() { return left != null && right != null; } boolean needsSuccessor() { return left != null && right != null; }
@@ -3,14 +3,25 @@ package speiger.src.collections.PACKAGE.maps.impl.tree;
import java.util.Map; import java.util.Map;
#if TYPE_OBJECT #if TYPE_OBJECT
import java.util.Comparator; import java.util.Comparator;
import java.util.Objects;
#endif #endif
import java.util.Objects;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import java.util.function.Consumer;
import speiger.src.collections.PACKAGE.collections.BI_ITERATOR; import speiger.src.collections.PACKAGE.collections.BI_ITERATOR;
#if !TYPE_OBJECT #if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.functions.COMPARATOR; import speiger.src.collections.PACKAGE.functions.COMPARATOR;
import speiger.src.collections.PACKAGE.functions.CONSUMER;
#endif #endif
#if !TYPE_OBJECT && !VALUE_OBJECT
import speiger.src.collections.PACKAGE.functions.consumer.BI_OBJECT_CONSUMER;
#endif
#if !TYPE_OBJECT && !VALUE_BOOLEAN
import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
#endif
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;
import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR; import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR;
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;
@@ -20,13 +31,30 @@ import speiger.src.collections.PACKAGE.sets.NAVIGABLE_SET;
import speiger.src.collections.PACKAGE.sets.SET; import speiger.src.collections.PACKAGE.sets.SET;
import speiger.src.collections.PACKAGE.sets.SORTED_SET; import speiger.src.collections.PACKAGE.sets.SORTED_SET;
import speiger.src.collections.PACKAGE.utils.ITERATORS; import speiger.src.collections.PACKAGE.utils.ITERATORS;
import speiger.src.collections.PACKAGE.utils.maps.MAPS;
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 #if !SAME_TYPE
import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_UNARY_OPERATOR;
import speiger.src.collections.VALUE_PACKAGE.lists.VALUE_LIST_ITERATOR; import speiger.src.collections.VALUE_PACKAGE.lists.VALUE_LIST_ITERATOR;
import speiger.src.collections.VALUE_PACKAGE.utils.VALUE_ITERATORS; import speiger.src.collections.VALUE_PACKAGE.utils.VALUE_ITERATORS;
#endif #endif
#if !VALUE_OBJECT && !SAME_TYPE
import speiger.src.collections.VALUE_PACKAGE.functions.VALUE_CONSUMER;
#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
import speiger.src.collections.VALUE_PACKAGE.functions.consumer.VALUE_BI_OBJECT_CONSUMER;
import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_PREDICATE;
#endif
#if !TYPE_OBJECT && !VALUE_OBJECT #if !TYPE_OBJECT && !VALUE_OBJECT
import speiger.src.collections.objects.lists.ObjectListIterator; import speiger.src.collections.objects.lists.ObjectListIterator;
import speiger.src.collections.objects.utils.ObjectIterators; import speiger.src.collections.objects.utils.ObjectIterators;
@@ -416,7 +444,7 @@ public class RB_TREE_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_G
} }
@Override @Override
public VALUE_TYPE REMOVE_KEY(KEY_TYPE key) { public VALUE_TYPE REMOVE_VALUE(KEY_TYPE key) {
Entry KEY_VALUE_GENERIC_TYPE entry = findNode(key); Entry KEY_VALUE_GENERIC_TYPE entry = findNode(key);
if(entry == null) return getDefaultReturnValue(); if(entry == null) return getDefaultReturnValue();
VALUE_TYPE value = entry.value; VALUE_TYPE value = entry.value;
@@ -424,6 +452,15 @@ public class RB_TREE_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_G
return value; return value;
} }
@Override
public VALUE_TYPE REMOVE_VALUEOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) {
Entry KEY_VALUE_GENERIC_TYPE entry = findNode(key);
if(entry == null) return defaultValue;
VALUE_TYPE value = entry.value;
removeNode(entry);
return value;
}
#if TYPE_OBJECT && VALUE_OBJECT #if TYPE_OBJECT && VALUE_OBJECT
@Override @Override
public boolean remove(Object key, Object value) { public boolean remove(Object key, Object value) {
@@ -443,6 +480,101 @@ public class RB_TREE_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_G
} }
#endif #endif
@Override
public boolean replace(KEY_TYPE key, VALUE_TYPE oldValue, VALUE_TYPE newValue) {
Entry KEY_VALUE_GENERIC_TYPE entry = findNode(key);
if(entry == null || entry.value != oldValue) return false;
entry.value = newValue;
return true;
}
@Override
public VALUE_TYPE replace(KEY_TYPE key, VALUE_TYPE value) {
Entry KEY_VALUE_GENERIC_TYPE entry = findNode(key);
if(entry == null) return getDefaultReturnValue();
VALUE_TYPE oldValue = entry.value;
entry.value = value;
return oldValue;
}
@Override
public VALUE_TYPE COMPUTE(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) {
Entry KEY_VALUE_GENERIC_TYPE entry = findNode(key);
if(entry == null) {
VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, getDefaultReturnValue());
if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue;
put(key, newValue);
return newValue;
}
VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, entry.value);
if(VALUE_EQUALS(newValue, getDefaultReturnValue())) {
removeNode(entry);
return newValue;
}
entry.value = newValue;
return newValue;
}
@Override
public VALUE_TYPE COMPUTE_IF_ABSENT(KEY_TYPE key, FUNCTION KEY_VALUE_GENERIC_TYPE mappingFunction) {
Entry KEY_VALUE_GENERIC_TYPE entry = findNode(key);
if(entry == null) {
VALUE_TYPE newValue = mappingFunction.GET_VALUE(key);
if(VALUE_EQUALS(newValue, getDefaultReturnValue())) return newValue;
put(key, newValue);
return newValue;
}
return entry.value;
}
@Override
public VALUE_TYPE COMPUTE_IF_PRESENT(KEY_TYPE key, UNARY_OPERATOR KEY_VALUE_GENERIC_TYPE mappingFunction) {
Entry KEY_VALUE_GENERIC_TYPE entry = findNode(key);
if(entry == null) return getDefaultReturnValue();
VALUE_TYPE newValue = mappingFunction.APPLY_VALUE(key, entry.value);
if(VALUE_EQUALS(newValue, getDefaultReturnValue())) {
removeNode(entry);
return newValue;
}
entry.value = newValue;
return newValue;
}
@Override
public VALUE_TYPE MERGE(KEY_TYPE key, VALUE_TYPE value, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction) {
Entry KEY_VALUE_GENERIC_TYPE entry = findNode(key);
VALUE_TYPE newValue = entry == null ? value : mappingFunction.APPLY_VALUE(entry.value, value);
if(VALUE_EQUALS(newValue, getDefaultReturnValue())) {
if(entry != null)
removeNode(entry);
}
else if(entry == null) put(key, newValue);
else entry.value = 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();
Entry KEY_VALUE_GENERIC_TYPE subEntry = findNode(key);
VALUE_TYPE newValue = subEntry == null ? entry.ENTRY_VALUE() : mappingFunction.APPLY_VALUE(subEntry.value, entry.ENTRY_VALUE());
if(VALUE_EQUALS(newValue, getDefaultReturnValue())) {
if(subEntry != null)
removeNode(subEntry);
}
else if(subEntry == null) put(key, newValue);
else subEntry.value = newValue;
}
}
@Override
public void forEach(BI_CONSUMER KEY_VALUE_GENERIC_TYPE action) {
for(Entry KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next())
action.accept(entry.key, entry.value);
}
@Override @Override
public int size() { return size; } public int size() { return size; }
@@ -856,6 +988,14 @@ public class RB_TREE_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_G
return descendingMap; return descendingMap;
} }
RB_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE next(RB_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry) {
return entry.next();
}
RB_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE previous(RB_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry) {
return entry.previous();
}
@Override @Override
public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE subMap(KEY_TYPE fromKey, boolean fromInclusive, KEY_TYPE toKey, boolean toInclusive) { public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE subMap(KEY_TYPE fromKey, boolean fromInclusive, KEY_TYPE toKey, boolean toInclusive) {
if (!inRange(fromKey, fromInclusive)) throw new IllegalArgumentException("fromKey out of range"); if (!inRange(fromKey, fromInclusive)) throw new IllegalArgumentException("fromKey out of range");
@@ -936,6 +1076,18 @@ public class RB_TREE_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_G
@Override @Override
public MAP.Entry KEY_VALUE_GENERIC_TYPE higherEntry(KEY_TYPE e) { return super.lowerEntry(e); } public MAP.Entry KEY_VALUE_GENERIC_TYPE higherEntry(KEY_TYPE e) { return super.lowerEntry(e); }
protected RB_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE findLowest() {
if(fromStart) return m.first;
RB_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = loInclusive ? m.findCeilingNode(low) : m.findHigherNode(low);
return entry == null || tooHigh(entry.key) ? null : entry;
}
protected RB_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE findHighest() {
if(toEnd) return m.last;
RB_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = hiInclusive ? m.findFloorNode(high) : m.findLowerNode(high);
return entry == null || tooLow(entry.key) ? null : entry;
}
@Override @Override
LIST_ITERATOR KEY_GENERIC_TYPE keyIterator(boolean descending) { LIST_ITERATOR KEY_GENERIC_TYPE keyIterator(boolean descending) {
LIST_ITERATOR KEY_GENERIC_TYPE iter = new SubMapKeyIterator(!descending); LIST_ITERATOR KEY_GENERIC_TYPE iter = new SubMapKeyIterator(!descending);
@@ -948,6 +1100,14 @@ public class RB_TREE_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_G
return entry == null || !inClosedRange(key) ? null : ITERATORS.invert(new SubMapKeyIterator(entry, fromStart ? null : findLowest(), toEnd ? null : findHighest())); return entry == null || !inClosedRange(key) ? null : ITERATORS.invert(new SubMapKeyIterator(entry, fromStart ? null : findLowest(), toEnd ? null : findHighest()));
} }
RB_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE next(RB_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry) {
return entry.previous();
}
RB_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE previous(RB_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry) {
return entry.next();
}
@Override @Override
public COMPARATOR KEY_GENERIC_TYPE comparator() { return m.comparator() == null ? null : m.comparator().reversed(); } public COMPARATOR KEY_GENERIC_TYPE comparator() { return m.comparator() == null ? null : m.comparator().reversed(); }
@@ -1010,6 +1170,8 @@ public class RB_TREE_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_G
abstract LIST_ITERATOR KEY_GENERIC_TYPE keyIterator(KEY_TYPE key); abstract LIST_ITERATOR KEY_GENERIC_TYPE keyIterator(KEY_TYPE key);
abstract VALUE_LIST_ITERATOR VALUE_GENERIC_TYPE valueIterator(); abstract VALUE_LIST_ITERATOR VALUE_GENERIC_TYPE valueIterator();
abstract ObjectListIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> entryIterator(); abstract ObjectListIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> entryIterator();
abstract RB_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE next(RB_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry);
abstract RB_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE previous(RB_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry);
@Override @Override
public abstract NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE descendingMap(); public abstract NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE descendingMap();
@@ -1170,8 +1332,13 @@ public class RB_TREE_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_G
#endif #endif
@Override @Override
public VALUE_TYPE REMOVE_KEY(KEY_TYPE key) { public VALUE_TYPE REMOVE_VALUE(KEY_TYPE key) {
return inRange(key) ? m.REMOVE_KEY(key) : getDefaultReturnValue(); return inRange(key) ? m.REMOVE_VALUE(key) : getDefaultReturnValue();
}
@Override
public VALUE_TYPE REMOVE_VALUEOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) {
return inRange(key) ? m.REMOVE_VALUE(key) : defaultValue;
} }
#if TYPE_OBJECT && VALUE_OBJECT #if TYPE_OBJECT && VALUE_OBJECT
@@ -1213,6 +1380,12 @@ public class RB_TREE_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_G
return values; return values;
} }
@Override
public void forEach(BI_CONSUMER KEY_VALUE_GENERIC_TYPE action) {
for(RB_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = findLowest(), last = findHighest();entry != null && (last == null || last != previous(entry));entry = next(entry))
action.accept(entry.key, entry.value);
}
@Override @Override
public int size() { public int size() {
return (fromStart && toEnd) ? m.size() : entrySet().size(); return (fromStart && toEnd) ? m.size() : entrySet().size();
@@ -1358,6 +1531,68 @@ public class RB_TREE_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_G
public int size() { return NavigableSubMap.this.size(); } public int size() { return NavigableSubMap.this.size(); }
@Override @Override
public void clear() { NavigableSubMap.this.clear(); } public void clear() { NavigableSubMap.this.clear(); }
@Override
public void forEach(Consumer<? super MAP.Entry KEY_VALUE_GENERIC_TYPE> action) {
Objects.requireNonNull(action);
for(RB_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = findLowest(), last = findHighest();entry != null && (last == null || last != previous(entry));entry = next(entry))
action.accept(new BasicEntryKV_BRACES(entry.key, entry.value));
}
@Override
public <E> void forEach(E input, ObjectObjectConsumer<MAP.Entry KEY_VALUE_GENERIC_TYPE, E> action) {
Objects.requireNonNull(action);
for(RB_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = findLowest(), last = findHighest();entry != null && (last == null || last != previous(entry));entry = next(entry))
action.accept(new BasicEntryKV_BRACES(entry.key, entry.value), input);
}
@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 subEntry = new BasicEntryKV_BRACES();
for(RB_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = findLowest(), last = findHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) {
subEntry.set(entry.key, entry.value);
if(filter.getBoolean(subEntry)) 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 subEntry = new BasicEntryKV_BRACES();
for(RB_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = findLowest(), last = findHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) {
subEntry.set(entry.key, entry.value);
if(filter.getBoolean(subEntry)) 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 subEntry = new BasicEntryKV_BRACES();
for(RB_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = findLowest(), last = findHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) {
subEntry.set(entry.key, entry.value);
if(!filter.getBoolean(subEntry)) return false;
}
return true;
}
@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 subEntry = new BasicEntryKV_BRACES();
for(RB_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = findLowest(), last = findHighest();entry != null && (last == null || last != previous(entry));entry = next(entry)) {
subEntry.set(entry.key, entry.value);
if(filter.getBoolean(subEntry)) return subEntry;
}
return null;
}
} }
final class SubMapValues extends VALUE_ABSTRACT_COLLECTION VALUE_GENERIC_TYPE { final class SubMapValues extends VALUE_ABSTRACT_COLLECTION VALUE_GENERIC_TYPE {
@@ -1389,6 +1624,52 @@ public class RB_TREE_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_G
public void clear() { public void clear() {
NavigableSubMap.this.clear(); NavigableSubMap.this.clear();
} }
@Override
public void forEach(VALUE_CONSUMER VALUE_SUPER_GENERIC_TYPE action) {
Objects.requireNonNull(action);
for(RB_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = findLowest(), last = findHighest();entry != null && (last == null || last != previous(entry));entry = next(entry))
action.accept(entry.value);
}
@Override
public <E> void forEach(E input, VALUE_BI_OBJECT_CONSUMER VVS_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
for(RB_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = findLowest(), last = findHighest();entry != null && (last == null || last != previous(entry));entry = next(entry))
action.accept(entry.value, input);
}
@Override
public boolean matchesAny(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(RB_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = findLowest(), last = findHighest();entry != null && (last == null || last != previous(entry));entry = next(entry))
if(filter.VALUE_TEST_VALUE(entry.value)) return true;
return false;
}
@Override
public boolean matchesNone(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(RB_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = findLowest(), last = findHighest();entry != null && (last == null || last != previous(entry));entry = next(entry))
if(filter.VALUE_TEST_VALUE(entry.value)) return false;
return true;
}
@Override
public boolean matchesAll(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(RB_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = findLowest(), last = findHighest();entry != null && (last == null || last != previous(entry));entry = next(entry))
if(!filter.VALUE_TEST_VALUE(entry.value)) return false;
return true;
}
@Override
public VALUE_TYPE findFirst(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(RB_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = findLowest(), last = findHighest();entry != null && (last == null || last != previous(entry));entry = next(entry))
if(filter.VALUE_TEST_VALUE(entry.value)) return entry.value;
return EMPTY_VALUE;
}
} }
final class SubMapEntrySetIterator extends SubMapEntryIterator implements ObjectListIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> { final class SubMapEntrySetIterator extends SubMapEntryIterator implements ObjectListIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> {
@@ -1562,6 +1843,68 @@ public class RB_TREE_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_G
public void clear() { public void clear() {
RB_TREE_MAP.this.clear(); RB_TREE_MAP.this.clear();
} }
@Override
public void forEach(Consumer<? super MAP.Entry KEY_VALUE_GENERIC_TYPE> action) {
Objects.requireNonNull(action);
for(RB_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next())
action.accept(new BasicEntryKV_BRACES(entry.key, entry.value));
}
@Override
public <E> void forEach(E input, ObjectObjectConsumer<MAP.Entry KEY_VALUE_GENERIC_TYPE, E> action) {
Objects.requireNonNull(action);
for(RB_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next())
action.accept(new BasicEntryKV_BRACES(entry.key, entry.value), input);
}
@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 subEntry = new BasicEntryKV_BRACES();
for(RB_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) {
subEntry.set(entry.key, entry.value);
if(filter.getBoolean(subEntry)) 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 subEntry = new BasicEntryKV_BRACES();
for(RB_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) {
subEntry.set(entry.key, entry.value);
if(filter.getBoolean(subEntry)) 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 subEntry = new BasicEntryKV_BRACES();
for(RB_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) {
subEntry.set(entry.key, entry.value);
if(!filter.getBoolean(subEntry)) return false;
}
return true;
}
@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 subEntry = new BasicEntryKV_BRACES();
for(RB_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) {
subEntry.set(entry.key, entry.value);
if(filter.getBoolean(subEntry)) return subEntry;
}
return null;
}
} }
static final class KeySet KEY_VALUE_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE implements NAVIGABLE_SET KEY_GENERIC_TYPE { static final class KeySet KEY_VALUE_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE implements NAVIGABLE_SET KEY_GENERIC_TYPE {
@@ -1673,6 +2016,72 @@ public class RB_TREE_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_G
public void clear() { public void clear() {
m.clear(); m.clear();
} }
protected RB_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE start() {
if(m instanceof RB_TREE_MAP) return ((RB_TREE_MAP KEY_VALUE_GENERIC_TYPE)m).first;
return ((NavigableSubMap KEY_VALUE_GENERIC_TYPE)m).findLowest();
}
protected RB_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE end() {
if(m instanceof RB_TREE_MAP) return null;
return ((NavigableSubMap KEY_VALUE_GENERIC_TYPE)m).findLowest();
}
protected RB_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE next(RB_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry) {
if(m instanceof RB_TREE_MAP) return entry.next();
return ((NavigableSubMap KEY_VALUE_GENERIC_TYPE)m).next(entry);
}
protected RB_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE previous(RB_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry) {
if(m instanceof RB_TREE_MAP) return entry.previous();
return ((NavigableSubMap KEY_VALUE_GENERIC_TYPE)m).previous(entry);
}
@Override
public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) {
Objects.requireNonNull(action);
for(RB_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = start(), end = end();entry != null && (end == null || (end != previous(entry)));entry = next(entry))
action.accept(entry.key);
}
@Override
public <E> void forEach(E input, BI_OBJECT_CONSUMER KKS_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
for(RB_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = start(), end = end();entry != null && (end == null || (end != previous(entry)));entry = next(entry))
action.accept(entry.key, input);
}
@Override
public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(RB_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = start(), end = end();entry != null && (end == null || (end != previous(entry)));entry = next(entry))
if(filter.TEST_VALUE(entry.key)) return true;
return false;
}
@Override
public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(RB_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = start(), end = end();entry != null && (end == null || (end != previous(entry)));entry = next(entry))
if(filter.TEST_VALUE(entry.key)) return false;
return true;
}
@Override
public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(RB_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = start(), end = end();entry != null && (end == null || (end != previous(entry)));entry = next(entry))
if(!filter.TEST_VALUE(entry.key)) return false;
return true;
}
@Override
public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(RB_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = start(), end = end();entry != null && (end == null || (end != previous(entry)));entry = next(entry))
if(filter.TEST_VALUE(entry.key)) return entry.key;
return EMPTY_KEY_VALUE;
}
} }
final class Values extends VALUE_ABSTRACT_COLLECTION VALUE_GENERIC_TYPE { final class Values extends VALUE_ABSTRACT_COLLECTION VALUE_GENERIC_TYPE {
@@ -1705,6 +2114,52 @@ public class RB_TREE_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_G
public void clear() { public void clear() {
RB_TREE_MAP.this.clear(); RB_TREE_MAP.this.clear();
} }
@Override
public void forEach(VALUE_CONSUMER VALUE_SUPER_GENERIC_TYPE action) {
Objects.requireNonNull(action);
for(RB_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next())
action.accept(entry.value);
}
@Override
public <E> void forEach(E input, VALUE_BI_OBJECT_CONSUMER VVS_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
for(RB_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next())
action.accept(entry.value, input);
}
@Override
public boolean matchesAny(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(RB_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next())
if(filter.VALUE_TEST_VALUE(entry.value)) return true;
return false;
}
@Override
public boolean matchesNone(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(RB_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next())
if(filter.VALUE_TEST_VALUE(entry.value)) return false;
return true;
}
@Override
public boolean matchesAll(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(RB_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next())
if(!filter.VALUE_TEST_VALUE(entry.value)) return false;
return true;
}
@Override
public VALUE_TYPE findFirst(VALUE_PREDICATE VALUE_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(RB_TREE_MAP.Entry KEY_VALUE_GENERIC_TYPE entry = first;entry != null;entry = entry.next())
if(filter.VALUE_TEST_VALUE(entry.value)) return entry.value;
return EMPTY_VALUE;
}
} }
final class EntryIterator extends MapEntryIterator implements ObjectListIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> { final class EntryIterator extends MapEntryIterator implements ObjectListIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> {
@@ -8,11 +8,27 @@ import java.util.function.BiConsumer;
import java.util.function.BiFunction; import java.util.function.BiFunction;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.function.Function; import java.util.function.Function;
#if TYPE_OBJECT
import java.util.Comparator;
#endif
import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_COLLECTION; import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_COLLECTION;
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.FUNCTION;
import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR; import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR;
#if !TYPE_OBJECT && !TYPE_BOOLEAN
import speiger.src.collections.PACKAGE.functions.COMPARATOR;
#endif
#if !TYPE_BOOLEAN
import speiger.src.collections.PACKAGE.maps.impl.customHash.LINKED_CUSTOM_HASH_MAP;
import speiger.src.collections.PACKAGE.maps.impl.customHash.CUSTOM_HASH_MAP;
import speiger.src.collections.PACKAGE.maps.impl.hash.LINKED_HASH_MAP;
import speiger.src.collections.PACKAGE.maps.impl.hash.HASH_MAP;
import speiger.src.collections.PACKAGE.maps.impl.immutable.IMMUTABLE_HASH_MAP;
import speiger.src.collections.PACKAGE.maps.impl.tree.AVL_TREE_MAP;
import speiger.src.collections.PACKAGE.maps.impl.tree.RB_TREE_MAP;
import speiger.src.collections.PACKAGE.utils.STRATEGY;
#endif
import speiger.src.collections.PACKAGE.sets.SET; import speiger.src.collections.PACKAGE.sets.SET;
#if !SAME_TYPE #if !SAME_TYPE
import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_UNARY_OPERATOR; import speiger.src.collections.VALUE_PACKAGE.functions.function.VALUE_UNARY_OPERATOR;
@@ -50,6 +66,30 @@ public interface MAP KEY_VALUE_GENERIC_TYPE extends Map<CLASS_TYPE, CLASS_VALUE_
* @see Map#put(Object, Object) * @see Map#put(Object, Object)
*/ */
public VALUE_TYPE put(KEY_TYPE key, VALUE_TYPE value); public VALUE_TYPE put(KEY_TYPE key, VALUE_TYPE value);
/**
* Type Specific array method to bulk add elements into a map without creating a wrapper and increasing performances
* @param keys the keys that should be added
* @param values the values that should be added
* @see Map#putAll(Map)
* @throws IllegalStateException if the arrays are not the same size
*/
public default void putAll(KEY_TYPE[] keys, VALUE_TYPE[] values) {
if(keys.length != values.length) throw new IllegalStateException("Array sizes do not match");
putAll(keys, values, 0, keys.length);
}
/**
* Type Specific array method to bulk add elements into a map without creating a wrapper and increasing performances
* @param keys the keys that should be added
* @param values the values that should be added
* @param offset where the to start in the array
* @param size how many elements should be added
* @see Map#putAll(Map)
* @throws IllegalStateException if the arrays are not within the range
*/
public void putAll(KEY_TYPE[] keys, VALUE_TYPE[] values, int offset, int size);
/** /**
* Type Specific method to reduce boxing/unboxing of values * Type Specific method to reduce boxing/unboxing of values
* @param key the key that should be inserted, * @param key the key that should be inserted,
@@ -59,6 +99,12 @@ public interface MAP KEY_VALUE_GENERIC_TYPE extends Map<CLASS_TYPE, CLASS_VALUE_
*/ */
public VALUE_TYPE putIfAbsent(KEY_TYPE key, VALUE_TYPE value); public VALUE_TYPE putIfAbsent(KEY_TYPE key, VALUE_TYPE value);
/**
* Type-Specific bulk put method put elements into the map if not present.
* @param m elements that should be added if not present.
*/
public void putAllIfAbsent(MAP KEY_VALUE_GENERIC_TYPE m);
#if VALUE_PRIMITIVES #if VALUE_PRIMITIVES
/** /**
* A Helper method to add a primitives together. If key is not present then this functions as a put. * A Helper method to add a primitives together. If key is not present then this functions as a put.
@@ -68,6 +114,12 @@ public interface MAP KEY_VALUE_GENERIC_TYPE extends Map<CLASS_TYPE, CLASS_VALUE_
*/ */
public VALUE_TYPE addTo(KEY_TYPE key, VALUE_TYPE value); public VALUE_TYPE addTo(KEY_TYPE key, VALUE_TYPE value);
/**
* A Helper method to bulk add primitives together.
* @param m the values that should be added/inserted
*/
public void addToAll(MAP KEY_VALUE_GENERIC_TYPE m);
#endif #endif
/** /**
* Type Specific function for the bull putting of values * Type Specific function for the bull putting of values
@@ -120,7 +172,7 @@ public interface MAP KEY_VALUE_GENERIC_TYPE extends Map<CLASS_TYPE, CLASS_VALUE_
* @param key the element that should be removed * @param key the element that should be removed
* @return the value that was removed or default return value * @return the value that was removed or default return value
*/ */
public VALUE_TYPE REMOVE_KEY(KEY_TYPE key); public VALUE_TYPE REMOVE_VALUE(KEY_TYPE key);
/** /**
* @see Map#remove(Object) * @see Map#remove(Object)
@@ -131,9 +183,9 @@ public interface MAP KEY_VALUE_GENERIC_TYPE extends Map<CLASS_TYPE, CLASS_VALUE_
@Override @Override
public default CLASS_VALUE_TYPE remove(Object key) { public default CLASS_VALUE_TYPE remove(Object key) {
#if TYPE_OBJECT #if TYPE_OBJECT
return VALUE_TO_OBJ(REMOVE_KEY((CLASS_TYPE)key)); return VALUE_TO_OBJ(REMOVE_VALUE((CLASS_TYPE)key));
#else #else
return key instanceof CLASS_TYPE ? VALUE_TO_OBJ(REMOVE_KEY(CLASS_TO_KEY(key))) : VALUE_TO_OBJ(getDefaultReturnValue()); return key instanceof CLASS_TYPE ? VALUE_TO_OBJ(REMOVE_VALUE(CLASS_TO_KEY(key))) : VALUE_TO_OBJ(getDefaultReturnValue());
#endif #endif
} }
@@ -163,8 +215,16 @@ public interface MAP KEY_VALUE_GENERIC_TYPE extends Map<CLASS_TYPE, CLASS_VALUE_
return key instanceof CLASS_TYPE && value instanceof CLASS_VALUE_TYPE && remove(CLASS_TO_KEY(key), CLASS_TO_VALUE(value)); return key instanceof CLASS_TYPE && value instanceof CLASS_VALUE_TYPE && remove(CLASS_TO_KEY(key), CLASS_TO_VALUE(value));
#endif #endif
} }
#endif
#endif
/**
* Type-Specific Remove function with a default return value if wanted.
* @see Map#remove(Object, Object)
* @param key the element that should be removed
* @param defaultValue the value that should be returned if the entry doesn't exist
* @return the value that was removed or default value
*/
public VALUE_TYPE REMOVE_VALUEOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue);
/** /**
* A Type Specific replace method to replace an existing value * A Type Specific replace method to replace an existing value
* @param key the element that should be searched for * @param key the element that should be searched for
@@ -182,6 +242,12 @@ public interface MAP KEY_VALUE_GENERIC_TYPE extends Map<CLASS_TYPE, CLASS_VALUE_
* @note this fails if the value is not present * @note this fails if the value is not present
*/ */
public VALUE_TYPE replace(KEY_TYPE key, VALUE_TYPE value); public VALUE_TYPE replace(KEY_TYPE key, VALUE_TYPE value);
/**
* Type-Specific bulk replace method. Could be seen as putAllIfPresent
* @param m elements that should be replaced.
*/
public void REPLACE_VALUES(MAP KEY_VALUE_GENERIC_TYPE m);
/** /**
* A Type Specific mass replace method to reduce boxing/unboxing * A Type Specific mass replace method to reduce boxing/unboxing
* @param mappingFunction operation to replace all values * @param mappingFunction operation to replace all values
@@ -218,6 +284,13 @@ public interface MAP KEY_VALUE_GENERIC_TYPE extends Map<CLASS_TYPE, CLASS_VALUE_
* @note if the result matches the default return value then the key is removed from the map * @note if the result matches the default return value then the key is removed from the map
*/ */
public VALUE_TYPE MERGE(KEY_TYPE key, VALUE_TYPE value, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction); public VALUE_TYPE MERGE(KEY_TYPE key, VALUE_TYPE value, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction);
/**
* A Bulk method for merging Maps.
* @param m the entries that should be bulk added
* @param mappingFunction the operator that should generate the new Value
* @note if the result matches the default return value then the key is removed from the map
*/
public void BULK_MERGE(MAP KEY_VALUE_GENERIC_TYPE m, VALUE_UNARY_OPERATOR VALUE_VALUE_GENERIC_TYPE mappingFunction);
#if !TYPE_OBJECT || !VALUE_OBJECT #if !TYPE_OBJECT || !VALUE_OBJECT
@Override @Override
@@ -391,4 +464,517 @@ public interface MAP KEY_VALUE_GENERIC_TYPE extends Map<CLASS_TYPE, CLASS_VALUE_
public default CLASS_VALUE_TYPE setValue(CLASS_VALUE_TYPE value) { return VALUE_TO_OBJ(setValue(OBJ_TO_VALUE(value))); } public default CLASS_VALUE_TYPE setValue(CLASS_VALUE_TYPE value) { return VALUE_TO_OBJ(setValue(OBJ_TO_VALUE(value))); }
#endif #endif
} }
#if !TYPE_BOOLEAN
/**
* Helper function to unify code
* @Type(T)
* @ValueType(V)
* @return a OpenHashMap
*/
public static GENERIC_KEY_VALUE_BRACES HASH_MAP KEY_VALUE_GENERIC_TYPE createMap() {
return new HASH_MAPKV_BRACES();
}
/**
* Helper function to unify code
* @param size the minimum capacity of the Map
* @Type(T)
* @ValueType(V)
* @return a OpenHashMap with a mimimum capacity
*/
public static GENERIC_KEY_VALUE_BRACES HASH_MAP KEY_VALUE_GENERIC_TYPE createMap(int size) {
return new HASH_MAPKV_BRACES(size);
}
/**
* Helper function to unify code
* @param keys the keys that should be inserted
* @param values the values that should be inserted
* @Type(T)
* @ValueType(V)
* @throws IllegalStateException if the keys and values do not match in length
* @return a OpenHashMap thats contains the injected values
*/
public static GENERIC_KEY_VALUE_BRACES HASH_MAP KEY_VALUE_GENERIC_TYPE createMap(KEY_TYPE[] keys, VALUE_TYPE[] values) {
return new HASH_MAPKV_BRACES(keys, values);
}
#if !TYPE_OBJECT || !VALUE_OBJECT
/**
* Helper function to unify code
* @param keys the keys that should be inserted
* @param values the values that should be inserted
* @Type(T)
* @ValueType(V)
* @throws IllegalStateException if the keys and values do not match in length
* @return a OpenHashMap thats contains the injected values
* @note the keys and values will be unboxed
*/
public static GENERIC_KEY_VALUE_BRACES HASH_MAP KEY_VALUE_GENERIC_TYPE createMap(CLASS_TYPE[] keys, CLASS_VALUE_TYPE[] values) {
return new HASH_MAPKV_BRACES(keys, values);
}
#endif
/**
* Helper function to unify code
* @param map that should be cloned
* @Type(T)
* @ValueType(V)
* @return a OpenHashMap thats copies the contents of the provided map
*/
public static GENERIC_KEY_VALUE_BRACES HASH_MAP KEY_VALUE_GENERIC_TYPE createMap(MAP KEY_VALUE_GENERIC_TYPE map) {
return new HASH_MAPKV_BRACES(map);
}
/**
* Helper function to unify code
* @param map that should be cloned
* @Type(T)
* @ValueType(V)
* @return a OpenHashMap thats copies the contents of the provided map
* @note the map will be unboxed
*/
public static GENERIC_KEY_VALUE_BRACES HASH_MAP KEY_VALUE_GENERIC_TYPE createMap(Map<? extends CLASS_TYPE, ? extends CLASS_VALUE_TYPE> map) {
return new HASH_MAPKV_BRACES(map);
}
/**
* Helper function to unify code
* @Type(T)
* @ValueType(V)
* @return a LinkedOpenHashMap
*/
public static GENERIC_KEY_VALUE_BRACES LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE createLinkedMap() {
return new LINKED_HASH_MAPKV_BRACES();
}
/**
* Helper function to unify code
* @param size the minimum capacity of the Map
* @Type(T)
* @ValueType(V)
* @return a LinkedOpenHashMap with a mimimum capacity
*/
public static GENERIC_KEY_VALUE_BRACES LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE createLinkedMap(int size) {
return new LINKED_HASH_MAPKV_BRACES(size);
}
/**
* Helper function to unify code
* @param keys the keys that should be inserted
* @param values the values that should be inserted
* @Type(T)
* @ValueType(V)
* @throws IllegalStateException if the keys and values do not match in length
* @return a LinkedOpenHashMap thats contains the injected values
*/
public static GENERIC_KEY_VALUE_BRACES LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE createLinkedMap(KEY_TYPE[] keys, VALUE_TYPE[] values) {
return new LINKED_HASH_MAPKV_BRACES(keys, values);
}
#if !TYPE_OBJECT || !VALUE_OBJECT
/**
* Helper function to unify code
* @param keys the keys that should be inserted
* @param values the values that should be inserted
* @Type(T)
* @ValueType(V)
* @throws IllegalStateException if the keys and values do not match in length
* @return a LinkedOpenHashMap thats contains the injected values
* @note the keys and values will be unboxed
*/
public static GENERIC_KEY_VALUE_BRACES LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE createLinkedMap(CLASS_TYPE[] keys, CLASS_VALUE_TYPE[] values) {
return new LINKED_HASH_MAPKV_BRACES(keys, values);
}
#endif
/**
* Helper function to unify code
* @param map that should be cloned
* @Type(T)
* @ValueType(V)
* @return a LinkedOpenHashMap thats copies the contents of the provided map
*/
public static GENERIC_KEY_VALUE_BRACES LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE createLinkedMap(MAP KEY_VALUE_GENERIC_TYPE map) {
return new LINKED_HASH_MAPKV_BRACES(map);
}
/**
* Helper function to unify code
* @param map that should be cloned
* @Type(T)
* @ValueType(V)
* @return a LinkedOpenHashMap thats copies the contents of the provided map
* @note the map will be unboxed
*/
public static GENERIC_KEY_VALUE_BRACES IMMUTABLE_HASH_MAP KEY_VALUE_GENERIC_TYPE createLinkedMap(Map<? extends CLASS_TYPE, ? extends CLASS_VALUE_TYPE> map) {
return new IMMUTABLE_HASH_MAPKV_BRACES(map);
}
/**
* Helper function to unify code
* @param keys the keys that should be inserted
* @param values the values that should be inserted
* @Type(T)
* @ValueType(V)
* @throws IllegalStateException if the keys and values do not match in length
* @return a ImmutableOpenHashMap thats contains the injected values
*/
public static GENERIC_KEY_VALUE_BRACES IMMUTABLE_HASH_MAP KEY_VALUE_GENERIC_TYPE createImmutable(KEY_TYPE[] keys, VALUE_TYPE[] values) {
return new IMMUTABLE_HASH_MAPKV_BRACES(keys, values);
}
#if !TYPE_OBJECT || !VALUE_OBJECT
/**
* Helper function to unify code
* @param keys the keys that should be inserted
* @param values the values that should be inserted
* @Type(T)
* @ValueType(V)
* @throws IllegalStateException if the keys and values do not match in length
* @return a ImmutableOpenHashMap thats contains the injected values
* @note the keys and values will be unboxed
*/
public static GENERIC_KEY_VALUE_BRACES IMMUTABLE_HASH_MAP KEY_VALUE_GENERIC_TYPE createImmutable(CLASS_TYPE[] keys, CLASS_VALUE_TYPE[] values) {
return new IMMUTABLE_HASH_MAPKV_BRACES(keys, values);
}
#endif
/**
* Helper function to unify code
* @param map that should be cloned
* @Type(T)
* @ValueType(V)
* @return a ImmutableOpenHashMap thats copies the contents of the provided map
*/
public static GENERIC_KEY_VALUE_BRACES IMMUTABLE_HASH_MAP KEY_VALUE_GENERIC_TYPE createImmutable(MAP KEY_VALUE_GENERIC_TYPE map) {
return new IMMUTABLE_HASH_MAPKV_BRACES(map);
}
/**
* Helper function to unify code
* @param map that should be cloned
* @Type(T)
* @ValueType(V)
* @return a ImmutableOpenHashMap thats copies the contents of the provided map
* @note the map will be unboxed
*/
public static GENERIC_KEY_VALUE_BRACES IMMUTABLE_HASH_MAP KEY_VALUE_GENERIC_TYPE createImmutable(Map<? extends CLASS_TYPE, ? extends CLASS_VALUE_TYPE> map) {
return new IMMUTABLE_HASH_MAPKV_BRACES(map);
}
/**
* Helper function to unify code
* @param strategy the Hash Controller
* @Type(T)
* @ValueType(V)
* @return a CustomOpenHashMap
*/
public static GENERIC_KEY_VALUE_BRACES CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE createCustomMap(STRATEGY KEY_GENERIC_TYPE strategy) {
return new CUSTOM_HASH_MAPKV_BRACES(strategy);
}
/**
* Helper function to unify code
* @param size the minimum capacity of the Map
* @param strategy the Hash Controller
* @Type(T)
* @ValueType(V)
* @return a CustomOpenHashMap with a mimimum capacity
*/
public static GENERIC_KEY_VALUE_BRACES CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE createCustomMap(int size, STRATEGY KEY_GENERIC_TYPE strategy) {
return new CUSTOM_HASH_MAPKV_BRACES(size, strategy);
}
/**
* Helper function to unify code
* @param keys the keys that should be inserted
* @param values the values that should be inserted
* @param strategy the Hash Controller
* @Type(T)
* @ValueType(V)
* @throws IllegalStateException if the keys and values do not match in length
* @return a CustomOpenHashMap thats contains the injected values
*/
public static GENERIC_KEY_VALUE_BRACES CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE createCustomMap(KEY_TYPE[] keys, VALUE_TYPE[] values, STRATEGY KEY_GENERIC_TYPE strategy) {
return new CUSTOM_HASH_MAPKV_BRACES(keys, values, strategy);
}
#if !TYPE_OBJECT || !VALUE_OBJECT
/**
* Helper function to unify code
* @param keys the keys that should be inserted
* @param values the values that should be inserted
* @param strategy the Hash Controller
* @Type(T)
* @ValueType(V)
* @throws IllegalStateException if the keys and values do not match in length
* @return a CustomOpenHashMap thats contains the injected values
* @note the keys and values will be unboxed
*/
public static GENERIC_KEY_VALUE_BRACES CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE createCustomMap(CLASS_TYPE[] keys, CLASS_VALUE_TYPE[] values, STRATEGY KEY_GENERIC_TYPE strategy) {
return new CUSTOM_HASH_MAPKV_BRACES(keys, values, strategy);
}
#endif
/**
* Helper function to unify code
* @param map that should be cloned
* @param strategy the Hash Controller
* @Type(T)
* @ValueType(V)
* @return a CustomOpenHashMap thats copies the contents of the provided map
*/
public static GENERIC_KEY_VALUE_BRACES CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE createCustomMap(MAP KEY_VALUE_GENERIC_TYPE map, STRATEGY KEY_GENERIC_TYPE strategy) {
return new CUSTOM_HASH_MAPKV_BRACES(map, strategy);
}
/**
* Helper function to unify code
* @param map that should be cloned
* @param strategy the Hash Controller
* @Type(T)
* @ValueType(V)
* @return a CustomOpenHashMap thats copies the contents of the provided map
* @note the map will be unboxed
*/
public static GENERIC_KEY_VALUE_BRACES CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE createCustomMap(Map<? extends CLASS_TYPE, ? extends CLASS_VALUE_TYPE> map, STRATEGY KEY_GENERIC_TYPE strategy) {
return new CUSTOM_HASH_MAPKV_BRACES(map, strategy);
}
/**
* Helper function to unify code
* @param strategy the Hash Controller
* @Type(T)
* @ValueType(V)
* @return a CustomLinkedOpenHashMap
*/
public static GENERIC_KEY_VALUE_BRACES LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE createCustomLinkedMap(STRATEGY KEY_GENERIC_TYPE strategy) {
return new LINKED_CUSTOM_HASH_MAPKV_BRACES(strategy);
}
/**
* Helper function to unify code
* @param size the minimum capacity of the Map
* @param strategy the Hash Controller
* @Type(T)
* @ValueType(V)
* @return a CustomLinkedOpenHashMap with a mimimum capacity
*/
public static GENERIC_KEY_VALUE_BRACES LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE createCustomLinkedMap(int size, STRATEGY KEY_GENERIC_TYPE strategy) {
return new LINKED_CUSTOM_HASH_MAPKV_BRACES(size, strategy);
}
/**
* Helper function to unify code
* @param keys the keys that should be inserted
* @param values the values that should be inserted
* @param strategy the Hash Controller
* @Type(T)
* @ValueType(V)
* @throws IllegalStateException if the keys and values do not match in length
* @return a CustomLinkedOpenHashMap thats contains the injected values
*/
public static GENERIC_KEY_VALUE_BRACES LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE createCustomLinkedMap(KEY_TYPE[] keys, VALUE_TYPE[] values, STRATEGY KEY_GENERIC_TYPE strategy) {
return new LINKED_CUSTOM_HASH_MAPKV_BRACES(keys, values, strategy);
}
#if !TYPE_OBJECT || !VALUE_OBJECT
/**
* Helper function to unify code
* @param keys the keys that should be inserted
* @param values the values that should be inserted
* @param strategy the Hash Controller
* @Type(T)
* @ValueType(V)
* @throws IllegalStateException if the keys and values do not match in length
* @return a CustomLinkedOpenHashMap thats contains the injected values
* @note the keys and values will be unboxed
*/
public static GENERIC_KEY_VALUE_BRACES LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE createCustomLinkedMap(CLASS_TYPE[] keys, CLASS_VALUE_TYPE[] values, STRATEGY KEY_GENERIC_TYPE strategy) {
return new LINKED_CUSTOM_HASH_MAPKV_BRACES(keys, values, strategy);
}
#endif
/**
* Helper function to unify code
* @param map that should be cloned
* @param strategy the Hash Controller
* @Type(T)
* @ValueType(V)
* @return a CustomLinkedOpenHashMap thats copies the contents of the provided map
*/
public static GENERIC_KEY_VALUE_BRACES LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE createCustomLinkedMap(MAP KEY_VALUE_GENERIC_TYPE map, STRATEGY KEY_GENERIC_TYPE strategy) {
return new LINKED_CUSTOM_HASH_MAPKV_BRACES(map, strategy);
}
/**
* Helper function to unify code
* @param map that should be cloned
* @param strategy the Hash Controller
* @Type(T)
* @ValueType(V)
* @return a CustomLinkedOpenHashMap thats copies the contents of the provided map
* @note the map will be unboxed
*/
public static GENERIC_KEY_VALUE_BRACES LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE createCustomLinkedMap(Map<? extends CLASS_TYPE, ? extends CLASS_VALUE_TYPE> map, STRATEGY KEY_GENERIC_TYPE strategy) {
return new LINKED_CUSTOM_HASH_MAPKV_BRACES(map, strategy);
}
/**
* Helper function to unify code
* @Type(T)
* @ValueType(V)
* @return a RBTreeMap
*/
public static GENERIC_KEY_VALUE_BRACES RB_TREE_MAP KEY_VALUE_GENERIC_TYPE createRBTreeMap() {
return new RB_TREE_MAPKV_BRACES();
}
/**
* Helper function to unify code
* @param comp the Sorter of the TreeMap
* @Type(T)
* @ValueType(V)
* @return a RBTreeMap
*/
public static GENERIC_KEY_VALUE_BRACES RB_TREE_MAP KEY_VALUE_GENERIC_TYPE createRBTreeMap(COMPARATOR KEY_GENERIC_TYPE comp) {
return new RB_TREE_MAPKV_BRACES(comp);
}
/**
* Helper function to unify code
* @param keys the keys that should be inserted
* @param values the values that should be inserted
* @param comp the Sorter of the TreeMap
* @Type(T)
* @ValueType(V)
* @throws IllegalStateException if the keys and values do not match in length
* @return a RBTreeMap thats contains the injected values
*/
public static GENERIC_KEY_VALUE_BRACES RB_TREE_MAP KEY_VALUE_GENERIC_TYPE createRBTreeMap(KEY_TYPE[] keys, VALUE_TYPE[] values, COMPARATOR KEY_GENERIC_TYPE comp) {
return new RB_TREE_MAPKV_BRACES(keys, values, comp);
}
#if !TYPE_OBJECT || !VALUE_OBJECT
/**
* Helper function to unify code
* @param keys the keys that should be inserted
* @param values the values that should be inserted
* @param comp the Sorter of the TreeMap
* @Type(T)
* @ValueType(V)
* @throws IllegalStateException if the keys and values do not match in length
* @return a RBTreeMap thats contains the injected values
* @note the keys and values will be unboxed
*/
public static GENERIC_KEY_VALUE_BRACES RB_TREE_MAP KEY_VALUE_GENERIC_TYPE createRBTreeMap(CLASS_TYPE[] keys, CLASS_VALUE_TYPE[] values, COMPARATOR KEY_GENERIC_TYPE comp) {
return new RB_TREE_MAPKV_BRACES(keys, values, comp);
}
#endif
/**
* Helper function to unify code
* @param map that should be cloned
* @param comp the Sorter of the TreeMap
* @Type(T)
* @ValueType(V)
* @return a RBTreeMap thats copies the contents of the provided map
*/
public static GENERIC_KEY_VALUE_BRACES RB_TREE_MAP KEY_VALUE_GENERIC_TYPE createRBTreeMap(MAP KEY_VALUE_GENERIC_TYPE map, COMPARATOR KEY_GENERIC_TYPE comp) {
return new RB_TREE_MAPKV_BRACES(map, comp);
}
/**
* Helper function to unify code
* @param map that should be cloned
* @param comp the Sorter of the TreeMap
* @Type(T)
* @ValueType(V)
* @return a RBTreeMap thats copies the contents of the provided map
* @note the map will be unboxed
*/
public static GENERIC_KEY_VALUE_BRACES RB_TREE_MAP KEY_VALUE_GENERIC_TYPE createRBTreeMap(Map<? extends CLASS_TYPE, ? extends CLASS_VALUE_TYPE> map, COMPARATOR KEY_GENERIC_TYPE comp) {
return new RB_TREE_MAPKV_BRACES(map, comp);
}
/**
* Helper function to unify code
* @Type(T)
* @ValueType(V)
* @return a AVLTreeMap
*/
public static GENERIC_KEY_VALUE_BRACES AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE createAVLTreeMap() {
return new AVL_TREE_MAPKV_BRACES();
}
/**
* Helper function to unify code
* @param comp the Sorter of the TreeMap
* @Type(T)
* @ValueType(V)
* @return a AVLTreeMap
*/
public static GENERIC_KEY_VALUE_BRACES AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE createAVLTreeMap(COMPARATOR KEY_GENERIC_TYPE comp) {
return new AVL_TREE_MAPKV_BRACES(comp);
}
/**
* Helper function to unify code
* @param keys the keys that should be inserted
* @param values the values that should be inserted
* @param comp the Sorter of the TreeMap
* @Type(T)
* @ValueType(V)
* @throws IllegalStateException if the keys and values do not match in length
* @return a AVLTreeMap thats contains the injected values
*/
public static GENERIC_KEY_VALUE_BRACES AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE createAVLTreeMap(KEY_TYPE[] keys, VALUE_TYPE[] values, COMPARATOR KEY_GENERIC_TYPE comp) {
return new AVL_TREE_MAPKV_BRACES(keys, values, comp);
}
#if !TYPE_OBJECT || !VALUE_OBJECT
/**
* Helper function to unify code
* @param keys the keys that should be inserted
* @param values the values that should be inserted
* @param comp the Sorter of the TreeMap
* @Type(T)
* @ValueType(V)
* @throws IllegalStateException if the keys and values do not match in length
* @return a AVLTreeMap thats contains the injected values
* @note the keys and values will be unboxed
*/
public static GENERIC_KEY_VALUE_BRACES AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE createAVLTreeMap(CLASS_TYPE[] keys, CLASS_VALUE_TYPE[] values, COMPARATOR KEY_GENERIC_TYPE comp) {
return new AVL_TREE_MAPKV_BRACES(keys, values, comp);
}
#endif
/**
* Helper function to unify code
* @param map that should be cloned
* @param comp the Sorter of the TreeMap
* @Type(T)
* @ValueType(V)
* @return a AVLTreeMap thats copies the contents of the provided map
*/
public static GENERIC_KEY_VALUE_BRACES AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE createAVLTreeMap(MAP KEY_VALUE_GENERIC_TYPE map, COMPARATOR KEY_GENERIC_TYPE comp) {
return new AVL_TREE_MAPKV_BRACES(map, comp);
}
/**
* Helper function to unify code
* @param map that should be cloned
* @param comp the Sorter of the TreeMap
* @Type(T)
* @ValueType(V)
* @return a AVLTreeMap thats copies the contents of the provided map
* @note the map will be unboxed
*/
public static GENERIC_KEY_VALUE_BRACES AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE createAVLTreeMap(Map<? extends CLASS_TYPE, ? extends CLASS_VALUE_TYPE> map, COMPARATOR KEY_GENERIC_TYPE comp) {
return new AVL_TREE_MAPKV_BRACES(map, comp);
}
#endif
} }
@@ -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);
}
}
@@ -3,13 +3,18 @@ package speiger.src.collections.PACKAGE.queues;
#if TYPE_OBJECT #if TYPE_OBJECT
import java.util.Arrays; import java.util.Arrays;
import java.util.Comparator; import java.util.Comparator;
import java.util.function.Consumer;
#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.PACKAGE.functions.consumer.BI_OBJECT_CONSUMER;
import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
import speiger.src.collections.utils.ITrimmable; import speiger.src.collections.utils.ITrimmable;
/** /**
@@ -101,21 +106,21 @@ public class ARRAY_FIFO_QUEUE KEY_GENERIC_TYPE implements PRIORITY_DEQUEUE KEY_G
} }
@Override @Override
public void ENQUEUE(KEY_TYPE e) { public void enqueue(KEY_TYPE e) {
array[last] = e; array[last] = e;
last = ++last % array.length; last = ++last % array.length;
if(last == first) expand(); if(last == first) expand();
} }
@Override @Override
public void ENQUEUE_FIRST(KEY_TYPE e) { public void enqueueFirst(KEY_TYPE e) {
if(first == 0) first = array.length; if(first == 0) first = array.length;
array[--first] = e; array[--first] = e;
if(first == last) expand(); if(first == last) expand();
} }
@Override @Override
public KEY_TYPE DEQUEUE() { public KEY_TYPE dequeue() {
if(first == last) throw new NoSuchElementException(); if(first == last) throw new NoSuchElementException();
KEY_TYPE data = array[first]; KEY_TYPE data = array[first];
#if TYPE_OBJECT #if TYPE_OBJECT
@@ -127,7 +132,7 @@ public class ARRAY_FIFO_QUEUE KEY_GENERIC_TYPE implements PRIORITY_DEQUEUE KEY_G
} }
@Override @Override
public KEY_TYPE DEQUEUE_LAST() { public KEY_TYPE dequeueLast() {
if(first == last) throw new NoSuchElementException(); if(first == last) throw new NoSuchElementException();
if(last == 0) last = array.length; if(last == 0) last = array.length;
KEY_TYPE data = array[--last]; KEY_TYPE data = array[--last];
@@ -139,13 +144,13 @@ public class ARRAY_FIFO_QUEUE KEY_GENERIC_TYPE implements PRIORITY_DEQUEUE KEY_G
} }
@Override @Override
public KEY_TYPE PEEK(int index) { public KEY_TYPE peek(int index) {
if(first == last || index < 0 || index > size()) throw new NoSuchElementException(); if(first == last || index < 0 || index > size()) throw new NoSuchElementException();
return array[(first + index) % array.length]; return array[(first + index) % array.length];
} }
@Override @Override
public boolean REMOVE(KEY_TYPE e) { public boolean removeFirst(KEY_TYPE e) {
if(first == last) return false; if(first == last) return false;
for(int i = 0,m=size();i<m;i++) { for(int i = 0,m=size();i<m;i++) {
int index = (first + i) % array.length; int index = (first + i) % array.length;
@@ -156,8 +161,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;
@@ -221,6 +225,65 @@ public class ARRAY_FIFO_QUEUE KEY_GENERIC_TYPE implements PRIORITY_DEQUEUE KEY_G
@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_OBJECT_CONSUMER KKS_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
if(first == last) return;
for(int i = 0,m=size();i<m;i++)
action.accept(array[(first + i) % array.length], input);
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;
}
@Override @Override
public boolean trim(int size) { public boolean trim(int size) {
int newSize = Math.max(size, size()); int newSize = Math.max(size, size());
@@ -237,9 +300,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(MIN_CAPACITY, 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,25 +327,6 @@ 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 > MIN_CAPACITY && size <= array.length / 4) resize(size, array.length / 2);
@@ -4,14 +4,18 @@ 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;
#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.PACKAGE.functions.consumer.BI_OBJECT_CONSUMER;
import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
import speiger.src.collections.PACKAGE.utils.ARRAYS; import speiger.src.collections.PACKAGE.utils.ARRAYS;
/** /**
@@ -180,7 +184,7 @@ public class ARRAY_PRIORITY_QUEUE KEY_GENERIC_TYPE implements PRIORITY_QUEUE KEY
} }
@Override @Override
public void ENQUEUE(KEY_TYPE e) { public void enqueue(KEY_TYPE e) {
if(size == array.length) array = Arrays.copyOf(array, size+1); if(size == array.length) array = Arrays.copyOf(array, size+1);
if(firstIndex != -1){ if(firstIndex != -1){
int compare = comparator == null ? COMPAREABLE_TO_KEY(e, array[firstIndex]) : comparator.compare(e, array[firstIndex]); int compare = comparator == null ? COMPAREABLE_TO_KEY(e, array[firstIndex]) : comparator.compare(e, array[firstIndex]);
@@ -191,7 +195,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 +208,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,6 +255,58 @@ 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_OBJECT_CONSUMER KKS_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
for(int i = 0,m=size;i<m;i++) action.accept(dequeue(), input);
}
@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;
}
@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 @Override
public ITERATOR KEY_GENERIC_TYPE iterator() { public ITERATOR KEY_GENERIC_TYPE iterator() {
return new Iter(); return new Iter();
@@ -262,21 +318,12 @@ public class ARRAY_PRIORITY_QUEUE KEY_GENERIC_TYPE implements PRIORITY_QUEUE KEY
} }
@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 +353,7 @@ public class ARRAY_PRIORITY_QUEUE KEY_GENERIC_TYPE implements PRIORITY_QUEUE KEY
@Override @Override
public KEY_TYPE NEXT() { public KEY_TYPE NEXT() {
return DEQUEUE(); return dequeue();
} }
} }
} }
@@ -4,14 +4,18 @@ 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;
#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.PACKAGE.functions.consumer.BI_OBJECT_CONSUMER;
import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
import speiger.src.collections.PACKAGE.utils.ARRAYS; import speiger.src.collections.PACKAGE.utils.ARRAYS;
/** /**
@@ -200,14 +204,14 @@ public class HEAP_PRIORITY_QUEUE KEY_GENERIC_TYPE implements PRIORITY_QUEUE KEY_
} }
@Override @Override
public void ENQUEUE(KEY_TYPE e) { public void enqueue(KEY_TYPE e) {
if(size == array.length) array = Arrays.copyOf(array, size + 1); if(size == array.length) array = Arrays.copyOf(array, size + 1);
array[size++] = e; array[size++] = e;
ARRAYS.shiftUp(array, size-1, comparator); ARRAYS.shiftUp(array, size-1, comparator);
} }
@Override @Override
public KEY_TYPE DEQUEUE() { public KEY_TYPE dequeue() {
if(size <= 0) throw new NoSuchElementException(); if(size <= 0) throw new NoSuchElementException();
KEY_TYPE value = array[0]; KEY_TYPE value = array[0];
array[0] = array[--size]; array[0] = array[--size];
@@ -219,25 +223,77 @@ 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_OBJECT_CONSUMER KKS_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
for(int i = 0,m=size;i<m;i++) action.accept(dequeue(), input);
}
@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;
}
@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;
}
protected boolean removeIndex(int index) { protected boolean removeIndex(int index) {
array[index] = array[--size]; array[index] = array[--size];
#if TYPE_OBJECT #if TYPE_OBJECT
@@ -259,21 +315,12 @@ public class HEAP_PRIORITY_QUEUE KEY_GENERIC_TYPE implements PRIORITY_QUEUE KEY_
} }
@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 +329,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();
} }
} }
} }
@@ -10,39 +10,16 @@ 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);
/** /**
* 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
* @param e the boxed element that should be inserted
*/
@Deprecated
public default void enqueueFirst(CLASS_TYPE e) { ENQUEUE_FIRST(OBJ_TO_KEY(e)); }
/**
* Boxed Method for the dequeue last method
* @return the last element of the Dequeue
* @throws java.util.NoSuchElementException if no element is in the dequeue
*
*/
@Deprecated
public default CLASS_TYPE dequeueLast() { return KEY_TO_OBJ(DEQUEUE_LAST()); }
/**
* Peeking function for the last element
* @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,18 @@ package speiger.src.collections.PACKAGE.queues;
#if TYPE_OBJECT #if TYPE_OBJECT
import java.util.Comparator; import java.util.Comparator;
import speiger.src.collections.objects.collections.ObjectIterator;
#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.ITERABLE;
/** /**
* 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,43 +28,42 @@ 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 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
@@ -79,42 +73,26 @@ public interface PRIORITY_QUEUE KEY_GENERIC_TYPE extends ObjectPriorityQueue<CLA
/** /**
* @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
/** /**
* 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
@Deprecated
public default void enqueue(CLASS_TYPE e) { ENQUEUE(OBJ_TO_KEY(e)); }
@Deprecated
public default CLASS_TYPE dequeue() { return KEY_TO_OBJ(DEQUEUE()); }
@Deprecated
public default CLASS_TYPE peek(int index) { return KEY_TO_OBJ(PEEK(index)); }
@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
} }
@@ -3,13 +3,18 @@ package speiger.src.collections.PACKAGE.sets;
import java.util.Collection; import java.util.Collection;
#if TYPE_OBJECT #if TYPE_OBJECT
import java.util.Comparator; import java.util.Comparator;
import java.util.function.Consumer;
#endif #endif
import java.util.Iterator; import java.util.Iterator;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import java.util.Objects;
import speiger.src.collections.PACKAGE.collections.BI_ITERATOR; import speiger.src.collections.PACKAGE.collections.BI_ITERATOR;
#if !TYPE_OBJECT #if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.functions.COMPARATOR; import speiger.src.collections.PACKAGE.functions.COMPARATOR;
import speiger.src.collections.PACKAGE.functions.CONSUMER;
#endif #endif
import speiger.src.collections.PACKAGE.functions.consumer.BI_OBJECT_CONSUMER;
import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
import speiger.src.collections.PACKAGE.collections.COLLECTION; import speiger.src.collections.PACKAGE.collections.COLLECTION;
import speiger.src.collections.PACKAGE.collections.ITERATOR; import speiger.src.collections.PACKAGE.collections.ITERATOR;
import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR; import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR;
@@ -115,7 +120,7 @@ public class AVL_TREE_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE
* A Helper constructor that allows to create a Set with exactly the same values as the provided collection. * A Helper constructor that allows to create a Set with exactly the same values as the provided collection.
* @param collection the set the elements should be added to the TreeSet * @param collection the set the elements should be added to the TreeSet
*/ */
@Deprecated @Primitive
public AVL_TREE_SET(Collection<? extends CLASS_TYPE> collection) { public AVL_TREE_SET(Collection<? extends CLASS_TYPE> collection) {
addAll(collection); addAll(collection);
} }
@@ -125,7 +130,7 @@ public class AVL_TREE_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE
* @param collection the set the elements should be added to the TreeSet * @param collection the set the elements should be added to the TreeSet
* @param comp the sorter of the tree, can be null * @param comp the sorter of the tree, can be null
*/ */
@Deprecated @Primitive
public AVL_TREE_SET(Collection<? extends CLASS_TYPE> collection, COMPARATOR KEY_GENERIC_TYPE comp) { public AVL_TREE_SET(Collection<? extends CLASS_TYPE> collection, COMPARATOR KEY_GENERIC_TYPE comp) {
comparator = comp; comparator = comp;
addAll(collection); addAll(collection);
@@ -290,6 +295,57 @@ public class AVL_TREE_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE
#endif #endif
} }
@Override
public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) {
Objects.requireNonNull(action);
for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) {
action.accept(entry.key);
}
}
@Override
public <E> void forEach(E input, BI_OBJECT_CONSUMER KKS_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next())
action.accept(entry.key, input);
}
@Override
public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) {
if(filter.TEST_VALUE(entry.key)) return true;
}
return false;
}
@Override
public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) {
if(filter.TEST_VALUE(entry.key)) return false;
}
return true;
}
@Override
public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) {
if(!filter.TEST_VALUE(entry.key)) return false;
}
return true;
}
@Override
public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) {
if(filter.TEST_VALUE(entry.key)) return entry.key;
}
return EMPTY_VALUE;
}
protected Entry KEY_GENERIC_TYPE findNode(KEY_TYPE o) { protected Entry KEY_GENERIC_TYPE findNode(KEY_TYPE o) {
Entry KEY_GENERIC_TYPE node = tree; Entry KEY_GENERIC_TYPE node = tree;
int compare; int compare;
@@ -514,11 +570,11 @@ public class AVL_TREE_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE
entry.key = successor.key; entry.key = successor.key;
entry = successor; entry = successor;
} }
if(entry.previous() == null) first = entry.next();
if(entry.next() == null) last = entry.previous();
Entry KEY_GENERIC_TYPE replacement = entry.left != null ? entry.left : entry.right; Entry KEY_GENERIC_TYPE replacement = entry.left != null ? entry.left : entry.right;
if(replacement != null) { if(replacement != null) {
if(entry.replace(replacement)) tree = replacement; if(entry.replace(replacement)) tree = replacement;
if(entry == first) first = replacement;
if(entry == last) last = entry.right != null ? entry.right : replacement;
entry.left = entry.right = entry.parent = null; entry.left = entry.right = entry.parent = null;
fixAfterDeletion(replacement); fixAfterDeletion(replacement);
} }
@@ -526,11 +582,6 @@ public class AVL_TREE_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE
else { else {
fixAfterDeletion(entry); fixAfterDeletion(entry);
entry.replace(null); entry.replace(null);
if(entry.parent != null) {
Entry KEY_GENERIC_TYPE parent = entry.parent;
if(entry == first) first = parent.left != null ? parent.left : parent;
if(entry == last) last = entry.right != null ? parent.right : parent;
}
entry.parent = null; entry.parent = null;
} }
} }
@@ -549,6 +600,8 @@ public class AVL_TREE_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE
else entry.parent.right = right; else entry.parent.right = right;
right.left = entry; right.left = entry;
entry.parent = right; entry.parent = right;
entry.updateHeight();
right.updateHeight();
} }
} }
@@ -564,6 +617,8 @@ public class AVL_TREE_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE
else entry.parent.left = left; else entry.parent.left = left;
left.right = entry; left.right = entry;
entry.parent = left; entry.parent = left;
entry.updateHeight();
left.updateHeight();
} }
} }
@@ -692,6 +747,9 @@ public class AVL_TREE_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE
return new DescendingSubSetBRACES(set, fromStart, start, loInclusive, false, fromElement, inclusive); return new DescendingSubSetBRACES(set, fromStart, start, loInclusive, false, fromElement, inclusive);
} }
protected Entry KEY_GENERIC_TYPE next(Entry KEY_GENERIC_TYPE entry) { return entry.previous(); }
protected Entry KEY_GENERIC_TYPE start() { return findHighest(); }
@Override @Override
public KEY_TYPE FIRST_KEY() { return super.LAST_KEY(); } public KEY_TYPE FIRST_KEY() { return super.LAST_KEY(); }
@@ -797,6 +855,8 @@ public class AVL_TREE_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE
boolean inRange(KEY_TYPE key) { return !tooLow(key) && !tooHigh(key); } boolean inRange(KEY_TYPE key) { return !tooLow(key) && !tooHigh(key); }
boolean inClosedRange(KEY_TYPE key) { return (fromStart || set.compare(key, start) >= 0) && (toEnd || set.compare(end, key) >= 0); } boolean inClosedRange(KEY_TYPE key) { return (fromStart || set.compare(key, start) >= 0) && (toEnd || set.compare(end, key) >= 0); }
boolean inRange(KEY_TYPE key, boolean inclusive) { return inclusive ? inRange(key) : inClosedRange(key); } boolean inRange(KEY_TYPE key, boolean inclusive) { return inclusive ? inRange(key) : inClosedRange(key); }
protected Entry KEY_GENERIC_TYPE next(Entry KEY_GENERIC_TYPE entry) { return entry.next(); }
protected Entry KEY_GENERIC_TYPE start() { return findLowest(); }
@Override @Override
public boolean addAndMoveToFirst(KEY_TYPE o) { throw new UnsupportedOperationException(); } public boolean addAndMoveToFirst(KEY_TYPE o) { throw new UnsupportedOperationException(); }
@@ -939,6 +999,57 @@ public class AVL_TREE_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE
return fromStart && toEnd ? set.size() : iterator().skip(Integer.MAX_VALUE); return fromStart && toEnd ? set.size() : iterator().skip(Integer.MAX_VALUE);
} }
@Override
public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) {
Objects.requireNonNull(action);
for(Entry KEY_GENERIC_TYPE entry = start();entry != null && inRange(entry.key);entry = next(entry)) {
action.accept(entry.key);
}
}
@Override
public <E> void forEach(E input, BI_OBJECT_CONSUMER KKS_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
for(Entry KEY_GENERIC_TYPE entry = start();entry != null && inRange(entry.key);entry = next(entry))
action.accept(entry.key, input);
}
@Override
public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(Entry KEY_GENERIC_TYPE entry = start();entry != null && inRange(entry.key);entry = next(entry)) {
if(filter.TEST_VALUE(entry.key)) return true;
}
return false;
}
@Override
public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(Entry KEY_GENERIC_TYPE entry = start();entry != null && inRange(entry.key);entry = next(entry)) {
if(filter.TEST_VALUE(entry.key)) return false;
}
return true;
}
@Override
public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(Entry KEY_GENERIC_TYPE entry = start();entry != null && inRange(entry.key);entry = next(entry)) {
if(!filter.TEST_VALUE(entry.key)) return false;
}
return true;
}
@Override
public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(Entry KEY_GENERIC_TYPE entry = start();entry != null && inRange(entry.key);entry = next(entry)) {
if(filter.TEST_VALUE(entry.key)) return entry.key;
}
return EMPTY_VALUE;
}
class SubSetIterator implements LIST_ITERATOR KEY_GENERIC_TYPE class SubSetIterator implements LIST_ITERATOR KEY_GENERIC_TYPE
{ {
Entry KEY_GENERIC_TYPE previous; Entry KEY_GENERIC_TYPE previous;
@@ -1094,6 +1205,7 @@ public class AVL_TREE_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE
if(current == previous) index--; if(current == previous) index--;
updateNext(); updateNext();
updatePrevious(); updatePrevious();
if(current.needsSuccessor()) next = current;
removeNode(current); removeNode(current);
current = null; current = null;
} }
@@ -1120,9 +1232,9 @@ public class AVL_TREE_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE
int getHeight() { return state; } int getHeight() { return state; }
void updateHeight() { state = (1 + Math.max(left == null ? 0 : left.getHeight(), right == null ? 0 : right.getHeight())); } void updateHeight() { state = (1 + Math.max(left == null ? -1 : left.getHeight(), right == null ? -1 : right.getHeight())); }
int getBalance() { return (left == null ? 0 : left.getHeight()) - (right == null ? 0 : right.getBalance()); } int getBalance() { return (left == null ? -1 : left.getHeight()) - (right == null ? -1 : right.getHeight()); }
boolean needsSuccessor() { return left != null && right != null; } boolean needsSuccessor() { return left != null && right != null; }
@@ -12,17 +12,21 @@ import java.util.Set;
#if PRIMITIVES #if PRIMITIVES
import java.util.function.JAVA_PREDICATE; import java.util.function.JAVA_PREDICATE;
#endif #endif
import speiger.src.collections.PACKAGE.collections.BI_ITERATOR; import speiger.src.collections.PACKAGE.collections.BI_ITERATOR;
import speiger.src.collections.PACKAGE.collections.COLLECTION; import speiger.src.collections.PACKAGE.collections.COLLECTION;
import speiger.src.collections.PACKAGE.collections.ITERATOR; import speiger.src.collections.PACKAGE.collections.ITERATOR;
import speiger.src.collections.PACKAGE.functions.consumer.BI_OBJECT_CONSUMER;
import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
#if !TYPE_OBJECT #if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.functions.COMPARATOR; import speiger.src.collections.PACKAGE.functions.COMPARATOR;
import speiger.src.collections.PACKAGE.functions.CONSUMER; import speiger.src.collections.PACKAGE.functions.CONSUMER;
import speiger.src.collections.objects.utils.ObjectArrays;
#endif #endif
import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR; import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR;
import speiger.src.collections.PACKAGE.utils.ARRAYS; import speiger.src.collections.PACKAGE.utils.ARRAYS;
/** /**
* A Type Specific ArraySet implementation. * A Type Specific ArraySet implementation.
* That is based around the idea of {@link java.util.List#indexOf(Object)} for no duplication. * That is based around the idea of {@link java.util.List#indexOf(Object)} for no duplication.
@@ -77,7 +81,7 @@ public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE im
* @param c the elements that should be added to the set. * @param c the elements that should be added to the set.
* @note this slowly checks every element to remove duplicates * @note this slowly checks every element to remove duplicates
*/ */
@Deprecated @Primitive
public ARRAY_SET(Collection<? extends CLASS_TYPE> c) { public ARRAY_SET(Collection<? extends CLASS_TYPE> c) {
this(c.size()); this(c.size());
addAll(c); addAll(c);
@@ -98,7 +102,7 @@ public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE im
* Since it is assumed that there is no duplication in the first place * Since it is assumed that there is no duplication in the first place
* @param s the set the element should be taken from * @param s the set the element should be taken from
*/ */
@Deprecated @Primitive
public ARRAY_SET(Set<? extends CLASS_TYPE> s) { public ARRAY_SET(Set<? extends CLASS_TYPE> s) {
this(s.size()); this(s.size());
for(CLASS_TYPE e : s) for(CLASS_TYPE e : s)
@@ -208,6 +212,68 @@ public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE im
return data[size - 1]; return data[size - 1];
} }
@Override
public boolean removeAll(COLLECTION KEY_GENERIC_TYPE c) {
int j = 0;
for(int i = 0;i<size;i++) {
if(!c.contains(data[i]))
data[j++] = data[i];
}
boolean result = j != size;
#if TYPE_OBJECT
Arrays.fill(data, j, size, null);
#endif
size = j;
return result;
}
@Override
public boolean retainAll(COLLECTION KEY_GENERIC_TYPE c) {
int j = 0;
for(int i = 0;i<size;i++) {
if(c.contains(data[i]))
data[j++] = data[i];
}
boolean result = j != size;
#if TYPE_OBJECT
Arrays.fill(data, j, size, null);
#endif
size = j;
return result;
}
@Override
@Primitive
public boolean removeAll(Collection<?> c) {
int j = 0;
for(int i = 0;i<size;i++) {
if(!c.contains(KEY_TO_OBJ(data[i])))
data[j++] = data[i];
}
boolean result = j != size;
#if TYPE_OBJECT
Arrays.fill(data, j, size, null);
#endif
size = j;
return result;
}
@Override
@Primitive
public boolean retainAll(Collection<?> c) {
int j = 0;
for(int i = 0;i<size;i++) {
if(c.contains(KEY_TO_OBJ(data[i])))
data[j++] = data[i];
}
boolean result = j != size;
#if TYPE_OBJECT
Arrays.fill(data, j, size, null);
#endif
size = j;
return result;
}
#if !TYPE_OBJECT #if !TYPE_OBJECT
@Override @Override
public boolean remove(KEY_TYPE o) { public boolean remove(KEY_TYPE o) {
@@ -277,21 +343,55 @@ public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE im
} }
#endif #endif
#if TYPE_OBJECT
@Override @Override
public void forEach(Consumer KEY_SUPER_GENERIC_TYPE action) { public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) {
Objects.requireNonNull(action); Objects.requireNonNull(action);
for(int i = 0;i<size;action.accept(data[i++])); for(int i = 0;i<size;action.accept(data[i++]));
} }
#else
@Override @Override
public void forEach(CONSUMER KEY_GENERIC_TYPE action) { public <E> void forEach(E input, BI_OBJECT_CONSUMER KKS_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action); Objects.requireNonNull(action);
for(int i = 0;i<size;action.accept(data[i++])); for(int i = 0;i<size;i++)
action.accept(data[i], input);
}
@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;
} }
#endif
#if !TYPE_OBJECT #if !TYPE_OBJECT
protected int findIndex(KEY_TYPE o) { protected int findIndex(KEY_TYPE o) {
for(int i = size-1;i>=0;i--) for(int i = size-1;i>=0;i--)
@@ -355,6 +455,34 @@ public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE im
return size; return size;
} }
#if !TYPE_OBJECT
@Override
public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] a) {
if(a == null || a.length < size()) return Arrays.copyOf(data, size());
System.arraycopy(data, 0, a, 0, size());
return a;
}
#endif
@Override
@Deprecated
public Object[] toArray() {
Object[] obj = new Object[size()];
for(int i = 0;i<size();i++)
obj[i] = KEY_TO_OBJ(data[i]);
return obj;
}
@Override
@Primitive
public <E> E[] toArray(E[] a) {
if(a == null) a = (E[])new Object[size()];
else if(a.length < size()) a = (E[])ObjectArrays.newArray(a.getClass().getComponentType(), size());
for(int i = 0;i<size();i++)
a[i] = (E)KEY_TO_OBJ(data[i]);
return a;
}
private class SubSet extends ABSTRACT_SET KEY_GENERIC_TYPE implements SORTED_SET KEY_GENERIC_TYPE { private class SubSet extends ABSTRACT_SET KEY_GENERIC_TYPE implements SORTED_SET KEY_GENERIC_TYPE {
int offset; int offset;
int length; int length;
@@ -543,14 +671,14 @@ public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE im
int fromIndex = findIndex(fromElement); int fromIndex = findIndex(fromElement);
int toIndex = findIndex(toElement); int toIndex = findIndex(toElement);
if(fromIndex == -1 || toIndex == -1) throw new NoSuchElementException(); if(fromIndex == -1 || toIndex == -1) throw new NoSuchElementException();
return new SubSet(fromIndex, toIndex - fromIndex); return new SubSet(fromIndex, toIndex - fromIndex + 1);
} }
@Override @Override
public SORTED_SET KEY_GENERIC_TYPE headSet(KEY_TYPE toElement) { public SORTED_SET KEY_GENERIC_TYPE headSet(KEY_TYPE toElement) {
int toIndex = findIndex(toElement); int toIndex = findIndex(toElement);
if(toIndex == -1) throw new NoSuchElementException(); if(toIndex == -1) throw new NoSuchElementException();
return new SubSet(0, toIndex); return new SubSet(0, toIndex+1);
} }
@Override @Override
@@ -565,6 +693,34 @@ public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE im
return length; return length;
} }
#if !TYPE_OBJECT
@Override
public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] a) {
if(a == null || a.length < size()) return Arrays.copyOfRange(data, offset, end());
System.arraycopy(data, offset, a, 0, size());
return a;
}
#endif
@Override
@Deprecated
public Object[] toArray() {
Object[] obj = new Object[size()];
for(int i = 0;i<size();i++)
obj[i] = KEY_TO_OBJ(data[offset+i]);
return obj;
}
@Override
@Primitive
public <E> E[] toArray(E[] a) {
if(a == null) a = (E[])new Object[size()];
else if(a.length < size()) a = (E[])ObjectArrays.newArray(a.getClass().getComponentType(), size());
for(int i = 0;i<size();i++)
a[i] = (E)KEY_TO_OBJ(data[offset+i]);
return a;
}
#if !TYPE_OBJECT #if !TYPE_OBJECT
protected int findIndex(KEY_TYPE o) { protected int findIndex(KEY_TYPE o) {
for(int i = length-1;i>=0;i--) for(int i = length-1;i>=0;i--)
@@ -0,0 +1,490 @@
package speiger.src.collections.PACKAGE.sets;
#if TYPE_OBJECT
import java.util.Comparator;
import java.util.function.Consumer;
#endif
import java.util.Collection;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Objects;
import speiger.src.collections.PACKAGE.collections.BI_ITERATOR;
import speiger.src.collections.PACKAGE.collections.COLLECTION;
import speiger.src.collections.PACKAGE.collections.ITERATOR;
#if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.functions.COMPARATOR;
import speiger.src.collections.PACKAGE.functions.CONSUMER;
#endif
import speiger.src.collections.PACKAGE.functions.consumer.BI_OBJECT_CONSUMER;
import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR;
import speiger.src.collections.PACKAGE.utils.ARRAYS;
import speiger.src.collections.PACKAGE.utils.ITERATORS;
import speiger.src.collections.utils.HashUtil;
import speiger.src.collections.utils.SanityChecks;
/**
* A Type Specific Custom implementation of the HashSet
* Instead of using Wrapper Object Arrays for storing keys and values there is dedicated arrays for storing keys.
* Extra to that there is a couple quality of life functions provided
* @Type(T)
*/
public class IMMUTABLE_HASH_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE implements SORTED_SET KEY_GENERIC_TYPE
{
/** The Backing keys array */
protected transient KEY_TYPE[] keys;
/** The Backing array for links between nodes. Left 32 Bits => Previous Entry, Right 32 Bits => Next Entry */
protected transient long[] links;
/** If a null value is present */
protected transient boolean containsNull;
/** Index of the Null Value */
protected transient int nullIndex;
/** Max Index that is allowed to be searched through nullIndex - 1 */
protected transient int mask;
/** Amount of Elements stored in the HashSet */
protected int size;
/** The First Index in the Map */
protected int firstIndex = -1;
/** The Last Index in the Map */
protected int lastIndex = -1;
/**
* Helper constructor 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++;
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 & mask)]))) {
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 = size;
mask = newMask;
keys = newKeys;
links = newLinks;
lastIndex = prev;
if(prev != -1) newLinks[prev] |= 0xFFFFFFFFL;
}
@Override
public boolean add(KEY_TYPE o) { throw new UnsupportedOperationException(); }
@Override
@Primitive
public boolean addAll(Collection<? extends CLASS_TYPE> c) { throw new UnsupportedOperationException(); }
@Override
public boolean addAll(COLLECTION KEY_GENERIC_TYPE c) { throw new UnsupportedOperationException(); }
@Override
public boolean addAndMoveToFirst(KEY_TYPE o) { throw new UnsupportedOperationException(); }
@Override
public boolean addAndMoveToLast(KEY_TYPE o) { throw new UnsupportedOperationException(); }
@Override
public boolean moveToFirst(KEY_TYPE o) { throw new UnsupportedOperationException(); }
@Override
public boolean moveToLast(KEY_TYPE o) { throw new UnsupportedOperationException(); }
@Override
public boolean contains(Object o) {
if(o == null) return containsNull;
int pos = HashUtil.mix(o.hashCode()) & mask;
KEY_TYPE current = keys[pos];
if(KEY_EQUALS_NULL(current)) return false;
if(EQUALS_KEY_TYPE(current, o)) return true;
while(true) {
if(KEY_EQUALS_NULL((current = keys[pos = (++pos & mask)]))) return false;
else if(EQUALS_KEY_TYPE(current, o)) return true;
}
}
@Override
public KEY_TYPE FIRST_KEY() {
if(size == 0) throw new NoSuchElementException();
return keys[firstIndex];
}
@Override
public KEY_TYPE POLL_FIRST_KEY() { throw new UnsupportedOperationException(); }
@Override
public KEY_TYPE LAST_KEY() {
if(size == 0) throw new NoSuchElementException();
return keys[lastIndex];
}
@Override
public KEY_TYPE POLL_LAST_KEY() { throw new UnsupportedOperationException(); }
@Override
public boolean remove(Object o) { throw new UnsupportedOperationException(); }
#if !TYPE_OBJECT
@Override
public boolean contains(KEY_TYPE o) {
if(KEY_EQUALS_NULL(o)) return containsNull;
int pos = HashUtil.mix(KEY_TO_HASH(o)) & mask;
KEY_TYPE current = keys[pos];
if(KEY_EQUALS_NULL(current)) return false;
if(KEY_EQUALS(current, o)) return true;
while(true) {
if(KEY_EQUALS_NULL((current = keys[pos = (++pos & mask)]))) return false;
else if(KEY_EQUALS(current, o)) return true;
}
}
@Override
public boolean remove(KEY_TYPE o) { throw new UnsupportedOperationException(); }
#endif
@Override
public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) {
Objects.requireNonNull(action);
int index = firstIndex;
while(index != -1) {
action.accept(keys[index]);
index = (int)links[index];
}
}
@Override
public <E> void forEach(E input, BI_OBJECT_CONSUMER KKS_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
int index = firstIndex;
while(index != -1) {
action.accept(keys[index], input);
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;
}
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;
}
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;
}
return true;
}
@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];
}
return EMPTY_VALUE;
}
@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 COMPARATOR KEY_GENERIC_TYPE comparator() { return null; }
@Override
public SORTED_SET KEY_GENERIC_TYPE subSet(KEY_TYPE fromElement, KEY_TYPE toElement) { throw new UnsupportedOperationException(); }
@Override
public SORTED_SET KEY_GENERIC_TYPE headSet(KEY_TYPE toElement) { throw new UnsupportedOperationException(); }
@Override
public SORTED_SET KEY_GENERIC_TYPE tailSet(KEY_TYPE fromElement) { throw new UnsupportedOperationException(); }
@Override
public void clear() { throw new UnsupportedOperationException(); }
@Override
public int size() {
return size;
}
private class SetIterator implements LIST_ITERATOR KEY_GENERIC_TYPE {
int previous = -1;
int next = -1;
int current = -1;
int index = 0;
SetIterator() {
next = firstIndex;
}
SetIterator(KEY_TYPE from) {
if(KEY_EQUALS_NULL(from)) {
if(containsNull) {
next = (int) links[nullIndex];
previous = nullIndex;
}
else throw new NoSuchElementException("The null element is not in the set");
}
else if(KEY_EQUALS(keys[lastIndex], from)) {
previous = lastIndex;
index = size;
}
else {
int pos = HashUtil.mix(KEY_TO_HASH(from)) & mask;
while(KEY_EQUALS_NOT_NULL(keys[pos])) {
if(KEY_EQUALS(keys[pos], from)) {
next = (int)links[pos];
previous = pos;
break;
}
pos = ++pos & mask;
}
if(previous == -1 && next == -1)
throw new NoSuchElementException("The element was not found");
}
}
@Override
public boolean hasNext() {
return next != -1;
}
@Override
public boolean hasPrevious() {
return previous != -1;
}
@Override
public int nextIndex() {
ensureIndexKnown();
return index;
}
@Override
public int previousIndex() {
ensureIndexKnown();
return index - 1;
}
@Override
public void remove() { throw new UnsupportedOperationException(); }
@Override
public KEY_TYPE PREVIOUS() {
if(!hasPrevious()) throw new NoSuchElementException();
current = previous;
previous = (int)(links[current] >> 32);
next = current;
if(index >= 0) index--;
return keys[current];
}
@Override
public KEY_TYPE NEXT() {
if(!hasNext()) throw new NoSuchElementException();
current = next;
next = (int)(links[current]);
previous = current;
if(index >= 0) index++;
return keys[current];
}
private void ensureIndexKnown() {
if(index == -1) {
if(previous == -1) {
index = 0;
}
else if(next == -1) {
index = size;
}
else {
index = 1;
for(int pos = firstIndex;pos != previous;pos = (int)links[pos], index++);
}
}
}
#if TYPE_OBJECT
@Override
public void set(Object e) { throw new UnsupportedOperationException(); }
@Override
public void add(Object e) { throw new UnsupportedOperationException(); }
#else
@Override
public void set(KEY_TYPE e) { throw new UnsupportedOperationException(); }
@Override
public void add(KEY_TYPE e) { throw new UnsupportedOperationException(); }
#endif
}
}
@@ -2,7 +2,9 @@ package speiger.src.collections.PACKAGE.sets;
#if TYPE_OBJECT #if TYPE_OBJECT
import java.util.Comparator; import java.util.Comparator;
import java.util.function.Consumer;
#endif #endif
import java.util.Objects;
import java.util.Collection; import java.util.Collection;
import java.util.Iterator; import java.util.Iterator;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
@@ -18,7 +20,10 @@ import speiger.src.collections.PACKAGE.functions.COMPARATOR;
import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR; import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR;
#if !TYPE_OBJECT #if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.utils.ITERATORS; import speiger.src.collections.PACKAGE.utils.ITERATORS;
import speiger.src.collections.PACKAGE.functions.CONSUMER;
#endif #endif
import speiger.src.collections.PACKAGE.functions.consumer.BI_OBJECT_CONSUMER;
import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
import speiger.src.collections.PACKAGE.utils.STRATEGY; import speiger.src.collections.PACKAGE.utils.STRATEGY;
import speiger.src.collections.utils.HashUtil; import speiger.src.collections.utils.HashUtil;
import speiger.src.collections.utils.SanityChecks; import speiger.src.collections.utils.SanityChecks;
@@ -130,7 +135,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 +148,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 +429,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 +506,83 @@ 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_OBJECT_CONSUMER KKS_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
int index = firstIndex;
while(index != -1) {
action.accept(keys[index], input);
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;
}
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;
}
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;
}
return true;
}
@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];
}
return EMPTY_VALUE;
}
@Override @Override
public LIST_ITERATOR KEY_GENERIC_TYPE iterator() { public LIST_ITERATOR KEY_GENERIC_TYPE iterator() {
return new SetIterator(); return new SetIterator();
@@ -6,8 +6,9 @@ import java.util.Comparator;
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;
#endif #endif
import speiger.src.collections.PACKAGE.collections.COLLECTION; import speiger.src.collections.PACKAGE.collections.COLLECTION;
@@ -17,7 +18,10 @@ import speiger.src.collections.PACKAGE.collections.ITERATOR;
import speiger.src.collections.PACKAGE.collections.BI_ITERATOR; import speiger.src.collections.PACKAGE.collections.BI_ITERATOR;
#if !TYPE_OBJECT #if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.functions.COMPARATOR; import speiger.src.collections.PACKAGE.functions.COMPARATOR;
import speiger.src.collections.PACKAGE.functions.CONSUMER;
#endif #endif
import speiger.src.collections.PACKAGE.functions.consumer.BI_OBJECT_CONSUMER;
import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR; import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR;
#if !TYPE_OBJECT #if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.utils.ITERATORS; import speiger.src.collections.PACKAGE.utils.ITERATORS;
@@ -116,7 +120,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 +131,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 +378,66 @@ 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_OBJECT_CONSUMER KKS_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
int index = firstIndex;
while(index != -1) {
action.accept(keys[index], input);
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;
}
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;
}
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;
}
return true;
}
@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];
}
return EMPTY_VALUE;
}
@Override @Override
protected void onNodeAdded(int pos) { protected void onNodeAdded(int pos) {
if(size == 0) { if(size == 0) {
@@ -396,7 +460,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 +537,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();
@@ -4,6 +4,10 @@ import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.Iterator; import java.util.Iterator;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import java.util.Objects;
#if TYPE_OBJECT
import java.util.function.Consumer;
#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 +15,10 @@ 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.PACKAGE.functions.consumer.BI_OBJECT_CONSUMER;
import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
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 +150,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 +163,7 @@ public class CUSTOM_HASH_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_T
* @throws NullPointerException if Strategy is null * @throws NullPointerException if Strategy is null
* @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1
*/ */
@Deprecated @Primitive
public CUSTOM_HASH_SET(Collection<? extends CLASS_TYPE> collection, float loadFactor, STRATEGY KEY_SUPER_GENERIC_TYPE strategy) { public CUSTOM_HASH_SET(Collection<? extends CLASS_TYPE> collection, float loadFactor, STRATEGY KEY_SUPER_GENERIC_TYPE strategy) {
this(collection.size(), loadFactor, strategy); this(collection.size(), loadFactor, strategy);
addAll(collection); addAll(collection);
@@ -268,7 +275,7 @@ public class CUSTOM_HASH_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_T
} }
@Override @Override
@Deprecated @Primitive
public boolean addAll(Collection<? extends CLASS_TYPE> c) { public boolean addAll(Collection<? extends CLASS_TYPE> c) {
if(loadFactor <= 0.5F) ensureCapacity(c.size()); if(loadFactor <= 0.5F) ensureCapacity(c.size());
else ensureCapacity(c.size() + size()); else ensureCapacity(c.size() + size());
@@ -348,12 +355,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);
@@ -434,6 +458,69 @@ 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_OBJECT_CONSUMER KKS_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
if(size() <= 0) return;
if(containsNull) action.accept(keys[nullIndex], input);
for(int i = nullIndex-1;i>=0;i--) {
if(!strategy.equals(keys[i], EMPTY_KEY_VALUE)) action.accept(keys[i], input);
}
}
@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;
}
@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;
}
private class SetIterator implements ITERATOR KEY_GENERIC_TYPE { private class SetIterator implements ITERATOR KEY_GENERIC_TYPE {
int pos = nullIndex; int pos = nullIndex;
int lastReturned = -1; int lastReturned = -1;
@@ -5,6 +5,9 @@ import java.util.Collection;
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;
#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 +15,10 @@ 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.PACKAGE.functions.consumer.BI_OBJECT_CONSUMER;
import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
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 +130,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 +141,7 @@ public class HASH_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE imp
* @param loadFactor the percentage of how full the backing array can be before they resize * @param loadFactor the percentage of how full the backing array can be before they resize
* @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1 * @throws IllegalStateException if the loadfactor is either below/equal to 0 or above/equal to 1
*/ */
@Deprecated @Primitive
public HASH_SET(Collection<? extends CLASS_TYPE> collection, float loadFactor) { public HASH_SET(Collection<? extends CLASS_TYPE> collection, float loadFactor) {
this(collection.size(), loadFactor); this(collection.size(), loadFactor);
addAll(collection); addAll(collection);
@@ -227,7 +233,7 @@ public class HASH_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE imp
} }
@Override @Override
@Deprecated @Primitive
public boolean addAll(Collection<? extends CLASS_TYPE> c) { public boolean addAll(Collection<? extends CLASS_TYPE> c) {
if(loadFactor <= 0.5F) ensureCapacity(c.size()); if(loadFactor <= 0.5F) ensureCapacity(c.size());
else ensureCapacity(c.size() + size()); else ensureCapacity(c.size() + size());
@@ -283,7 +289,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 +312,92 @@ 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_OBJECT_CONSUMER KKS_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
if(size() <= 0) return;
if(containsNull) action.accept(keys[nullIndex], input);
for(int i = nullIndex-1;i>=0;i--) {
if(KEY_EQUALS_NOT_NULL(keys[i])) action.accept(keys[i], input);
}
}
@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;
}
@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;
}
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);
@@ -3,13 +3,18 @@ package speiger.src.collections.PACKAGE.sets;
import java.util.Collection; import java.util.Collection;
#if TYPE_OBJECT #if TYPE_OBJECT
import java.util.Comparator; import java.util.Comparator;
import java.util.function.Consumer;
#endif #endif
import java.util.Iterator; import java.util.Iterator;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import java.util.Objects;
import speiger.src.collections.PACKAGE.collections.BI_ITERATOR; import speiger.src.collections.PACKAGE.collections.BI_ITERATOR;
#if !TYPE_OBJECT #if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.functions.COMPARATOR; import speiger.src.collections.PACKAGE.functions.COMPARATOR;
import speiger.src.collections.PACKAGE.functions.CONSUMER;
#endif #endif
import speiger.src.collections.PACKAGE.functions.consumer.BI_OBJECT_CONSUMER;
import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
import speiger.src.collections.PACKAGE.collections.COLLECTION; import speiger.src.collections.PACKAGE.collections.COLLECTION;
import speiger.src.collections.PACKAGE.collections.ITERATOR; import speiger.src.collections.PACKAGE.collections.ITERATOR;
import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR; import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR;
@@ -115,7 +120,7 @@ public class RB_TREE_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE
* A Helper constructor that allows to create a Set with exactly the same values as the provided collection. * A Helper constructor that allows to create a Set with exactly the same values as the provided collection.
* @param collection the set the elements should be added to the TreeSet * @param collection the set the elements should be added to the TreeSet
*/ */
@Deprecated @Primitive
public RB_TREE_SET(Collection<? extends CLASS_TYPE> collection) { public RB_TREE_SET(Collection<? extends CLASS_TYPE> collection) {
addAll(collection); addAll(collection);
} }
@@ -125,7 +130,7 @@ public class RB_TREE_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE
* @param collection the set the elements should be added to the TreeSet * @param collection the set the elements should be added to the TreeSet
* @param comp the sorter of the tree, can be null * @param comp the sorter of the tree, can be null
*/ */
@Deprecated @Primitive
public RB_TREE_SET(Collection<? extends CLASS_TYPE> collection, COMPARATOR KEY_GENERIC_TYPE comp) { public RB_TREE_SET(Collection<? extends CLASS_TYPE> collection, COMPARATOR KEY_GENERIC_TYPE comp) {
comparator = comp; comparator = comp;
addAll(collection); addAll(collection);
@@ -290,6 +295,57 @@ public class RB_TREE_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE
#endif #endif
} }
@Override
public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) {
Objects.requireNonNull(action);
for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) {
action.accept(entry.key);
}
}
@Override
public <E> void forEach(E input, BI_OBJECT_CONSUMER KKS_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next())
action.accept(entry.key, input);
}
@Override
public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) {
if(filter.TEST_VALUE(entry.key)) return true;
}
return false;
}
@Override
public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) {
if(filter.TEST_VALUE(entry.key)) return false;
}
return true;
}
@Override
public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) {
if(!filter.TEST_VALUE(entry.key)) return false;
}
return true;
}
@Override
public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(Entry KEY_GENERIC_TYPE entry = first;entry != null;entry = entry.next()) {
if(filter.TEST_VALUE(entry.key)) return entry.key;
}
return EMPTY_VALUE;
}
protected Entry KEY_GENERIC_TYPE findNode(KEY_TYPE o) { protected Entry KEY_GENERIC_TYPE findNode(KEY_TYPE o) {
Entry KEY_GENERIC_TYPE node = tree; Entry KEY_GENERIC_TYPE node = tree;
int compare; int compare;
@@ -752,6 +808,9 @@ public class RB_TREE_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE
return new DescendingSubSetBRACES(set, fromStart, start, loInclusive, false, fromElement, inclusive); return new DescendingSubSetBRACES(set, fromStart, start, loInclusive, false, fromElement, inclusive);
} }
protected Entry KEY_GENERIC_TYPE next(Entry KEY_GENERIC_TYPE entry) { return entry.previous(); }
protected Entry KEY_GENERIC_TYPE start() { return findHighest(); }
@Override @Override
public KEY_TYPE FIRST_KEY() { return super.LAST_KEY(); } public KEY_TYPE FIRST_KEY() { return super.LAST_KEY(); }
@@ -857,6 +916,8 @@ public class RB_TREE_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE
boolean inRange(KEY_TYPE key) { return !tooLow(key) && !tooHigh(key); } boolean inRange(KEY_TYPE key) { return !tooLow(key) && !tooHigh(key); }
boolean inClosedRange(KEY_TYPE key) { return (fromStart || set.compare(key, start) >= 0) && (toEnd || set.compare(end, key) >= 0); } boolean inClosedRange(KEY_TYPE key) { return (fromStart || set.compare(key, start) >= 0) && (toEnd || set.compare(end, key) >= 0); }
boolean inRange(KEY_TYPE key, boolean inclusive) { return inclusive ? inRange(key) : inClosedRange(key); } boolean inRange(KEY_TYPE key, boolean inclusive) { return inclusive ? inRange(key) : inClosedRange(key); }
protected Entry KEY_GENERIC_TYPE next(Entry KEY_GENERIC_TYPE entry) { return entry.next(); }
protected Entry KEY_GENERIC_TYPE start() { return findLowest(); }
@Override @Override
public boolean addAndMoveToFirst(KEY_TYPE o) { throw new UnsupportedOperationException(); } public boolean addAndMoveToFirst(KEY_TYPE o) { throw new UnsupportedOperationException(); }
@@ -999,6 +1060,57 @@ public class RB_TREE_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE
return fromStart && toEnd ? set.size() : iterator().skip(Integer.MAX_VALUE); return fromStart && toEnd ? set.size() : iterator().skip(Integer.MAX_VALUE);
} }
@Override
public void forEach(CONSUMER KEY_SUPER_GENERIC_TYPE action) {
Objects.requireNonNull(action);
for(Entry KEY_GENERIC_TYPE entry = start();entry != null && inRange(entry.key);entry = next(entry)) {
action.accept(entry.key);
}
}
@Override
public <E> void forEach(E input, BI_OBJECT_CONSUMER KKS_GENERIC_TYPE<E> action) {
Objects.requireNonNull(action);
for(Entry KEY_GENERIC_TYPE entry = start();entry != null && inRange(entry.key);entry = next(entry))
action.accept(entry.key, input);
}
@Override
public boolean matchesAny(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(Entry KEY_GENERIC_TYPE entry = start();entry != null && inRange(entry.key);entry = next(entry)) {
if(filter.TEST_VALUE(entry.key)) return true;
}
return false;
}
@Override
public boolean matchesNone(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(Entry KEY_GENERIC_TYPE entry = start();entry != null && inRange(entry.key);entry = next(entry)) {
if(filter.TEST_VALUE(entry.key)) return false;
}
return true;
}
@Override
public boolean matchesAll(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(Entry KEY_GENERIC_TYPE entry = start();entry != null && inRange(entry.key);entry = next(entry)) {
if(!filter.TEST_VALUE(entry.key)) return false;
}
return true;
}
@Override
public KEY_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) {
Objects.requireNonNull(filter);
for(Entry KEY_GENERIC_TYPE entry = start();entry != null && inRange(entry.key);entry = next(entry)) {
if(filter.TEST_VALUE(entry.key)) return entry.key;
}
return EMPTY_VALUE;
}
class SubSetIterator implements LIST_ITERATOR KEY_GENERIC_TYPE class SubSetIterator implements LIST_ITERATOR KEY_GENERIC_TYPE
{ {
Entry KEY_GENERIC_TYPE previous; Entry KEY_GENERIC_TYPE previous;
@@ -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;
@@ -5,12 +5,14 @@ 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
@@ -29,7 +31,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 +45,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 +55,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 +66,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);
} }
@@ -151,23 +153,32 @@ public class COLLECTIONS
#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(); } }
} }
/** /**
@@ -187,57 +198,29 @@ 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(); }
#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 @Override
@Deprecated @Deprecated
public boolean remove(Object o) { throw new UnsupportedOperationException(); } public boolean remove(Object o) { throw new UnsupportedOperationException(); }
@@ -264,35 +247,32 @@ public class COLLECTIONS
#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(); }
} }
/** /**
@@ -308,43 +288,23 @@ public class COLLECTIONS
#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 +337,24 @@ 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;
}
} }
} }
@@ -0,0 +1,127 @@
package speiger.src.collections.PACKAGE.utils;
import speiger.src.collections.PACKAGE.collections.ITERABLE;
#if !TYPE_OBJECT
import speiger.src.collections.objects.collections.ObjectIterable;
import speiger.src.collections.objects.collections.ObjectIterator;
#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;
/**
* A Helper class for Iterables
*/
public class ITERABLES
{
/**
* 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 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 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
* @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);
}
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);
}
}
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);
}
}
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);
}
}
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);
}
}
}
@@ -1,9 +1,20 @@
package speiger.src.collections.PACKAGE.utils; package speiger.src.collections.PACKAGE.utils;
import java.util.Iterator; import java.util.Iterator;
import java.util.NoSuchElementException;
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;
#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;
/** /**
* A Helper class for Iterators * A Helper class for Iterators
@@ -20,7 +31,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 +61,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 +71,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 +81,72 @@ 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 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 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 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
* @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);
}
/** /**
* 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 +299,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 +390,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 +652,139 @@ 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 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;
}
}
} }
@@ -2,6 +2,7 @@ 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;
@@ -12,6 +13,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 +31,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 +41,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 +55,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 +66,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 +76,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;
@@ -146,6 +238,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(); } }
@@ -272,7 +367,7 @@ 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 synchronize(l.subList(from, to));
} }
@Override @Override
@@ -381,7 +476,7 @@ 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 unmodifiable(l.subList(from, to));
} }
@Override @Override
@@ -453,14 +548,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
@@ -0,0 +1,127 @@
package speiger.src.collections.PACKAGE.utils;
#if TYPE_OBJECT
import java.util.Comparator;
#endif
import speiger.src.collections.PACKAGE.collections.ITERATOR;
#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;
/**
* 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 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); } }
}
/**
* 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 KEY_TYPE dequeueLast() { synchronized(mutex) { return dequeue.dequeueLast(); } }
}
}
@@ -56,7 +56,7 @@ public class SETS
* @return a set that is synchronized * @return a set that is synchronized
* @note if the set is already synchronized then it will just self return it * @note if the set is already synchronized then it will just self return it
*/ */
public static GENERIC_KEY_BRACES SET KEY_GENERIC_TYPE synchronizedSet(SET KEY_GENERIC_TYPE s) { public static GENERIC_KEY_BRACES SET KEY_GENERIC_TYPE synchronize(SET KEY_GENERIC_TYPE s) {
return s instanceof SynchronizedSet ? s : (s instanceof ITrimmable ? new SynchronizedTrimSetBRACES(s) : new SynchronizedSetBRACES(s)); return s instanceof SynchronizedSet ? s : (s instanceof ITrimmable ? new SynchronizedTrimSetBRACES(s) : new SynchronizedSetBRACES(s));
} }
@@ -68,7 +68,7 @@ public class SETS
* @return a set that is synchronized * @return a set that is synchronized
* @note if the set is already synchronized then it will just self return it * @note if the set is already synchronized then it will just self return it
*/ */
public static GENERIC_KEY_BRACES SET KEY_GENERIC_TYPE synchronizedSet(SET KEY_GENERIC_TYPE s, Object mutex) { public static GENERIC_KEY_BRACES SET KEY_GENERIC_TYPE synchronize(SET KEY_GENERIC_TYPE s, Object mutex) {
return s instanceof SynchronizedSet ? s : (s instanceof ITrimmable ? new SynchronizedTrimSetBRACES(s, mutex) : new SynchronizedSetBRACES(s, mutex)); return s instanceof SynchronizedSet ? s : (s instanceof ITrimmable ? new SynchronizedTrimSetBRACES(s, mutex) : new SynchronizedSetBRACES(s, mutex));
} }
@@ -79,7 +79,7 @@ public class SETS
* @return a SortedSet that is synchronized * @return a SortedSet that is synchronized
* @note if the set is already synchronized then it will just self return it * @note if the set is already synchronized then it will just self return it
*/ */
public static GENERIC_KEY_BRACES SORTED_SET KEY_GENERIC_TYPE synchronizedSet(SORTED_SET KEY_GENERIC_TYPE s) { public static GENERIC_KEY_BRACES SORTED_SET KEY_GENERIC_TYPE synchronize(SORTED_SET KEY_GENERIC_TYPE s) {
return s instanceof SynchronizedSortedSet ? s : (s instanceof ITrimmable ? new SynchronizedSortedTrimSetBRACES(s) : new SynchronizedSortedSetBRACES(s)); return s instanceof SynchronizedSortedSet ? s : (s instanceof ITrimmable ? new SynchronizedSortedTrimSetBRACES(s) : new SynchronizedSortedSetBRACES(s));
} }
@@ -91,7 +91,7 @@ public class SETS
* @return a SortedSet that is synchronized * @return a SortedSet that is synchronized
* @note if the set is already synchronized then it will just self return it * @note if the set is already synchronized then it will just self return it
*/ */
public static GENERIC_KEY_BRACES SORTED_SET KEY_GENERIC_TYPE synchronizedSet(SORTED_SET KEY_GENERIC_TYPE s, Object mutex) { public static GENERIC_KEY_BRACES SORTED_SET KEY_GENERIC_TYPE synchronize(SORTED_SET KEY_GENERIC_TYPE s, Object mutex) {
return s instanceof SynchronizedSortedSet ? s : (s instanceof ITrimmable ? new SynchronizedSortedTrimSetBRACES(s, mutex) : new SynchronizedSortedSetBRACES(s, mutex)); return s instanceof SynchronizedSortedSet ? s : (s instanceof ITrimmable ? new SynchronizedSortedTrimSetBRACES(s, mutex) : new SynchronizedSortedSetBRACES(s, mutex));
} }
@@ -102,7 +102,7 @@ public class SETS
* @return a NavigableSet that is synchronized * @return a NavigableSet that is synchronized
* @note if the set is already synchronized then it will just self return it * @note if the set is already synchronized then it will just self return it
*/ */
public static GENERIC_KEY_BRACES NAVIGABLE_SET KEY_GENERIC_TYPE synchronizedSet(NAVIGABLE_SET KEY_GENERIC_TYPE s) { public static GENERIC_KEY_BRACES NAVIGABLE_SET KEY_GENERIC_TYPE synchronize(NAVIGABLE_SET KEY_GENERIC_TYPE s) {
return s instanceof SynchronizedNavigableSet ? s : (s instanceof ITrimmable ? new SynchronizedNavigableTrimSetBRACES(s) : new SynchronizedNavigableSetBRACES(s)); return s instanceof SynchronizedNavigableSet ? s : (s instanceof ITrimmable ? new SynchronizedNavigableTrimSetBRACES(s) : new SynchronizedNavigableSetBRACES(s));
} }
@@ -114,15 +114,15 @@ public class SETS
* @return a NavigableSet that is synchronized * @return a NavigableSet that is synchronized
* @note if the set is already synchronized then it will just self return it * @note if the set is already synchronized then it will just self return it
*/ */
public static GENERIC_KEY_BRACES NAVIGABLE_SET KEY_GENERIC_TYPE synchronizedSet(NAVIGABLE_SET KEY_GENERIC_TYPE s, Object mutex) { public static GENERIC_KEY_BRACES NAVIGABLE_SET KEY_GENERIC_TYPE synchronize(NAVIGABLE_SET KEY_GENERIC_TYPE s, Object mutex) {
return s instanceof SynchronizedNavigableSet ? s : (s instanceof ITrimmable ? new SynchronizedNavigableTrimSetBRACES(s, mutex) : new SynchronizedNavigableSetBRACES(s, mutex)); return s instanceof SynchronizedNavigableSet ? s : (s instanceof ITrimmable ? new SynchronizedNavigableTrimSetBRACES(s, mutex) : new SynchronizedNavigableSetBRACES(s, mutex));
} }
/** /**
* Creates Unmodifyable Set wrapper * Creates Unmodifyable Set wrapper
* @param s set that should be made unmodifyable * @param s set that should be made unmodifiable
* @Type(T) * @Type(T)
* @return a UnmodifyableSet, if the set is already unmodifyable then it returns itself * @return a UnmodifyableSet, if the set is already unmodifiable then it returns itself
*/ */
public static GENERIC_KEY_BRACES SET KEY_GENERIC_TYPE unmodifiable(SET KEY_GENERIC_TYPE s) { public static GENERIC_KEY_BRACES SET KEY_GENERIC_TYPE unmodifiable(SET KEY_GENERIC_TYPE s) {
return s instanceof UnmodifiableSet ? s : new UnmodifiableSetBRACES(s); return s instanceof UnmodifiableSet ? s : new UnmodifiableSetBRACES(s);
@@ -130,9 +130,9 @@ public class SETS
/** /**
* Creates Unmodifyable SortedSet wrapper * Creates Unmodifyable SortedSet wrapper
* @param s sortedSet that should be made unmodifyable * @param s sortedSet that should be made unmodifiable
* @Type(T) * @Type(T)
* @return a UnmodifyableSortedSet, if the set is already unmodifyable then it returns itself * @return a UnmodifyableSortedSet, if the set is already unmodifiable then it returns itself
*/ */
public static GENERIC_KEY_BRACES SORTED_SET KEY_GENERIC_TYPE unmodifiable(SORTED_SET KEY_GENERIC_TYPE s) { public static GENERIC_KEY_BRACES SORTED_SET KEY_GENERIC_TYPE unmodifiable(SORTED_SET KEY_GENERIC_TYPE s) {
return s instanceof UnmodifiableSortedSet ? s : new UnmodifiableSortedSetBRACES(s); return s instanceof UnmodifiableSortedSet ? s : new UnmodifiableSortedSetBRACES(s);
@@ -140,9 +140,9 @@ public class SETS
/** /**
* Creates Unmodifyable NavigableSet wrapper * Creates Unmodifyable NavigableSet wrapper
* @param s navigableSet that should be made unmodifyable * @param s navigableSet that should be made unmodifiable
* @Type(T) * @Type(T)
* @return a UnmodifyableNavigableSet, if the set is already unmodifyable then it returns itself * @return a UnmodifyableNavigableSet, if the set is already unmodifiable then it returns itself
*/ */
public static GENERIC_KEY_BRACES NAVIGABLE_SET KEY_GENERIC_TYPE unmodifiable(NAVIGABLE_SET KEY_GENERIC_TYPE s) { public static GENERIC_KEY_BRACES NAVIGABLE_SET KEY_GENERIC_TYPE unmodifiable(NAVIGABLE_SET KEY_GENERIC_TYPE s) {
return s instanceof UnmodifiableNavigableSet ? s : new UnmodifiableNavigableSetBRACES(s); return s instanceof UnmodifiableNavigableSet ? s : new UnmodifiableNavigableSetBRACES(s);
@@ -155,7 +155,7 @@ public class SETS
* @Type(T) * @Type(T)
* @return a singletonset of the given element * @return a singletonset of the given element
*/ */
public static GENERIC_KEY_BRACES SET KEY_GENERIC_TYPE singletonSet(KEY_TYPE element) { public static GENERIC_KEY_BRACES SET KEY_GENERIC_TYPE singleton(KEY_TYPE element) {
return new SingletonSetBRACES(element); return new SingletonSetBRACES(element);
} }
@@ -358,6 +358,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 +413,28 @@ 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 subSet(KEY_TYPE fromElement, boolean fromInclusive, KEY_TYPE toElement, boolean toInclusive) { synchronized(mutex) { return synchronize(n.subSet(fromElement, fromInclusive, toElement, toInclusive), mutex); } }
@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 headSet(KEY_TYPE toElement, boolean inclusive) { synchronized(mutex) { return synchronize(n.headSet(toElement, inclusive), 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 tailSet(KEY_TYPE fromElement, boolean inclusive) { synchronized(mutex) { return 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 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 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 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 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 +453,9 @@ public class SETS
@Override @Override
public boolean trim(int size) { synchronized(mutex) { return trim.trim(size); } } public boolean trim(int size) { synchronized(mutex) { return trim.trim(size); } }
@Override
public void clearAndTrim(int size) { synchronized(mutex) { trim.clearAndTrim(size); } }
} }
private static class SynchronizedSortedSet KEY_GENERIC_TYPE extends SynchronizedSet KEY_GENERIC_TYPE implements SORTED_SET KEY_GENERIC_TYPE private static class SynchronizedSortedSet KEY_GENERIC_TYPE extends SynchronizedSet KEY_GENERIC_TYPE implements SORTED_SET KEY_GENERIC_TYPE
@@ -488,13 +494,13 @@ public class SETS
public BI_ITERATOR KEY_GENERIC_TYPE iterator(KEY_TYPE fromElement) { synchronized(mutex) { return s.iterator(fromElement); } } public BI_ITERATOR KEY_GENERIC_TYPE iterator(KEY_TYPE fromElement) { synchronized(mutex) { return s.iterator(fromElement); } }
@Override @Override
public SORTED_SET KEY_GENERIC_TYPE subSet(KEY_TYPE fromElement, KEY_TYPE toElement) { synchronized(mutex) { return synchronizedSet(s.subSet(fromElement, toElement), mutex); } } public SORTED_SET KEY_GENERIC_TYPE subSet(KEY_TYPE fromElement, KEY_TYPE toElement) { synchronized(mutex) { return synchronize(s.subSet(fromElement, toElement), mutex); } }
@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 headSet(KEY_TYPE toElement) { synchronized(mutex) { return synchronize(s.headSet(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 tailSet(KEY_TYPE fromElement) { synchronized(mutex) { return synchronize(s.tailSet(fromElement), mutex); } }
@Override @Override
public KEY_TYPE FIRST_KEY() { synchronized(mutex) { return s.FIRST_KEY(); } } public KEY_TYPE FIRST_KEY() { synchronized(mutex) { return s.FIRST_KEY(); } }
@@ -525,6 +531,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 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
@@ -6,6 +6,19 @@ package speiger.src.collections.PACKAGE.utils;
*/ */
public interface STRATEGY KEY_GENERIC_TYPE public interface STRATEGY KEY_GENERIC_TYPE
{ {
#if TYPE_OBJECT
/**
* Identity Strategy
*/
public static final STRATEGY NO_GENERIC_TYPE IDENTITY = new IdentityStrategyBRACES();
/**
* @Type(T)
* @return a IdentityStrategy that allows to emulate a IdentityHashMap
*/
public static GENERIC_KEY_BRACES STRATEGY KEY_GENERIC_TYPE identityStrategy() { return (STRATEGY<KEY_TYPE>)IDENTITY; }
#endif
/** /**
* Type Specific HashCode function * Type Specific HashCode function
* @param o the element that the hashcode is requested for (if object may be null) * @param o the element that the hashcode is requested for (if object may be null)
@@ -20,4 +33,19 @@ public interface STRATEGY KEY_GENERIC_TYPE
* @return if the elements match * @return if the elements match
*/ */
public boolean equals(KEY_TYPE key, KEY_TYPE value); public boolean equals(KEY_TYPE key, KEY_TYPE value);
#if TYPE_OBJECT
/**
* A Strategy that uses Identity HashCode instead of the normal hashing function.
* This simulates a IdentityHashMap without having the need to actually implement it.
* @Type(T)
*/
public static class IdentityStrategy KEY_GENERIC_TYPE implements STRATEGY KEY_GENERIC_TYPE
{
@Override
public int hashCode(KEY_TYPE o) { return System.identityHashCode(o); }
@Override
public boolean equals(KEY_TYPE key, KEY_TYPE value) { return key == value; }
}
#endif
} }
@@ -45,7 +45,6 @@ import speiger.src.collections.VALUE_PACKAGE.utils.VALUE_COLLECTIONS;
#if !SAME_TYPE && !VALUE_OBJECT #if !SAME_TYPE && !VALUE_OBJECT
import speiger.src.collections.VALUE_PACKAGE.utils.VALUE_SETS; import speiger.src.collections.VALUE_PACKAGE.utils.VALUE_SETS;
#endif #endif
#endif #endif
/** /**
@@ -110,7 +109,7 @@ public class MAPS
* @ValueType(V) * @ValueType(V)
* @return empty map of desired type * @return empty map of desired type
*/ */
public static GENERIC_KEY_VALUE_BRACES MAP KEY_VALUE_GENERIC_TYPE emptyMap() { public static GENERIC_KEY_VALUE_BRACES MAP KEY_VALUE_GENERIC_TYPE empty() {
#if TYPE_OBJECT || VALUE_OBJECT #if TYPE_OBJECT || VALUE_OBJECT
return (MAP KEY_VALUE_GENERIC_TYPE)EMPTY; return (MAP KEY_VALUE_GENERIC_TYPE)EMPTY;
#else #else
@@ -127,7 +126,7 @@ public class MAPS
* @note if the inputted map is already synchronized then it will just return it instead * @note if the inputted map is already synchronized then it will just return it instead
* @note iterators do not support synchronization * @note iterators do not support synchronization
*/ */
public static GENERIC_KEY_VALUE_BRACES MAP KEY_VALUE_GENERIC_TYPE synchronizeMap(MAP KEY_VALUE_GENERIC_TYPE map) { return map instanceof SynchronizedMap ? map : new SynchronizedMapKV_BRACES(map); } public static GENERIC_KEY_VALUE_BRACES MAP KEY_VALUE_GENERIC_TYPE synchronize(MAP KEY_VALUE_GENERIC_TYPE map) { return map instanceof SynchronizedMap ? map : new SynchronizedMapKV_BRACES(map); }
/** /**
* Helper function that creates a Helper wrapper to synchronize access with custom access control into the map. * Helper function that creates a Helper wrapper to synchronize access with custom access control into the map.
* @param map the map that should be synchronized * @param map the map that should be synchronized
@@ -138,7 +137,7 @@ public class MAPS
* @note if the inputted map is already synchronized then it will just return it instead * @note if the inputted map is already synchronized then it will just return it instead
* @note iterators do not support synchronization * @note iterators do not support synchronization
*/ */
public static GENERIC_KEY_VALUE_BRACES MAP KEY_VALUE_GENERIC_TYPE synchronizeMap(MAP KEY_VALUE_GENERIC_TYPE map, Object mutex) { return map instanceof SynchronizedMap ? map : new SynchronizedMapKV_BRACES(map, mutex); } public static GENERIC_KEY_VALUE_BRACES MAP KEY_VALUE_GENERIC_TYPE synchronize(MAP KEY_VALUE_GENERIC_TYPE map, Object mutex) { return map instanceof SynchronizedMap ? map : new SynchronizedMapKV_BRACES(map, mutex); }
/** /**
* Helper function that creates a Helper wrapper to synchronize access into the SortedMap. * Helper function that creates a Helper wrapper to synchronize access into the SortedMap.
@@ -149,7 +148,7 @@ public class MAPS
* @note if the inputted map is already synchronized then it will just return it instead * @note if the inputted map is already synchronized then it will just return it instead
* @note iterators do not support synchronization * @note iterators do not support synchronization
*/ */
public static GENERIC_KEY_VALUE_BRACES SORTED_MAP KEY_VALUE_GENERIC_TYPE synchronizeMap(SORTED_MAP KEY_VALUE_GENERIC_TYPE map) { return map instanceof SynchronizedSortedMap ? map : new SynchronizedSortedMapKV_BRACES(map); } public static GENERIC_KEY_VALUE_BRACES SORTED_MAP KEY_VALUE_GENERIC_TYPE synchronize(SORTED_MAP KEY_VALUE_GENERIC_TYPE map) { return map instanceof SynchronizedSortedMap ? map : new SynchronizedSortedMapKV_BRACES(map); }
/** /**
* Helper function that creates a Helper wrapper to synchronize access with custom access control into the SortedMap. * Helper function that creates a Helper wrapper to synchronize access with custom access control into the SortedMap.
* @param map the SortedMap that should be synchronized * @param map the SortedMap that should be synchronized
@@ -160,7 +159,7 @@ public class MAPS
* @note if the inputted map is already synchronized then it will just return it instead * @note if the inputted map is already synchronized then it will just return it instead
* @note iterators do not support synchronization * @note iterators do not support synchronization
*/ */
public static GENERIC_KEY_VALUE_BRACES SORTED_MAP KEY_VALUE_GENERIC_TYPE synchronizeMap(SORTED_MAP KEY_VALUE_GENERIC_TYPE map, Object mutex) { return map instanceof SynchronizedSortedMap ? map : new SynchronizedSortedMapKV_BRACES(map, mutex); } public static GENERIC_KEY_VALUE_BRACES SORTED_MAP KEY_VALUE_GENERIC_TYPE synchronize(SORTED_MAP KEY_VALUE_GENERIC_TYPE map, Object mutex) { return map instanceof SynchronizedSortedMap ? map : new SynchronizedSortedMapKV_BRACES(map, mutex); }
/** /**
* Helper function that creates a Helper wrapper to synchronize access into the NavigableMap. * Helper function that creates a Helper wrapper to synchronize access into the NavigableMap.
@@ -171,7 +170,7 @@ public class MAPS
* @note if the inputted map is already synchronized then it will just return it instead * @note if the inputted map is already synchronized then it will just return it instead
* @note iterators do not support synchronization * @note iterators do not support synchronization
*/ */
public static GENERIC_KEY_VALUE_BRACES NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE synchronizeMap(NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE map) { return map instanceof SynchronizedNavigableMap ? map : new SynchronizedNavigableMapKV_BRACES(map); } public static GENERIC_KEY_VALUE_BRACES NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE synchronize(NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE map) { return map instanceof SynchronizedNavigableMap ? map : new SynchronizedNavigableMapKV_BRACES(map); }
/** /**
* Helper function that creates a Helper wrapper to synchronize access with custom access control into the NavigableMap. * Helper function that creates a Helper wrapper to synchronize access with custom access control into the NavigableMap.
* @param map the NavigableMap that should be synchronized * @param map the NavigableMap that should be synchronized
@@ -182,7 +181,7 @@ public class MAPS
* @note if the inputted map is already synchronized then it will just return it instead * @note if the inputted map is already synchronized then it will just return it instead
* @note iterators do not support synchronization * @note iterators do not support synchronization
*/ */
public static GENERIC_KEY_VALUE_BRACES NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE synchronizeMap(NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE map, Object mutex) { return map instanceof SynchronizedNavigableMap ? map : new SynchronizedNavigableMapKV_BRACES(map, mutex); } public static GENERIC_KEY_VALUE_BRACES NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE synchronize(NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE map, Object mutex) { return map instanceof SynchronizedNavigableMap ? map : new SynchronizedNavigableMapKV_BRACES(map, mutex); }
/** /**
* A Helper function that creates a Helper wrapper to only allow Read Access into the Map * A Helper function that creates a Helper wrapper to only allow Read Access into the Map
@@ -192,7 +191,7 @@ public class MAPS
* @return a unmodifiable Map * @return a unmodifiable Map
* @note if the inputted map is already unmodifiable then it will just return it instead * @note if the inputted map is already unmodifiable then it will just return it instead
*/ */
public static GENERIC_KEY_VALUE_BRACES MAP KEY_VALUE_GENERIC_TYPE unmodifyableMap(MAP KEY_VALUE_GENERIC_TYPE map) { return map instanceof UnmodifyableMap ? map : new UnmodifyableMapKV_BRACES(map); } public static GENERIC_KEY_VALUE_BRACES MAP KEY_VALUE_GENERIC_TYPE unmodifiable(MAP KEY_VALUE_GENERIC_TYPE map) { return map instanceof UnmodifyableMap ? map : new UnmodifyableMapKV_BRACES(map); }
/** /**
* A Helper function that creates a Helper wrapper to only allow Read Access into the SortedMap * A Helper function that creates a Helper wrapper to only allow Read Access into the SortedMap
* @param map the SortedMap that should be made Unmodifiable * @param map the SortedMap that should be made Unmodifiable
@@ -201,7 +200,7 @@ public class MAPS
* @return a unmodifiable SortedMap * @return a unmodifiable SortedMap
* @note if the inputted SortedMap is already unmodifiable then it will just return it instead * @note if the inputted SortedMap is already unmodifiable then it will just return it instead
*/ */
public static GENERIC_KEY_VALUE_BRACES SORTED_MAP KEY_VALUE_GENERIC_TYPE unmodifyableMap(SORTED_MAP KEY_VALUE_GENERIC_TYPE map) { return map instanceof UnmodifyableSortedMap ? map : new UnmodifyableSortedMapKV_BRACES(map); } public static GENERIC_KEY_VALUE_BRACES SORTED_MAP KEY_VALUE_GENERIC_TYPE unmodifiable(SORTED_MAP KEY_VALUE_GENERIC_TYPE map) { return map instanceof UnmodifyableSortedMap ? map : new UnmodifyableSortedMapKV_BRACES(map); }
/** /**
* A Helper function that creates a Helper wrapper to only allow Read Access into NavigableMap Map * A Helper function that creates a Helper wrapper to only allow Read Access into NavigableMap Map
* @param map the NavigableMap that should be made Unmodifiable * @param map the NavigableMap that should be made Unmodifiable
@@ -210,23 +209,23 @@ public class MAPS
* @return a unmodifiable NavigableMap * @return a unmodifiable NavigableMap
* @note if the inputted NavigableMap is already unmodifiable then it will just return it instead * @note if the inputted NavigableMap is already unmodifiable then it will just return it instead
*/ */
public static GENERIC_KEY_VALUE_BRACES NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE unmodifyableMap(NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE map) { return map instanceof UnmodifyableNavigableMap ? map : new UnmodifyableNavigableMapKV_BRACES(map); } public static GENERIC_KEY_VALUE_BRACES NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE unmodifiable(NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE map) { return map instanceof UnmodifyableNavigableMap ? map : new UnmodifyableNavigableMapKV_BRACES(map); }
/** /**
* A Helper function that creates a Unmodifyable Entry * A Helper function that creates a Unmodifyable Entry
* @param entry the Entry that should be made unmodifyable * @param entry the Entry that should be made unmodifiable
* @Type(T) * @Type(T)
* @ValueType(V) * @ValueType(V)
* @return a Unmodifyable Entry * @return a Unmodifyable Entry
*/ */
public static GENERIC_KEY_VALUE_BRACES MAP.Entry KEY_VALUE_GENERIC_TYPE unmodifyableEntry(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { return entry instanceof UnmodifyableEntry ? entry : new UnmodifyableEntryKV_BRACES(entry); } public static GENERIC_KEY_VALUE_BRACES MAP.Entry KEY_VALUE_GENERIC_TYPE unmodifiable(MAP.Entry KEY_VALUE_GENERIC_TYPE entry) { return entry instanceof UnmodifyableEntry ? entry : new UnmodifyableEntryKV_BRACES(entry); }
/** /**
* A Helper function that creates a Unmodifyable Entry * A Helper function that creates a Unmodifyable Entry
* @param entry the Entry that should be made unmodifyable * @param entry the Entry that should be made unmodifiable
* @Type(T) * @Type(T)
* @ValueType(V) * @ValueType(V)
* @return a Unmodifyable Entry * @return a Unmodifyable Entry
*/ */
public static GENERIC_KEY_VALUE_BRACES MAP.Entry KEY_VALUE_GENERIC_TYPE unmodifyableEntry(Map.Entry<CLASS_TYPE, CLASS_VALUE_TYPE> entry) { return entry instanceof UnmodifyableEntry ? (UnmodifyableEntry KEY_VALUE_GENERIC_TYPE)entry : new UnmodifyableEntryKV_BRACES(entry); } public static GENERIC_KEY_VALUE_BRACES MAP.Entry KEY_VALUE_GENERIC_TYPE unmodifiable(Map.Entry<CLASS_TYPE, CLASS_VALUE_TYPE> entry) { return entry instanceof UnmodifyableEntry ? (UnmodifyableEntry KEY_VALUE_GENERIC_TYPE)entry : new UnmodifyableEntryKV_BRACES(entry); }
/** /**
* Creates a Singleton map from the provided values. * Creates a Singleton map from the provided values.
@@ -235,9 +234,9 @@ public class MAPS
* @param value the value that should be turned into a singleton * @param value the value that should be turned into a singleton
* @Type(T) * @Type(T)
* @ValueType(V) * @ValueType(V)
* @return a unmodifyable Singleton map. * @return a unmodifiable Singleton map.
*/ */
public static GENERIC_KEY_VALUE_BRACES MAP KEY_VALUE_GENERIC_TYPE singletonMap(KEY_TYPE key, VALUE_TYPE value) { return new SingletonMapKV_BRACES(key, value); } public static GENERIC_KEY_VALUE_BRACES MAP KEY_VALUE_GENERIC_TYPE singleton(KEY_TYPE key, VALUE_TYPE value) { return new SingletonMapKV_BRACES(key, value); }
/** /**
* Singleton Map instance that is used in the helper method * Singleton Map instance that is used in the helper method
@@ -265,7 +264,9 @@ public class MAPS
public VALUE_TYPE addTo(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); } public VALUE_TYPE addTo(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); }
#endif #endif
@Override @Override
public VALUE_TYPE REMOVE_KEY(KEY_TYPE key) { throw new UnsupportedOperationException(); } public VALUE_TYPE REMOVE_VALUE(KEY_TYPE key) { throw new UnsupportedOperationException(); }
@Override
public VALUE_TYPE REMOVE_VALUEOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { throw new UnsupportedOperationException(); }
#if !TYPE_OBJECT || !VALUE_OBJECT #if !TYPE_OBJECT || !VALUE_OBJECT
@Override @Override
public boolean remove(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); } public boolean remove(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); }
@@ -278,18 +279,18 @@ public class MAPS
#endif #endif
@Override @Override
public SET KEY_GENERIC_TYPE keySet() { public SET KEY_GENERIC_TYPE keySet() {
if(keySet == null) keySet = SETS.singletonSet(key); if(keySet == null) keySet = SETS.singleton(key);
return keySet; return keySet;
} }
@Override @Override
public VALUE_COLLECTION VALUE_GENERIC_TYPE values() { public VALUE_COLLECTION VALUE_GENERIC_TYPE values() {
if(values == null) values = VALUE_SETS.singletonSet(value); if(values == null) values = VALUE_SETS.singleton(value);
return values; return values;
} }
@Override @Override
public ObjectSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> ENTRY_SET() { public ObjectSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> ENTRY_SET() {
if(entrySet == null) entrySet = ObjectSets.singletonSet(new ABSTRACT_MAP.BasicEntryKV_BRACES(key, value)); if(entrySet == null) entrySet = ObjectSets.singleton(new ABSTRACT_MAP.BasicEntryKV_BRACES(key, value));
return entrySet; return entrySet;
} }
} }
@@ -309,7 +310,9 @@ public class MAPS
public VALUE_TYPE addTo(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); } public VALUE_TYPE addTo(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); }
#endif #endif
@Override @Override
public VALUE_TYPE REMOVE_KEY(KEY_TYPE key) { throw new UnsupportedOperationException(); } public VALUE_TYPE REMOVE_VALUE(KEY_TYPE key) { throw new UnsupportedOperationException(); }
@Override
public VALUE_TYPE REMOVE_VALUEOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { throw new UnsupportedOperationException(); }
#if !TYPE_OBJECT || !VALUE_OBJECT #if !TYPE_OBJECT || !VALUE_OBJECT
@Override @Override
public boolean remove(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); } public boolean remove(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); }
@@ -323,7 +326,7 @@ 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(); }
} }
@@ -361,31 +364,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 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 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 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 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 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 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 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 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 unmodifiable(map.tailMap(fromKey)); }
#if !TYPE_OBJECT #if !TYPE_OBJECT
@Override @Override
public void setDefaultMaxValue(KEY_TYPE e) { throw new UnsupportedOperationException(); } public void setDefaultMaxValue(KEY_TYPE e) { throw new UnsupportedOperationException(); }
@@ -405,13 +408,13 @@ 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 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 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 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 unmodifiable(map.ceilingEntry(key)); }
} }
/** /**
@@ -442,11 +445,11 @@ public class MAPS
@Override @Override
public COMPARATOR KEY_GENERIC_TYPE comparator() { return map.comparator(); } public COMPARATOR KEY_GENERIC_TYPE comparator() { return map.comparator(); }
@Override @Override
public SORTED_MAP KEY_VALUE_GENERIC_TYPE subMap(KEY_TYPE fromKey, KEY_TYPE toKey) { return unmodifyableMap(map.subMap(fromKey, toKey)); } public SORTED_MAP KEY_VALUE_GENERIC_TYPE subMap(KEY_TYPE fromKey, KEY_TYPE toKey) { return 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 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 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
@@ -485,7 +488,9 @@ public class MAPS
public VALUE_TYPE addTo(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); } public VALUE_TYPE addTo(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); }
#endif #endif
@Override @Override
public VALUE_TYPE REMOVE_KEY(KEY_TYPE key) { throw new UnsupportedOperationException(); } public VALUE_TYPE REMOVE_VALUE(KEY_TYPE key) { throw new UnsupportedOperationException(); }
@Override
public VALUE_TYPE REMOVE_VALUEOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { throw new UnsupportedOperationException(); }
#if !TYPE_OBJECT || !VALUE_OBJECT #if !TYPE_OBJECT || !VALUE_OBJECT
@Override @Override
public boolean remove(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); } public boolean remove(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); }
@@ -505,7 +510,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 +538,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(unmodifiable(T)));
} }
@Override @Override
@@ -543,7 +548,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 unmodifiable(iter.next()); }
}; };
} }
@@ -568,11 +573,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 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 +587,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 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 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 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 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 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 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
@@ -612,22 +617,22 @@ public class MAPS
#if !TYPE_OBJECT #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 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 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 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 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 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 synchronize(map.tailMap(fromKey), mutex); } }
@Override @Override
public void setDefaultMaxValue(KEY_TYPE e) { synchronized(mutex) { map.setDefaultMaxValue(e); } } public void setDefaultMaxValue(KEY_TYPE e) { synchronized(mutex) { map.setDefaultMaxValue(e); } }
@Override @Override
@@ -696,11 +701,11 @@ public class MAPS
@Override @Override
public COMPARATOR KEY_GENERIC_TYPE comparator() { synchronized(mutex) { return map.comparator(); } } public COMPARATOR KEY_GENERIC_TYPE comparator() { synchronized(mutex) { return map.comparator(); } }
@Override @Override
public SORTED_MAP KEY_VALUE_GENERIC_TYPE subMap(KEY_TYPE fromKey, KEY_TYPE toKey) { synchronized(mutex) { return synchronizeMap(map.subMap(fromKey, toKey), mutex); } } public SORTED_MAP KEY_VALUE_GENERIC_TYPE subMap(KEY_TYPE fromKey, KEY_TYPE toKey) { synchronized(mutex) { return 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 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 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
@@ -722,13 +727,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 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 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 synchronize(map.tailMap(fromKey), mutex); } }
#endif #endif
} }
@@ -768,14 +773,19 @@ public class MAPS
public VALUE_TYPE put(KEY_TYPE key, VALUE_TYPE value) { synchronized(mutex) { return map.put(key, value); } } public VALUE_TYPE put(KEY_TYPE key, VALUE_TYPE value) { synchronized(mutex) { return map.put(key, value); } }
@Override @Override
public VALUE_TYPE putIfAbsent(KEY_TYPE key, VALUE_TYPE value) { synchronized(mutex) { return map.putIfAbsent(key, value); } } public VALUE_TYPE putIfAbsent(KEY_TYPE key, VALUE_TYPE value) { synchronized(mutex) { return map.putIfAbsent(key, value); } }
public void putAllIfAbsent(MAP KEY_VALUE_GENERIC_TYPE m) { synchronized(mutex) { map.putAllIfAbsent(m); } }
#if VALUE_PRIMITIVES #if VALUE_PRIMITIVES
@Override @Override
public VALUE_TYPE addTo(KEY_TYPE key, VALUE_TYPE value) { synchronized(mutex) { return map.addTo(key, value); } } public VALUE_TYPE addTo(KEY_TYPE key, VALUE_TYPE value) { synchronized(mutex) { return map.addTo(key, value); } }
public void addToAll(MAP KEY_VALUE_GENERIC_TYPE m) { synchronized(mutex) { map.addToAll(m); } }
#endif #endif
@Override @Override
public void putAll(MAP KEY_VALUE_GENERIC_TYPE m) { synchronized(mutex) { map.putAll(m); } } public void putAll(MAP KEY_VALUE_GENERIC_TYPE m) { synchronized(mutex) { map.putAll(m); } }
@Override @Override
public void putAll(Map<? extends CLASS_TYPE, ? extends CLASS_VALUE_TYPE> m) { synchronized(mutex) { map.putAll(m); } } public void putAll(Map<? extends CLASS_TYPE, ? extends CLASS_VALUE_TYPE> m) { synchronized(mutex) { map.putAll(m); } }
@Override
public void putAll(KEY_TYPE[] keys, VALUE_TYPE[] values, int offset, int size) { synchronized(mutex) { map.putAll(keys, values, offset, size); } }
#if !TYPE_OBJECT #if !TYPE_OBJECT
@Override @Override
public boolean containsKey(KEY_TYPE key) { synchronized(mutex) { return map.containsKey(key); } } public boolean containsKey(KEY_TYPE key) { synchronized(mutex) { return map.containsKey(key); } }
@@ -787,7 +797,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 +809,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 +820,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); } }
@@ -816,19 +832,19 @@ public class MAPS
public int size() { synchronized(mutex) { return super.size(); } } public int size() { synchronized(mutex) { return super.size(); } }
@Override @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;
} }
@@ -16,5 +16,5 @@ public interface IArray extends RandomAccess, ITrimmable
* *
* @param size the desired minimum capacity * @param size the desired minimum capacity
*/ */
public void ensureCapacity(int size); void ensureCapacity(int size);
} }
@@ -10,7 +10,7 @@ public interface ITrimmable
* Trims the original collection down to the size of the current elements * Trims the original collection down to the size of the current elements
* @return if the internal array has been trimmed. * @return if the internal array has been trimmed.
*/ */
public default boolean trim() { default boolean trim() {
return trim(0); return trim(0);
} }
@@ -19,5 +19,19 @@ public interface ITrimmable
* @param size the requested trim size. * @param size the requested trim size.
* @return if the internal array has been trimmed. * @return if the internal array has been trimmed.
*/ */
public boolean trim(int size); boolean trim(int size);
/**
* Trims the collection down to the original size and clears all present elements with it.
*/
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
*/
void clearAndTrim(int size);
} }
@@ -1,5 +1,8 @@
package speiger.src.collections.utils; package speiger.src.collections.utils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Random; import java.util.Random;
import java.util.concurrent.ForkJoinPool; import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask; import java.util.concurrent.ForkJoinTask;
@@ -8,15 +11,15 @@ import java.util.concurrent.ForkJoinTask;
* Helper class that provides functions that are shared within the library. * Helper class that provides functions that are shared within the library.
* On top of that it provides some helper functions that allow control of some internals of the Library * On top of that it provides some helper functions that allow control of some internals of the Library
*/ */
public class SanityChecks public final class SanityChecks
{ {
/** Max Possible ArraySize without the JVM Crashing */ /** Max Possible ArraySize without the JVM Crashing */
public static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; public static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
private static ForkJoinPool WORK_POOL = ForkJoinPool.commonPool(); private static ForkJoinPool WORK_POOL = ForkJoinPool.commonPool();
private static boolean FORCE_IGNORE_PARALLELISM = false; private static boolean FORCE_IGNORE_PARALLELISM = false;
private static ThreadLocal<Random> RANDOM = ThreadLocal.withInitial(Random::new); private static final ThreadLocal<Random> RANDOM = ThreadLocal.withInitial(Random::new);
private static ThreadLocal<Boolean> FORCE_ASYNC = ThreadLocal.withInitial(() -> false); private static final ThreadLocal<Boolean> FORCE_ASYNC = ThreadLocal.withInitial(() -> false);
private static ThreadLocal<Boolean> FORCE_TASK_POOL = ThreadLocal.withInitial(() -> false); private static final ThreadLocal<Boolean> FORCE_TASK_POOL = ThreadLocal.withInitial(() -> false);
/** /**
* Internal function to cast a Integer to a Byte * Internal function to cast a Integer to a Byte
@@ -90,8 +93,8 @@ public class SanityChecks
* @param task the Task to invoke * @param task the Task to invoke
* @param <T> the type of the task * @param <T> the type of the task
*/ */
public static <T> void invokeTask(ForkJoinTask<T> task) { public static <T> void invokeTask(@NotNull ForkJoinTask<T> task) {
if(FORCE_ASYNC.get().booleanValue()) invokeAsyncTask(task); if(FORCE_ASYNC.get()) invokeAsyncTask(task);
else getPool().invoke(task); else getPool().invoke(task);
} }
@@ -100,7 +103,7 @@ public class SanityChecks
* @param task the Task to invoke * @param task the Task to invoke
* @param <T> the type of the task * @param <T> the type of the task
*/ */
public static <T> void invokeAsyncTask(ForkJoinTask<T> task) { public static <T> void invokeAsyncTask(@NotNull ForkJoinTask<T> task) {
getPool().execute(task); getPool().execute(task);
} }
@@ -109,12 +112,12 @@ public class SanityChecks
* @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.
* @param pool The ForkJoinPool that should receive the tasks. If null {@link ForkJoinPool#commonPool()} is set instead * @param pool The ForkJoinPool that should receive the tasks. If null {@link ForkJoinPool#commonPool()} is set instead
*/ */
public static void setWorkPool(ForkJoinPool pool) { public static void setWorkPool(@Nullable ForkJoinPool pool) {
WORK_POOL = pool == null ? ForkJoinPool.commonPool() : pool; WORK_POOL = pool == null ? ForkJoinPool.commonPool() : pool;
} }
private static ForkJoinPool getPool() { private static @NotNull ForkJoinPool getPool() {
if(FORCE_TASK_POOL.get().booleanValue()) { if(FORCE_TASK_POOL.get()) {
ForkJoinPool pool = ForkJoinTask.getPool(); ForkJoinPool pool = ForkJoinTask.getPool();
if(pool != null) return pool; if(pool != null) return pool;
} }
@@ -126,7 +129,7 @@ public class SanityChecks
* @return if the Current Thread has not to await task completion. * @return if the Current Thread has not to await task completion.
*/ */
public static boolean isForcedAsync() { public static boolean isForcedAsync() {
return FORCE_ASYNC.get().booleanValue(); return FORCE_ASYNC.get();
} }
/** /**
@@ -134,7 +137,7 @@ public class SanityChecks
* @return if the task checks the current pool to be executed in if it is valid. * @return if the task checks the current pool to be executed in if it is valid.
*/ */
public static boolean isForcedTaskPool() { public static boolean isForcedTaskPool() {
return FORCE_TASK_POOL.get().booleanValue(); return FORCE_TASK_POOL.get();
} }
/** /**
@@ -142,7 +145,7 @@ public class SanityChecks
* @param value it tasks should not be awaited for * @param value it tasks should not be awaited for
*/ */
public static void setForcedAsync(boolean value) { public static void setForcedAsync(boolean value) {
FORCE_ASYNC.set(Boolean.valueOf(value)); FORCE_ASYNC.set(value);
} }
/** /**
@@ -150,7 +153,7 @@ public class SanityChecks
* @param value if the current thread should check if it is a ThreadPoolWorker. * @param value if the current thread should check if it is a ThreadPoolWorker.
*/ */
public static void setForcedTaskPool(boolean value) { public static void setForcedTaskPool(boolean value) {
FORCE_TASK_POOL.set(Boolean.valueOf(value)); FORCE_TASK_POOL.set(value);
} }
/** /**
@@ -164,7 +167,7 @@ public class SanityChecks
/** /**
* @return Thread Specific Random needed for internal functions in this library. * @return Thread Specific Random needed for internal functions in this library.
*/ */
public static Random getRandom() { public static @NotNull Random getRandom() {
return RANDOM.get(); return RANDOM.get();
} }
} }
@@ -1,6 +1,8 @@
package speiger.src.collections.utils; package speiger.src.collections.utils;
import org.jetbrains.annotations.NotNull;
/** /**
* The Stack Interface represents the Last-In-First-Out layout (LIFO). * The Stack Interface represents the Last-In-First-Out layout (LIFO).
* It provides a simple {@link #push(Object)}, {@link #pop()} function, * It provides a simple {@link #push(Object)}, {@link #pop()} function,
@@ -14,32 +16,40 @@ public interface Stack<T>
* 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
*/ */
public void push(T e); void push(@NotNull T e);
/** /**
* Removes the Object on top of the stack. * Removes the Object on top of the stack.
* @return the element that is on top of the stack * @return the element that is on top of the stack
* @throws ArrayIndexOutOfBoundsException if the stack is empty * @throws ArrayIndexOutOfBoundsException if the stack is empty
*/ */
public T pop(); @NotNull T pop();
/** /**
* Provides the amount of elements currently in the stack * Provides the amount of elements currently in the stack
* @return amount of elements in the list * @return amount of elements in the list
*/ */
public int size(); int size();
/**
* @return if the stack is empty
*/
default boolean isEmpty() {
return size() == 0;
}
/** /**
* Clears the stack * Clears the stack
*/ */
public void clear(); void clear();
/** /**
* Provides the Object on top of the stack * Provides the Object on top of the stack
* @return the element that is on top of the stack * @return the element that is on top of the stack
* @throws ArrayIndexOutOfBoundsException if the stack is empty * @throws ArrayIndexOutOfBoundsException if the stack is empty
*/ */
public default T top() { default @NotNull T top() {
return peek(0); return peek(0);
} }
@@ -50,5 +60,5 @@ public interface Stack<T>
* @return the element that was requested * @return the element that was requested
* @throws ArrayIndexOutOfBoundsException if the index is out of bounds * @throws ArrayIndexOutOfBoundsException if the index is out of bounds
*/ */
public T peek(int index); @NotNull T peek(int index);
} }
@@ -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,7 +131,7 @@ 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]));
} }
@@ -62,11 +62,7 @@ public abstract class BaseInt2IntSortedMapTest extends BaseInt2IntMapTest
{ {
if(!getValidSortedMapTests().contains(SortedMapTests.FIRST)) return; if(!getValidSortedMapTests().contains(SortedMapTests.FIRST)) return;
Int2IntSortedMap map = createMap(TEST_ARRAY, TEST_ARRAY); Int2IntSortedMap map = createMap(TEST_ARRAY, TEST_ARRAY);
for(int i = 0;i<TEST_ARRAY.length;i++) Assert.assertEquals(map.pollFirstIntKey(), 0);
{
Assert.assertEquals(TEST_ARRAY[i], map.pollFirstIntKey());
}
Assert.assertEquals(0, map.size());
} }
@Test @Test
@@ -74,11 +70,7 @@ public abstract class BaseInt2IntSortedMapTest extends BaseInt2IntMapTest
{ {
if(!getValidSortedMapTests().contains(SortedMapTests.LAST)) return; if(!getValidSortedMapTests().contains(SortedMapTests.LAST)) return;
Int2IntSortedMap map = createMap(TEST_ARRAY, TEST_ARRAY); Int2IntSortedMap map = createMap(TEST_ARRAY, TEST_ARRAY);
for(int i = TEST_ARRAY.length-1;i>=0;i--) Assert.assertEquals(map.pollLastIntKey(), 99);
{
Assert.assertEquals(TEST_ARRAY[i], map.pollLastIntKey());
}
Assert.assertEquals(0, map.size());
} }
@Test @Test
@@ -87,8 +79,8 @@ public abstract class BaseInt2IntSortedMapTest extends BaseInt2IntMapTest
if(!getValidSortedMapTests().contains(SortedMapTests.SUB_MAP)) return; if(!getValidSortedMapTests().contains(SortedMapTests.SUB_MAP)) return;
Int2IntSortedMap map = createMap(TEST_ARRAY, TEST_ARRAY); Int2IntSortedMap map = createMap(TEST_ARRAY, TEST_ARRAY);
Int2IntSortedMap subMap = map.subMap(25, 75); Int2IntSortedMap subMap = map.subMap(25, 75);
Assert.assertEquals(50, subMap.remInt(50)); Assert.assertEquals(50, subMap.remove(50));
Assert.assertNotEquals(50, subMap.remInt(50)); Assert.assertNotEquals(50, subMap.remove(50));
Assert.assertFalse(subMap.containsKey(20)); Assert.assertFalse(subMap.containsKey(20));
Assert.assertFalse(subMap.containsKey(80)); Assert.assertFalse(subMap.containsKey(80));
} }
@@ -99,8 +91,8 @@ public abstract class BaseInt2IntSortedMapTest extends BaseInt2IntMapTest
if(!getValidSortedMapTests().contains(SortedMapTests.HEAD_MAP)) return; if(!getValidSortedMapTests().contains(SortedMapTests.HEAD_MAP)) return;
Int2IntSortedMap map = createMap(TEST_ARRAY, TEST_ARRAY); Int2IntSortedMap map = createMap(TEST_ARRAY, TEST_ARRAY);
Int2IntSortedMap subMap = map.headMap(75); Int2IntSortedMap subMap = map.headMap(75);
Assert.assertEquals(50, subMap.remInt(50)); Assert.assertEquals(50, subMap.remove(50));
Assert.assertNotEquals(50, subMap.remInt(50)); Assert.assertNotEquals(50, subMap.remove(50));
Assert.assertFalse(subMap.containsKey(80)); Assert.assertFalse(subMap.containsKey(80));
} }
@@ -110,8 +102,8 @@ public abstract class BaseInt2IntSortedMapTest extends BaseInt2IntMapTest
if(!getValidSortedMapTests().contains(SortedMapTests.TAIL_MAP)) return; if(!getValidSortedMapTests().contains(SortedMapTests.TAIL_MAP)) return;
Int2IntSortedMap map = createMap(TEST_ARRAY, TEST_ARRAY); Int2IntSortedMap map = createMap(TEST_ARRAY, TEST_ARRAY);
Int2IntSortedMap subMap = map.tailMap(25); Int2IntSortedMap subMap = map.tailMap(25);
Assert.assertEquals(50, subMap.remInt(50)); Assert.assertEquals(50, subMap.remove(50));
Assert.assertNotEquals(50, subMap.remInt(50)); Assert.assertNotEquals(50, subMap.remove(50));
Assert.assertFalse(subMap.containsKey(20)); Assert.assertFalse(subMap.containsKey(20));
} }
} }
@@ -2,6 +2,7 @@ package speiger.src.collections.ints.base;
import java.util.Arrays; import java.util.Arrays;
import java.util.EnumSet; import java.util.EnumSet;
import java.util.List;
import java.util.stream.IntStream; import java.util.stream.IntStream;
import org.junit.Assert; import org.junit.Assert;
@@ -12,6 +13,7 @@ import speiger.src.collections.ints.utils.IntArrays;
import speiger.src.collections.ints.utils.IntCollections; import speiger.src.collections.ints.utils.IntCollections;
import speiger.src.collections.ints.utils.IntCollections.SynchronizedCollection; import speiger.src.collections.ints.utils.IntCollections.SynchronizedCollection;
import speiger.src.collections.ints.utils.IntCollections.UnmodifiableCollection; import speiger.src.collections.ints.utils.IntCollections.UnmodifiableCollection;
import speiger.src.collections.objects.lists.ObjectArrayList;
import speiger.src.collections.tests.CollectionTest; import speiger.src.collections.tests.CollectionTest;
@SuppressWarnings("javadoc") @SuppressWarnings("javadoc")
@@ -47,6 +49,9 @@ public abstract class BaseIntCollectionTest extends BaseIntIterableTest
Assert.assertEquals(TEST_ARRAY.length, collection.size()); Assert.assertEquals(TEST_ARRAY.length, collection.size());
collection.addAll(create(BULK_ADD_ARRAY)); collection.addAll(create(BULK_ADD_ARRAY));
Assert.assertEquals(TEST_ARRAY.length + BULK_ADD_ARRAY.length, collection.size()); Assert.assertEquals(TEST_ARRAY.length + BULK_ADD_ARRAY.length, collection.size());
// Testing if adding via non Type Specific work like they should
List<Integer> wrapper = new ObjectArrayList<>(create(ADD_ARRAY));
Assert.assertNotNull(create(ADD_ARRAY).addAll(wrapper));
} }
@Test @Test
@@ -158,9 +163,19 @@ 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());
}
} }
@@ -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));
} }
@@ -26,14 +26,14 @@ public abstract class BaseIntPriorityQueueTest extends BaseIntIterableTest
if(getValidPriorityQueueTests().contains(PriorityQueueTest.IN_OUT)) { if(getValidPriorityQueueTests().contains(PriorityQueueTest.IN_OUT)) {
IntPriorityQueue queue = create(EMPTY_ARRAY); IntPriorityQueue queue = create(EMPTY_ARRAY);
for(int i = 0;i<100;i++) { for(int i = 0;i<100;i++) {
queue.enqueueInt(i); queue.enqueue(i);
} }
for(int i = 0;i<100;i++) { for(int i = 0;i<100;i++) {
Assert.assertEquals(i, queue.dequeueInt()); Assert.assertEquals(i, queue.dequeue());
} }
queue = create(TEST_ARRAY); queue = create(TEST_ARRAY);
for(int i = 0;i<100;i++) { for(int i = 0;i<100;i++) {
Assert.assertEquals(i, queue.dequeueInt()); Assert.assertEquals(i, queue.dequeue());
} }
} }
} }
@@ -43,17 +43,17 @@ public abstract class BaseIntPriorityQueueTest extends BaseIntIterableTest
if(getValidPriorityQueueTests().contains(PriorityQueueTest.PEEK)) { if(getValidPriorityQueueTests().contains(PriorityQueueTest.PEEK)) {
IntPriorityQueue queue = create(EMPTY_ARRAY); IntPriorityQueue queue = create(EMPTY_ARRAY);
for(int i = 0;i<100;i++) { for(int i = 0;i<100;i++) {
queue.enqueueInt(i); queue.enqueue(i);
} }
if(isUnsortedRead()) { if(isUnsortedRead()) {
for(int i = 0;i<100;i++) { for(int i = 0;i<100;i++) {
int value = queue.peekInt(i); int value = queue.peek(i);
Assert.assertTrue(value >= 0 && value < 100); Assert.assertTrue(value >= 0 && value < 100);
} }
} }
else { else {
for(int i = 0;i<100;i++) { for(int i = 0;i<100;i++) {
Assert.assertEquals(i, queue.peekInt(i)); Assert.assertEquals(i, queue.peek(i));
} }
} }
} }
@@ -64,20 +64,20 @@ public abstract class BaseIntPriorityQueueTest extends BaseIntIterableTest
if(getValidPriorityQueueTests().contains(PriorityQueueTest.REMOVE)) { if(getValidPriorityQueueTests().contains(PriorityQueueTest.REMOVE)) {
IntPriorityQueue queue = create(EMPTY_ARRAY); IntPriorityQueue queue = create(EMPTY_ARRAY);
for(int i = 0;i<100;i++) { for(int i = 0;i<100;i++) {
queue.enqueueInt(i); queue.enqueue(i);
} }
queue.removeInt(40); queue.removeFirst(40);
for(int i = 0;i<99;i++) { for(int i = 0;i<99;i++) {
if(i >= 40) Assert.assertEquals(i + 1, queue.dequeueInt()); if(i >= 40) Assert.assertEquals(i + 1, queue.dequeue());
else Assert.assertEquals(i, queue.dequeueInt()); else Assert.assertEquals(i, queue.dequeue());
} }
for(int i = 0;i<100;i++) { for(int i = 0;i<100;i++) {
queue.enqueueInt(i); queue.enqueue(i);
} }
queue.removeLastInt(40); queue.removeLast(40);
for(int i = 0;i<99;i++) { for(int i = 0;i<99;i++) {
if(i >= 40) Assert.assertEquals(i + 1, queue.dequeueInt()); if(i >= 40) Assert.assertEquals(i + 1, queue.dequeue());
else Assert.assertEquals(i, queue.dequeueInt()); else Assert.assertEquals(i, queue.dequeue());
} }
} }
} }
@@ -89,7 +89,7 @@ public abstract class BaseIntPriorityQueueTest extends BaseIntIterableTest
IntPriorityQueue queue = create(EMPTY_ARRAY); IntPriorityQueue queue = create(EMPTY_ARRAY);
if(isUnsortedRead()) { if(isUnsortedRead()) {
for(int i = 0;i<100;i++) { for(int i = 0;i<100;i++) {
queue.enqueueInt(i); queue.enqueue(i);
} }
int[] array = queue.toIntArray(); int[] array = queue.toIntArray();
IntArrays.stableSort(array); IntArrays.stableSort(array);
@@ -102,28 +102,21 @@ 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());
} }
} }
} }
@@ -49,9 +49,15 @@ public abstract class BaseIntSortedSetTest extends BaseIntCollectionTest
public void pollTest() { public void pollTest() {
if(getValidSortedSetTests().contains(SortedSetTest.POLL)) { if(getValidSortedSetTests().contains(SortedSetTest.POLL)) {
IntSortedSet set = create(TEST_ARRAY); IntSortedSet set = create(TEST_ARRAY);
Assert.assertEquals(set.pollFirstInt(), 0); for(int i = 0;i<100;i++)
Assert.assertEquals(set.pollLastInt(), 99); {
Assert.assertEquals(i, set.pollFirstInt());
}
set = create(TEST_ARRAY);
for(int i = 99;i>=0;i--)
{
Assert.assertEquals(i, set.pollLastInt());
}
} }
} }
@@ -18,13 +18,13 @@ public interface IIntStackTests
public default void testPush() public default void testPush()
{ {
IntStack stacks = create(TEST_ARRAY); IntStack stacks = create(TEST_ARRAY);
stacks.pushInt(500); stacks.push(500);
Assert.assertEquals(500, stacks.topInt()); Assert.assertEquals(500, stacks.top());
} }
@Test @Test
public default void testPop() public default void testPop()
{ {
Assert.assertEquals(99, create(TEST_ARRAY).topInt()); Assert.assertEquals(99, create(TEST_ARRAY).top());
} }
} }
@@ -0,0 +1,44 @@
package speiger.src.collections.ints.lists;
import org.junit.Test;
import speiger.src.collections.ints.base.BaseIntListTest;
import speiger.src.collections.ints.base.BaseIntPriorityQueueTest;
import speiger.src.collections.ints.base.IIntStackTests;
import speiger.src.collections.ints.queues.IntPriorityQueue;
/**
* @author Speiger
*
*/
public class IntLinkedListTest extends BaseIntListTest implements IIntStackTests
{
@Override
public IntLinkedList create(int[] data) {
return new IntLinkedList(data);
}
@Test
@Override
public void testPush() {
IIntStackTests.super.testPush();
}
@Test
@Override
public void testPop() {
IIntStackTests.super.testPop();
}
/**
* @author Speiger
*/
public static class IntLinkedListQueueTest extends BaseIntPriorityQueueTest {
@Override
protected IntPriorityQueue create(int[] data) {
return new IntLinkedList(data);
}
}
}
@@ -6,6 +6,7 @@ import speiger.src.collections.ints.base.BaseIntCollectionTest;
import speiger.src.collections.ints.base.BaseIntSortedSetTest; import speiger.src.collections.ints.base.BaseIntSortedSetTest;
import speiger.src.collections.ints.collections.IntCollection; import speiger.src.collections.ints.collections.IntCollection;
import speiger.src.collections.ints.utils.IntStrategy; import speiger.src.collections.ints.utils.IntStrategy;
import speiger.src.collections.tests.CollectionTest;
import speiger.src.collections.tests.SortedSetTest; import speiger.src.collections.tests.SortedSetTest;
@SuppressWarnings("javadoc") @SuppressWarnings("javadoc")
@@ -21,6 +22,14 @@ public class IntHashSetTests
{ {
@Override @Override
protected IntCollection create(int[] data) { return new IntOpenHashSet(data); } protected IntCollection create(int[] data) { return new IntOpenHashSet(data); }
@Override
protected EnumSet<CollectionTest> getValidCollectionTests()
{
EnumSet<CollectionTest> tests = super.getValidCollectionTests();
tests.remove(CollectionTest.TO_STRING);
return tests;
}
} }
public static class IntLinkedOpenHashSetTests extends BaseIntOpenHashSetTests public static class IntLinkedOpenHashSetTests extends BaseIntOpenHashSetTests
@@ -33,6 +42,14 @@ public class IntHashSetTests
{ {
@Override @Override
protected IntCollection create(int[] data) { return new IntOpenCustomHashSet(data, new DefaultStrategy()); } protected IntCollection create(int[] data) { return new IntOpenCustomHashSet(data, new DefaultStrategy()); }
@Override
protected EnumSet<CollectionTest> getValidCollectionTests()
{
EnumSet<CollectionTest> tests = super.getValidCollectionTests();
tests.remove(CollectionTest.TO_STRING);
return tests;
}
} }
public static class IntLinkedOpenCustomHashSetTests extends BaseIntOpenHashSetTests public static class IntLinkedOpenCustomHashSetTests extends BaseIntOpenHashSetTests
@@ -0,0 +1,134 @@
package speiger.src.collections.objects.utils;
import java.io.BufferedReader;
import java.io.File;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import speiger.src.collections.objects.lists.ObjectArrayList;
import speiger.src.collections.objects.lists.ObjectLinkedList;
import speiger.src.collections.objects.lists.ObjectList;
@SuppressWarnings("javadoc")
public class StringSortTest
{
public static final String[] NAMES = loadNames();
private static final String[] loadNames()
{
List<String> list = new ArrayList<>();
try(BufferedReader reader = Files.newBufferedReader(new File("src/test/resources/testAssets/strings/names.txt").toPath()))
{
reader.lines().forEach(list::add);
}
catch(Exception e)
{
e.printStackTrace();
}
list.sort(null);
return list.toArray(new String[list.size()]);
}
@Test
public void testArrayListSort() {
ObjectList<String> list = new ObjectArrayList<>(NAMES.clone());
ObjectLists.shuffle(list);
Assert.assertFalse(Arrays.equals(list.toArray(new String[list.size()]), NAMES));
list.sort(String::compareTo);
Assert.assertTrue(Arrays.equals(list.toArray(new String[list.size()]), NAMES));
ObjectLists.shuffle(list);
Assert.assertFalse(Arrays.equals(list.toArray(new String[list.size()]), NAMES));
list.sort(null);
Assert.assertTrue(Arrays.equals(list.toArray(new String[list.size()]), NAMES));
}
@Test
public void testLinkedListSort() {
ObjectList<String> list = new ObjectLinkedList<>(NAMES.clone());
ObjectLists.shuffle(list);
Assert.assertFalse(Arrays.equals(list.toArray(new String[list.size()]), NAMES));
list.sort(String::compareTo);
Assert.assertTrue(Arrays.equals(list.toArray(new String[list.size()]), NAMES));
ObjectLists.shuffle(list);
Assert.assertFalse(Arrays.equals(list.toArray(new String[list.size()]), NAMES));
list.sort(null);
Assert.assertTrue(Arrays.equals(list.toArray(new String[list.size()]), NAMES));
}
@Test
public void testInsertionSort() {
String[] array = ObjectArrays.shuffle(NAMES.clone());
Assert.assertFalse(Arrays.equals(array, NAMES));
ObjectArrays.insertionSort(array);
Assert.assertArrayEquals(NAMES, array);
ObjectArrays.shuffle(array);
Assert.assertFalse(Arrays.equals(array, NAMES));
ObjectArrays.insertionSort(array, String::compareTo);
Assert.assertArrayEquals(NAMES, array);
}
@Test
public void testMergeSort() {
String[] array = ObjectArrays.shuffle(NAMES.clone());
Assert.assertFalse(Arrays.equals(array, NAMES));
ObjectArrays.mergeSort(array);
Assert.assertArrayEquals(NAMES, array);
ObjectArrays.shuffle(array);
Assert.assertFalse(Arrays.equals(array, NAMES));
ObjectArrays.mergeSort(array, String::compareTo);
Assert.assertArrayEquals(NAMES, array);
}
@Test
public void testSelectionSortSort() {
String[] array = ObjectArrays.shuffle(NAMES.clone());
Assert.assertFalse(Arrays.equals(array, NAMES));
ObjectArrays.selectionSort(array);
Assert.assertArrayEquals(NAMES, array);
ObjectArrays.shuffle(array);
Assert.assertFalse(Arrays.equals(array, NAMES));
ObjectArrays.selectionSort(array, String::compareTo);
Assert.assertArrayEquals(NAMES, array);
}
@Test
public void testQuickSortSort() {
String[] array = ObjectArrays.shuffle(NAMES.clone());
Assert.assertFalse(Arrays.equals(array, NAMES));
ObjectArrays.quickSort(array);
Assert.assertArrayEquals(NAMES, array);
ObjectArrays.shuffle(array);
Assert.assertFalse(Arrays.equals(array, NAMES));
ObjectArrays.quickSort(array, String::compareTo);
Assert.assertArrayEquals(NAMES, array);
}
@Test
public void testParallelMergeSort() {
String[] array = ObjectArrays.shuffle(NAMES.clone());
Assert.assertFalse(Arrays.equals(array, NAMES));
ObjectArrays.parallelMergeSort(array);
Assert.assertArrayEquals(NAMES, array);
ObjectArrays.shuffle(array);
Assert.assertFalse(Arrays.equals(array, NAMES));
ObjectArrays.parallelMergeSort(array, String::compareTo);
Assert.assertArrayEquals(NAMES, array);
}
@Test
public void testParallelQuickSort() {
String[] array = ObjectArrays.shuffle(NAMES.clone());
Assert.assertFalse(Arrays.equals(array, NAMES));
ObjectArrays.parallelQuickSort(array);
Assert.assertArrayEquals(NAMES, array);
ObjectArrays.shuffle(array);
Assert.assertFalse(Arrays.equals(array, NAMES));
ObjectArrays.parallelQuickSort(array, String::compareTo);
Assert.assertArrayEquals(NAMES, array);
}
}
@@ -14,5 +14,6 @@ public enum CollectionTest
RETAIN_ALL, RETAIN_ALL,
TO_ARRAY, TO_ARRAY,
CLEAR, CLEAR,
WRAPPER; WRAPPER,
TO_STRING;
} }
File diff suppressed because it is too large Load Diff