101 Commits
Author SHA1 Message Date
Speiger 36f24731b0 Script Cleanup, Changelog Update and Version Bump.
Added a lot of Unit Tests (Roughly 7 Million) to Primitive Collections
(look Debug Branch) and found some really big bugs.
The Coverage was moved from 1.9% to 34.7% so far.
So there were a lot bugs found and at this point I need a break so this
is the first fixpatch until new tests are added.
2022-05-28 23:34:37 +02:00
Speiger ea5ace0166 Another Coverage Try 2022-05-28 20:32:15 +02:00
Speiger 663809ff27 another test 2022-05-28 20:11:00 +02:00
Speiger 5d6adb5446 Added Jacoco reports 2022-05-28 19:58:54 +02:00
Speiger 212ad1ace2 Add coverage test 2022-05-28 19:56:28 +02:00
Speiger 707827929a Updated version number 2022-05-27 21:21:11 +02:00
Speiger 27ad01657d More fixes from Unit tests.
-Fixed: ArrayList/LinkedList extractElements crashing when 0 or less elements are desired.
-Fixed: TreeMap pollFirst/LastKey should return the defaultMin/max value instead of a Empty value.
-Fixed: TreeMap keySet implementation was missing the class type implementations to pass keySet tests.
-Fixed: TreeMap.SubMap Iterator (primitive Keys) was crashing because a Null was set on to a primitive.
2022-05-27 16:35:41 +02:00
Speiger e7da7acc08 Started massive unit testing library these are the first fixes.
-Fixed: AbstractCollection.retainAll didn't push removed values through the consumer.
-Fixed: AbstractCollection.toArray wouldn't reset the last entry if the input array was larger then the elements in the collection.
-Fixed: SubList didn't check for ranges properly or didn't use parent list to validate changes.
-Fixed: ArrayList.addElements didn't check input array fully and used the wrong variable to move the elements around.
-Fixed: LinkedList.addElements(EmptyInput) would crash.
-Fixed: LinkedList.swapRemove didn't account for if the removed element was the prelast one.
-Fixed: LinkedList.removeElements would break the implementation if the list was almost empty and the middle element was removed.
-Fixed: LinkedHashSet.addAndMoveToFirst wouldn't move elements to the first place.
2022-05-22 15:13:29 +02:00
Speiger 72943cb22c Added AsyncBuilder for arrays 2022-05-17 18:10:07 +02:00
Speiger 068cc4a4f7 Fixed Bugs with Java Iterators not throwing the correct exception. 2022-05-17 10:45:05 +02:00
Speiger 31b34f5de1 Fixed a couple bugs.
-Fixed: TreeMap.subMap().entrySet().remove() wouldn't check primitives properly.
-Fixed: SortedMap.sub/tail/headMap were looping into themselves.
-Changed: LinkedList.addBulk variable definition was triggering a false positive.
2022-05-17 07:59:57 +02:00
Speiger 4bded1af80 Small Change to sorting
-Added: Array only sorting function return the inputed array. This was done to allow for static final references to use the method in one go without having to make lambda wrappers. Cleaner code.
2022-04-30 22:41:11 +02:00
Speiger 100c7fe260 Updated yml Scripts
-Updated: yml Scripts and ReadMe since the gradle setup no longer requires 2 commands to work properly.
2022-04-28 19:09:42 +02:00
Speiger 04f628fcc1 Pushing release 2022-04-21 17:41:50 +02:00
Speiger 5fa26bfbf3 New Stuff
-Fixed: Crash with FIFOQueues peek function when loops were applied.
-Fixed: FIFOQueues clean function was doing unessesary extra work.
-Added: Stream Overrides functions now support sorted.
-Updated: Changelog.
-Added: A couple more badges because why not.
2022-04-21 17:25:23 +02:00
Speiger 4d3eaaf604 removing SolarCloud code 2022-04-19 17:16:53 +02:00
Speiger 33ab7c48bf hopefully doesn't filter anything. Last attempt 2022-04-19 17:10:57 +02:00
Speiger 1f4784c75e Testing single task requirement 2022-04-19 16:58:22 +02:00
Speiger ae5a4ea818 Readded caching 2022-04-19 16:33:16 +02:00
Speiger 5d66f7b453 Update Code compare 2022-04-19 16:11:20 +02:00
Speiger 12af656150 Updated Task Name 2022-04-19 16:04:20 +02:00
Speiger 603ff3df0f Fixed code compare 2022-04-19 15:52:41 +02:00
Speiger b712981718 Code quality test 2022-04-19 15:51:01 +02:00
Speiger 863d1a1027 Updated Readme. 2022-04-18 21:41:55 +02:00
Speiger 6287da8efe ReadMe restructuring. 2022-04-18 09:06:32 +02:00
Speiger c27e852ccb typo missed by the spellchecker... 2022-04-17 20:39:06 +02:00
Speiger 0157765628 Hotfix. 2022-04-17 20:24:31 +02:00
Speiger 8689037ceb Documentation update 2022-04-17 20:21:48 +02:00
Speiger 03a8914986 Completion Jitpack Integration 2022-04-14 09:51:36 +02:00
Speiger 26b9d6706d Fixed Classification 2022-04-14 09:34:16 +02:00
Speiger a21d4a9eb6 Fixing Jitpack Publishing 2022-04-14 09:24:13 +02:00
Speiger 212d614ebd Trying switching Jitpack Java version. 2022-04-14 09:19:27 +02:00
Speiger bcba3ccde0 Another try 2022-04-14 09:13:53 +02:00
Speiger b42ad76372 Jitpack Test 2022-04-14 09:12:03 +02:00
Speiger f95565771a 0.6.0 Release Commit 2022-04-14 07:56:39 +02:00
Speiger 3d6cbf5ac1 Finishing touches for the 0.6.0 release. 2022-04-14 07:29:32 +02:00
Speiger fc5d43e14b Updated Changelog. 2022-04-14 06:06:35 +02:00
Speiger b3264748cd Added Author to module Info. 2022-04-14 05:47:19 +02:00
Speiger ede40f06d0 Small fixes.
-Fixed: Some imports.
-Fixed: containsValue for OpenHashMap was not checking nullEntry properly
2022-04-14 05:37:41 +02:00
Speiger e69c675f82 Fixed bug with linux & cleanup of the java version detector 2022-04-13 02:58:35 +02:00
Speiger 17c1c90957 Added Module-Info support 2022-04-13 02:54:03 +02:00
Speiger c6f2f71f6c Switching to a new lock to make read operations actually concurrent. 2022-04-13 02:00:52 +02:00
Speiger d2c7c151bc Implemented tests.
-Added: ConcurrentHashMap test suite
-Fixed: Bugs found in ConcurrentHashMaps with the iterator and clear function.
2022-04-12 08:08:17 +02:00
Speiger 4448eca787 Finishing ConcurrentHashMap implementation, next tests 2022-04-12 06:06:18 +02:00
Speiger 0350a77dff Finishing the ConcurrentMap implementation
This though isn't finishing the rest because the interface still needs
to be implemented.
-Added: Rest of the ConcurrentMap implementation
-Fixed: LinkedOpenHashMap Count method was returning prematurely.
2022-04-11 03:20:28 +02:00
Speiger 4f98c599df New Features.
-Added: ArrayList.of(CLASS, size) function that allows to preallocate
the size of the generic list.
-Updated: ListTests suppressors only suprres what they need to.
-Added: Start of the ConcurrentHashMap implementation (based on Guavas
implementation)

Note that the ConcurrentHashMap implementation is just started not
finished and still needs a lot of work, but the base code - any
subclasses is technically finished.
The implementation is also using linkedMaps to have faster iteration
performance.
2022-04-10 15:49:16 +02:00
Speiger 103b2407d2 Updated Changelog 2022-04-09 04:23:57 +02:00
Speiger 059da9be12 New Features
-Added: CopyOnWriteArrayList
-Added: UnitTests for CopyOnWriteArrayLists
2022-04-09 03:56:54 +02:00
Speiger 3cac3a997e And hopefully the last javaDoc fixes 2022-04-08 00:24:37 +02:00
Speiger 3ffb001c73 More fixes
-Fixed: More javadoc fixes
-Fixed: BaseIntIterableTest no longer uses a deprecated function
2022-04-08 00:13:51 +02:00
Speiger 2810a6f952 Small fixes
-Fixed: JavaDoc
-Changed: callback is now called onCompletion
2022-04-08 00:00:45 +02:00
Speiger 166362334b Added gradle now uses the java version it runs on. 2022-04-07 20:26:53 +02:00
Speiger d3f9103ebf Adding Logger for testings 2022-04-07 20:19:47 +02:00
Speiger 1c5507d4a5 Switching to local properties 2022-04-07 20:16:59 +02:00
Speiger 5e3cd9f484 Trying out something with github actions 2022-04-07 20:14:23 +02:00
Speiger f27b884b6a Moving to a more up to date system.
-Changed: Moved to gradle 7.3 for java17 support of the project.
-Changed: Moved to maven-publish plugin and added a bit more info to the poms.
2022-04-07 16:00:58 +02:00
Speiger 769a9d8ea5 Upgraded gradle version to 6.3 for a test 2022-04-07 13:32:04 +02:00
Speiger 9499a7f0e0 Setup matrix so multiple java versions are tested. 2022-04-07 13:27:12 +02:00
Speiger ca38583f96 Fixed Java11 Incompat 2022-04-07 00:14:09 +02:00
Speiger 9557a0cfb5 Merge branch 'master' of git@github.com:Speiger/Primitive-Collections.git 2022-04-07 00:08:05 +02:00
Speiger c61e8bb7fc New Features
- Added: addOrGet for sets.
- Added: Async API which allows to easily execute Iterables/Collections
offthread without the complexity.
2022-04-07 00:06:49 +02:00
SpeigerandSpeiger 4fbcaa47f8 Update README.md 2022-04-07 00:06:19 +02:00
Speiger 6f31fc5abb New Features
- Added: addOrGet for sets.
- Added: Async API which allows to easily execute Iterables/Collections
offthread without the complexity.
2022-04-07 00:04:52 +02:00
SpeigerandGitHub 10ec0e35d0 Update README.md 2021-12-27 21:29:51 +01:00
Speiger 29c4d253cf Disabling badge 2021-12-27 21:28:07 +01:00
Speiger 55c870d392 Adding Build Passing badge 2021-12-27 21:22:57 +01:00
SpeigerandGitHub cda6ec066d Adding Build Validation
Create gradle.yml
2021-12-27 20:38:55 +01:00
Speiger c8b89e6847 Renaming file for what the action did. 2021-12-27 20:34:15 +01:00
Speiger b46a739008 Finishing Build Action 2021-12-27 20:28:45 +01:00
Speiger af62394651 Testing for secrets to be present 2021-12-27 20:04:50 +01:00
SpeigerandGitHub bc75a5cd97 Merge pull request #8 from Speiger/master
Moving Credentials Away from this file because now i need it
2021-12-27 20:00:58 +01:00
Speiger 7d8af3af08 Moving Credentials Away from this file because now i need it 2021-12-27 19:59:19 +01:00
SpeigerandGitHub ef8197b275 Update gradle.yml 2021-12-27 19:24:16 +01:00
SpeigerandGitHub 58d9ac7fdd Update gradle.yml 2021-12-27 19:21:59 +01:00
SpeigerandGitHub 86a893916d Update gradle.yml 2021-12-27 19:20:06 +01:00
SpeigerandGitHub e7a6292fe9 Update gradle.yml 2021-12-27 19:10:09 +01:00
SpeigerandGitHub 81209b0cf8 Update gradle.yml 2021-12-27 19:07:05 +01:00
SpeigerandGitHub 77b8147f9b Update gradle.yml 2021-12-27 19:05:33 +01:00
SpeigerandGitHub 32abd7e14e Update gradle.yml 2021-12-27 19:04:33 +01:00
SpeigerandGitHub 8a582f0b08 Create gradle.yml 2021-12-27 19:01:45 +01:00
SpeigerandGitHub 01be6f7d43 Delete gradle.yml 2021-12-27 18:56:49 +01:00
SpeigerandGitHub 9011700879 testing build only 2021-12-27 18:55:51 +01:00
SpeigerandGitHub 12cd4e5e5f Update gradle.yml 2021-12-27 18:50:24 +01:00
SpeigerandGitHub 10201bcadb hopefully this works 2021-12-27 18:44:47 +01:00
SpeigerandGitHub 3b4fcc0069 Merge pull request #6 from Speiger/actions
Update gradle.yml
2021-12-27 18:32:51 +01:00
SpeigerandGitHub 31a1ef74fb Update gradle.yml 2021-12-27 18:32:23 +01:00
SpeigerandGitHub 9be3a1475f another build try 2021-12-27 18:29:54 +01:00
SpeigerandGitHub 7591f396fd getting into github actions
Adding a build test
2021-12-27 18:18:24 +01:00
Speiger 517b84042f Version Bump 2021-12-26 01:58:22 +01:00
Speiger dbfae33074 Fixed Bug with FIFOQueue performance 2021-12-26 00:08:19 +01:00
Speiger ead34009c6 Added pourAsList and pourAsSet 2021-12-25 20:27:33 +01:00
Speiger 7a4a0f05d1 Added subFrom (which is the inverse of addTo) 2021-12-25 20:07:37 +01:00
Speiger 8f32b2d887 Merge remote-tracking branch 'Github/master' 2021-12-25 03:49:45 +01:00
Speiger e6c9600b40 Refactoring and Deprecating SortedMap/Sets
- Added: OrderedMap/Set
- Added: All Relevant functions into Ordered interface
- Changed: Marked all Relevant SortedMap/Set functions Deprecated until
0.6.0
- Fixed: All code that was relevant to this
2021-12-25 03:46:51 +01:00
SpeigerandGitHub d5f2acb9ab Update LICENSE 2021-12-19 21:19:28 +01:00
Speiger 3274e96355 Added Benchmark links 2021-12-16 14:03:39 +01:00
Speiger 78dfa286b0 New Version
- Fixed: Bugs with Queues starting with the wrong size
- Fixed: ArrayGrowth for Queues was +1 instead of +50%
- Added: Benchmarks with java and FastUtil
2021-12-16 13:46:55 +01:00
Speiger f32624d131 Build Release..
-Fixed: Doc error on gradle build.
-Fixed: SubSet.iterator had a ambiguity.
2021-12-14 09:05:25 +01:00
Speiger 59a417056c Added Missing method & fixed potential issue with TreeSetBiIterators 2021-12-13 13:56:28 +01:00
Speiger 18f6704ed7 Expanded Unit tests to IntLists/Sets
Maps are sadly not possible. It will require writing templates for
permutations effectively copying guavas Test library.
So this will take a lot longer
2021-12-13 13:45:35 +01:00
Speiger caf2f22e9f Finished the Basic Unit test frame work to ensure stablity.
-Added: 150k Unit tests.
-Fixed: Reworked the NavigableSet/Map implementations of RBTree/AVLTree/Array Sets/Maps
2021-12-13 10:41:20 +01:00
86 changed files with 11809 additions and 5651 deletions
+36
View File
@@ -0,0 +1,36 @@
# This workflow uses actions that are not certified by GitHub.
# They are provided by a third-party and are governed by
# separate terms of service, privacy policy, and support
# documentation.
# This workflow will build a Java project with Gradle and cache/restore any dependencies to improve the workflow execution time
# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-gradle
name: Latest Build
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
jobs:
build:
strategy:
fail-fast: false
matrix:
jdk: [8, 11, 14, 16, 17]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up JDK ${{ matrix.jdk }}
uses: actions/setup-java@v1
with:
java-version: ${{ matrix.jdk }}
- name: Validate Gradle wrapper
uses: gradle/wrapper-validation-action@e6e38bacfdf1a337459f332974bb2327a31aaf4b
- name: Make gradlew executable
run: chmod +x ./gradlew
- name: Build with Gradle
run: ./gradlew build
-1
View File
@@ -1,7 +1,6 @@
# ---> Gradle
.gradle
/build/
gradle.properties
# Ignore Gradle GUI config
gradle-app.setting
+57
View File
@@ -1,5 +1,62 @@
# Changelog of versions
### Version 0.6.2
- Added: Array only sorting function return the inputed array. This was done to allow for static final references to use the method in one go without having to make lambda wrappers. Cleaner code.
- Added: Iterator Wrappers are now a bit more in Compliance with Java Standards.
- Added: AsyncBuilders now Support Array Inputs to create cleaner code.
- Changed: LinkedList.addBulk variable definition was triggering a false positive.
- Fixed: TreeMap.subMap().entrySet().remove() wouldn't check primitives properly.
- Fixed: SortedMap.sub/tail/headMap were looping into themselves.
- Fixed: AbstractCollection.retainAll didn't push removed values through the consumer.
- Fixed: AbstractCollection.toArray wouldn't reset the last entry if the input array was larger then the elements in the collection.
- Fixed: SubList didn't check for ranges properly or didn't use parent list to validate changes.
- Fixed: ArrayList.addElements didn't check input array fully and used the wrong variable to move the elements around.
- Fixed: LinkedList.addElements(EmptyInput) would crash.
- Fixed: LinkedList.swapRemove didn't account for if the removed element was the prelast one.
- Fixed: LinkedList.removeElements would break the implementation if the list was almost empty and the middle element was removed.
- Fixed: LinkedHashSet.addAndMoveToFirst wouldn't move elements to the first place.
- Fixed: ArrayList/LinkedList extractElements crashing when 0 or less elements are desired.
- Fixed: TreeMap pollFirst/LastKey should return the defaultMin/max value instead of a Empty value.
- Fixed: TreeMap keySet implementation was missing the class type implementations to pass keySet tests.
- Fixed: TreeMap.SubMap Iterator (primitive Keys) was crashing because a Null was set on to a primitive.
### Version 0.6.1
- Fixed: FIFO queue crashing when the last index is before the first index when peek is called.
- Fixed: FIFO queue only clears the array if it was in use.
- Added: Sorted Method for the stream replacing functions.
### Version 0.6.0
- Added: addOrGet for sets.
- Added: Async API which allows to easily execute Iterables/Collections offthread without the complexity.
- Added: CopyOnWriteArrayList and tests for it
- Added: Support up to Java17.
- Added: Build System now adds module-info if the Running JVM is 9 or higher
- Added: ArrayList.of(Class, size) that allows you to allocate a size right at the creation of the List without having to create a wrapper array.
- Added: A ConcurrentHashMap implementation.
- Fixed: containsValue in the HashMap wouldn't check the nullKey
- Removed: Deprecated functions from SortedMaps/Sets
### Version 0.5.3
- Added: OrderedMap/Set
- Added: Deprecation to Functions that are specific to Ordered interfaces in the SortedMap/Set
- Added: subFrom to Maps which is the counterpart of the addTo method
- Added: pourAsList and pourAsSet (booleans excluded for sets) to Iterable
- Fixed: ArrayList.grow had a small bug where it would trigger to early causing performance problems with exact sized collections.
- Fixed: FIFOQueue size constructor had a small bug where it would trigger a array enlargement when all elements were inserted.
### Version 0.5.2
- Fixed: Bugs with Queues starting with the wrong size
- Fixed: ArrayGrowth for Queues was +1 instead of +50%
- Added: Benchmarks with java and FastUtil
### Version 0.5.1
- Fixed: Reworked the NavigableSet/Map implementations of RBTree/AVLTree/Array Sets/Maps so they are now deemed stable.
- Added: Another 150k Unit tests.
- Added: List and Set Unit tests for Integer (or Primitives in this case) to ensure basic stability there. (Now covering all sets and lists)
- Fixed: Bugs with null values for primitive collections.
- Removed: ArraySet/Map subSet/subMap implementation was removed.
### Version 0.5.0
- Added: 2 Helper functions to find out how many bits are required to store a Number.
- Added: pour function directly into Iterable which allows to collect all elements in the Iterable directly.
+168 -175
View File
@@ -1,208 +1,201 @@
Apache License
Apache License
Version 2.0, December 2021
http://www.apache.org/licenses/
Version 2.0, January 2021
http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION,
AND DISTRIBUTION
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"License" shall mean the terms and conditions for use, reproduction, and distribution
as defined by Sections 1 through 9 of this document.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Licensor" shall mean the copyright owner or entity authorized by the copyright
owner that is granting the License.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Legal Entity" shall mean the union of the acting entity and all other entities
that control, are controlled by, or are under common control with that entity.
For the purposes of this definition, "control" means (i) the power, direct
or indirect, to cause the direction or management of such entity, whether
by contract or otherwise, or (ii) ownership of fifty percent (50%) or more
of the outstanding shares, or (iii) beneficial ownership of such entity.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions
granted by this License.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
"Source" form shall mean the preferred form for making modifications, including
but not limited to software source code, documentation source, and configuration
files.
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
"Object" form shall mean any form resulting from mechanical transformation
or translation of a Source form, including but not limited to compiled object
code, generated documentation, and conversions to other media types.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
"Work" shall mean the work of authorship, whether in Source or Object form,
made available under the License, as indicated by a copyright notice that
is included in or attached to the work (an example is provided in the Appendix
below).
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
"Derivative Works" shall mean any work, whether in Source or Object form,
that is based on (or derived from) the Work and for which the editorial revisions,
annotations, elaborations, or other modifications represent, as a whole, an
original work of authorship. For the purposes of this License, Derivative
Works shall not include works that remain separable from, or merely link (or
bind by name) to the interfaces of, the Work and Derivative Works thereof.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
"Contribution" shall mean any work of authorship, including the original version
of the Work and any modifications or additions to that Work or Derivative
Works thereof, that is intentionally submitted to Licensor for inclusion in
the Work by the copyright owner or by an individual or Legal Entity authorized
to submit on behalf of the copyright owner. For the purposes of this definition,
"submitted" means any form of electronic, verbal, or written communication
sent to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems, and
issue tracking systems that are managed by, or on behalf of, the Licensor
for the purpose of discussing and improving the Work, but excluding communication
that is conspicuously marked or otherwise designated in writing by the copyright
owner as "Not a Contribution."
Copyright 2021 Speiger
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf
of whom a Contribution has been received by Licensor and subsequently incorporated
within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this
License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive,
no-charge, royalty-free, irrevocable copyright license to reproduce, prepare
Derivative Works of, publicly display, publicly perform, sublicense, and distribute
the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License,
each Contributor hereby grants to You a perpetual, worldwide, non-exclusive,
no-charge, royalty-free, irrevocable (except as stated in this section) patent
license to make, have made, use, offer to sell, sell, import, and otherwise
transfer the Work, where such license applies only to those patent claims
licensable by such Contributor that are necessarily infringed by their Contribution(s)
alone or by combination of their Contribution(s) with the Work to which such
Contribution(s) was submitted. If You institute patent litigation against
any entity (including a cross-claim or counterclaim in a lawsuit) alleging
that the Work or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses granted to You
under this License for that Work shall terminate as of the date such litigation
is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or
Derivative Works thereof in any medium, with or without modifications, and
in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy
of this License; and
(b) You must cause any modified files to carry prominent notices stating that
You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute,
all copyright, patent, trademark, and attribution notices from the Source
form of the Work, excluding those notices that do not pertain to any part
of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution,
then any Derivative Works that You distribute must include a readable copy
of the attribution notices contained within such NOTICE file, excluding those
notices that do not pertain to any part of the Derivative Works, in at least
one of the following places: within a NOTICE text file distributed as part
of the Derivative Works; within the Source form or documentation, if provided
along with the Derivative Works; or, within a display generated by the Derivative
Works, if and wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and do not modify the
License. You may add Your own attribution notices within Derivative Works
that You distribute, alongside or as an addendum to the NOTICE text from the
Work, provided that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and may provide
additional or different license terms and conditions for use, reproduction,
or distribution of Your modifications, or for any such Derivative Works as
a whole, provided Your use, reproduction, and distribution of the Work otherwise
complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any
Contribution intentionally submitted for inclusion in the Work by You to the
Licensor shall be under the terms and conditions of this License, without
any additional terms or conditions. Notwithstanding the above, nothing herein
shall supersede or modify the terms of any separate license agreement you
may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names,
trademarks, service marks, or product names of the Licensor, except as required
for reasonable and customary use in describing the origin of the Work and
reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to
in writing, Licensor provides the Work (and each Contributor provides its
Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied, including, without limitation, any warranties
or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR
A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness
of using or redistributing the Work and assume any risks associated with Your
exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether
in tort (including negligence), contract, or otherwise, unless required by
applicable law (such as deliberate and grossly negligent acts) or agreed to
in writing, shall any Contributor be liable to You for damages, including
any direct, indirect, special, incidental, or consequential damages of any
character arising as a result of this License or out of the use or inability
to use the Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all other commercial
damages or losses), even if such Contributor has been advised of the possibility
of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work
or Derivative Works thereof, You may choose to offer, and charge a fee for,
acceptance of support, warranty, indemnity, or other liability obligations
and/or rights consistent with this License. However, in accepting such obligations,
You may act only on Your own behalf and on Your sole responsibility, not on
behalf of any other Contributor, and only if You agree to indemnify, defend,
and hold each Contributor harmless for any liability incurred by, or claims
asserted against, such Contributor by reason of your accepting any such warranty
or additional liability. END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate
notice, with the fields enclosed by brackets "[]" replaced with your own identifying
information. (Don't include the brackets!) The text should be enclosed in
the appropriate comment syntax for the file format. We also recommend that
a file or class name and description of purpose be included on the same "printed
page" as the copyright notice for easier identification within third-party
archives.
Copyright 2021 Speiger
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+47 -82
View File
@@ -1,93 +1,51 @@
![build](https://github.com/Speiger/Primitive-Collections/actions/workflows/build_validator.yml/badge.svg)
[![Latest Release](https://jitpack.io/v/Speiger/Primitive-Collections.svg)](https://jitpack.io/#Speiger/Primitive-Collections)
[![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
![GitHub commit activity](https://img.shields.io/github/commit-activity/m/Speiger/Primitive-Collections)
# Primitive-Collections
This is a Simple Primitive Collections Library aimed to outperform Java's Collection Library and FastUtil.
Both in Performance and Quality of Life Features.
This is a Simple Primitive Collections Library i started as a hobby Project.
It is based on Java's Collection Library and FastUtil.
But its focus is a different one.
## Benchmarks
Benchmarks can be found here: [[Charts]](https://github.com/Speiger/Primitive-Collections-Benchmarks/blob/master/BENCHMARKS-CHARTS.md), [[Tables]](https://github.com/Speiger/Primitive-Collections-Benchmarks/blob/master/BENCHMARKS.md)
## Special Features
[Here](features.md) you find a set of features added to Primitive Collections.
These are designed to improve performance or to provide Quality of Life.
## Main Features:
- ArrayLists / LinkedLists
- HashSet/Map (Linked & HashControl)
- TreeSet/Map (RB & AVL)
- EnumMap
- ArrayLists / LinkedLists / CopyOnWriteLists
- HashSets/Maps (Linked & HashControl)
- TreeSets/Maps (RB & AVL)
- EnumMaps
- Immutable Maps/Lists/Sets
- Priority Queue
- ConcurrentHashMaps
- Priority Queues
- Streams & Functional Queries
- SplitIterators
- Iterators
- Split/Iterators
- Pairs
- Unary/Functions
- Suppliers
- Bi/Consumers
## Current Level of Stability
Since this is a relatively new Library, stability was not perfect and some areas are not perfect yet.
Thanks to [ben-manes](https://github.com/ben-manes) we now have Roughly 16000 test covering Maps/Sets/Lists.
These tests cover Javas Collection API completely and ensuring a Stable implementation.
These freshly added tests allowed me to squash thousands of issues according to Googles Test Library (Guava-Tests).
These will be expanded on as time goes on.
One know aspect of Instability is SubSets and SubMaps. They require full rewrites to be fully stable.
So it is not advised to use them until these issues are addressed.
PriorityQueues are tested separately and ensure basic functionality though GuavaTests are planned.
They just require a custom test implementation.
As a summary: Stability is good/excellent, unless you need SubSets/SubMaps
## Specialized Functions
New Specialized functions that were added to increase performance or reduce allocations or Quality Of life.
To highlight things that may be wanted.
- Iterable:
- map/flatMap/arrayFlatMap: A Light weight version of Stream.map().
- findFirst: Allows to find the first element of a Predicated Iterable.
- filter: Allows to filter unwanted elements for wrapped Iterable
- matchAny/matchNone/matchAll: Allows to find elements in a collection.
- count: counts all valid elements in a collection.
- forEach: Allows to input a second element into a forEach move allowing for more flexibility for Method References
- reduce/limit/peek/distinct: Light Versions of the Stream variant, to reduce Stream usage.
- pour: a function that allows to collect all elements within the Collection
- Collection:
- containsAny: Allows to test if another collection contains an of the elements of the tested collection.
- primitiveStream: Provides access to the closest Java Stream Type.
- copy: shallowCopies the collection, used instead of clone because this is better to use.
(subCollections not supported for obvious reasons)
- toArray: the ToArray function from Java9 and newer that uses a Functional interface and can use a method reference
- List:
- add/get/removeElements (From FastUtil): Allows to add/get/remove an Array into/from a list. Just with less overhead
- extractElements: Allows to remove a Range of elements from the List and get what was removed.
- Unstable Sort(From FastUtil): Uses a faster but not stable sort (Quick-Sort as example) to sort the list.
- addIfAbsent/Present: adds a element only if absent/present in the list
- swapRemove: deletes a desired element and inserts the last element in its place instead of leftshifting elements.
- SortedSet:
- addAndMoveToFirst/Last (From FastUtil but moved to Interface): Allows to add a element to the first/last position of a sorted set.
- moveToFirst/Last: Moves the desired element at the first/last position of the SortedSet.
- pollFirst/Last: Allows to poll the first/last element of the set.
- Map:
- putAll: putAll but in Array form.
- putAllIfAbsent: Puts only the elements that are absent.
- addTo (Only Primitives Values) (From FastUtil but moved to Interface): allows to add to the value of a given key. If not present it will be added. (Accumulator)
- addToAll: Same as addTo but bulkVersion.
- removeOrDefault: removes a Element and if not present returns the default value instead of the present value.
- mergeAll: BulkVersion of Merge function.
- supplyIfAbsent: A Supplier based computeIfAbsent
- Sorted Map:
- addAndMoveToFirst/Last (From FastUtil but moved to Interface): Allows to add a element to the first/last position of a sorted Map.
- moveToFirst/Last: Moves the desired element at the first/last position of the Map.
- getAndMoveToFirst/Last: gets the element and moves it to the first/last position. Replicating a Optional LinkedHashMap feature.
- pollFirst/LastKey: Allows to poll the first/last element.
- first/LastValue: Allows to get the first/last value from the Map.
- AsyncBuilders
# Notes about Versions
Any 0.x.0 version (Minor) can be reason for massive changes including API.
To ensure that problems can be dealt with even if it is breaking the current API.
Any breaking changes will be Documented (once 1.0 is released)
Also to save space every 0.0.x (Patch) that is 2 Minor Versions behind will be removed.
So if 0.5.0 is released every 0.3.x patch will be deleted, except for the last patch for that minor version.
# How to install
Using Gradle:
Using Jitpack Gradle
```gradle
repositories {
maven {
url = "https://jitpack.io"
}
}
dependencies {
implementation 'com.github.Speiger:Primitive-Collections:0.6.2'
}
```
Using Custom Gradle:
```gradle
repositories {
maven {
@@ -95,13 +53,22 @@ repositories {
}
}
dependencies {
compile 'de.speiger:Primitive-Collections:0.5.0'
implementation 'de.speiger:Primitive-Collections:0.6.2'
}
```
Direct:
<details>
<summary>Direct: </summary>
<p>
| Version | Jar | Sources | Java Doc |
|--------- |------------------------------------------------------------------------------------------------------------------------------ |-------------------------------------------------------------------------------------------------------------------------------------- |-------------------------------------------------------------------------------------------------------------------------------------- |
| 0.6.2 | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.6.2/Primitive-Collections-0.6.2.jar) | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.6.2/Primitive-Collections-0.6.2-sources.jar) | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.6.2/Primitive-Collections-0.6.2-javadoc.jar) |
| 0.6.1 | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.6.1/Primitive-Collections-0.6.1.jar) | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.6.1/Primitive-Collections-0.6.1-sources.jar) | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.6.1/Primitive-Collections-0.6.1-javadoc.jar) |
| 0.6.0 | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.6.0/Primitive-Collections-0.6.0.jar) | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.6.0/Primitive-Collections-0.6.0-sources.jar) | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.6.0/Primitive-Collections-0.6.0-javadoc.jar) |
| 0.5.3 | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.5.3/Primitive-Collections-0.5.3.jar) | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.5.3/Primitive-Collections-0.5.3-sources.jar) | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.5.3/Primitive-Collections-0.5.3-javadoc.jar) |
| 0.5.2 | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.5.2/Primitive-Collections-0.5.2.jar) | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.5.2/Primitive-Collections-0.5.2-sources.jar) | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.5.2/Primitive-Collections-0.5.2-javadoc.jar) |
| 0.5.1 | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.5.1/Primitive-Collections-0.5.1.jar) | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.5.1/Primitive-Collections-0.5.1-sources.jar) | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.5.1/Primitive-Collections-0.5.1-javadoc.jar) |
| 0.5.0 | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.5.0/Primitive-Collections-0.5.0.jar) | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.5.0/Primitive-Collections-0.5.0-sources.jar) | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.5.0/Primitive-Collections-0.5.0-javadoc.jar) |
| 0.4.5 | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.4.5/Primitive-Collections-0.4.5.jar) | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.4.5/Primitive-Collections-0.4.5-sources.jar) | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.4.5/Primitive-Collections-0.4.5-javadoc.jar) |
| 0.4.4 | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.4.4/Primitive-Collections-0.4.4.jar) | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.4.4/Primitive-Collections-0.4.4-sources.jar) | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.4.4/Primitive-Collections-0.4.4-javadoc.jar) |
@@ -111,6 +78,9 @@ Direct:
| 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) |
</p>
</details>
# Contributing
If you want to contribute.
This project is created using gradle and java and my Template Library only. Nothing extra.
@@ -129,10 +99,5 @@ Please if you want to contribute follow the [Rule-Sheet](RuleSheet.md). It keeps
The SourceCode can be generated via:
/gradlew.bat generateSource
to build the jar:
to generate SourceCode and build the jar:
/gradlew.bat build
do not combine the commands because they can not be executed at the same time.
## Current Down Sides (Random order)
- SubMaps/Set implementation isn't perfect right now. This will be addressed slowly due to rewrites required.
- Documentation is only present at the lowest level for most cases and needs a typo fixing.
+49 -19
View File
@@ -8,7 +8,7 @@ tasks.withType(JavaCompile) {
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'maven'
apply plugin: 'maven-publish'
repositories {
mavenCentral()
@@ -18,9 +18,11 @@ repositories {
}
archivesBaseName = 'Primitive Collections'
version = '0.5.0';
version = '0.6.2';
sourceCompatibility = targetCompatibility = compileJava.sourceCompatibility = compileJava.targetCompatibility = '1.8'
sourceCompatibility = targetCompatibility = compileJava.sourceCompatibility = compileJava.targetCompatibility = JavaVersion.current();
System.out.println("Java Version: "+compileJava.sourceCompatibility)
javadoc {
options.tags = [ "implSpec", "note" ]
@@ -42,8 +44,7 @@ configurations {
}
dependencies {
builderCompile 'de.speiger:Simple-Code-Generator:1.0.5'
runtimeOnly 'de.speiger:Simple-Code-Generator:1.0.5'
builderImplementation 'de.speiger:Simple-Code-Generator:1.0.7'
testImplementation 'junit:junit:4.12'
testImplementation 'com.google.guava:guava-testlib:31.0.1-jre'
@@ -56,6 +57,14 @@ task generateSource(type: JavaExec) {
main = 'speiger.src.builder.PrimitiveCollectionsBuilder'
}
task generateGithubSource(type: JavaExec) {
group = 'internal'
description = 'Builds the sourcecode for Github Actions'
classpath = sourceSets.builder.runtimeClasspath
main = 'speiger.src.builder.PrimitiveCollectionsBuilder'
args = ['false', 'true']
}
task forceGenerateSource(type: JavaExec) {
group = 'internal'
description = 'Builds the sourcecode forceful'
@@ -74,6 +83,8 @@ task srcJar(type: Jar) {
classifier = 'sources'
}
compileJava.dependsOn generateGithubSource
javadoc.failOnError = false
javadoc.options.memberLevel = JavadocMemberLevel.PUBLIC
javadoc.options.quiet()
@@ -87,19 +98,23 @@ test {
useJUnit()
}
uploadArchives {
repositories.mavenDeployer {
repository(url: 'https://maven.speiger.com/repository/main') {
authentication(userName: project.properties.mavenUser, password: project.properties.mavenPassword)
}
snapshotRepository(url: 'https://maven.speiger.com/repository/main') {
authentication(userName: project.properties.mavenUser, password: project.properties.mavenPassword)
}
pom {
version = project.version
artifactId = project.archivesBaseName.replace(" ", "-")
groupId = 'de.speiger'
project {
publishing {
Properties props = new Properties()
if(file("$buildDir/credentials.properties").exists()) {
props.load(new FileInputStream("$buildDir/credentials.properties"))
}
publications {
mavenJava(MavenPublication) {
pom {
name = 'Primitive Collections'
description = 'A Primitive Collection library that reduces memory usage and improves performance'
url = 'https://github.com/Speiger/Primitive-Collections'
version = project.version
artifactId = project.archivesBaseName.replace(" ", "-")
groupId = 'de.speiger'
from components.java
artifact tasks.srcJar
artifact tasks.javadocJar
licenses {
license {
name = 'The Apache License, Version 2.0'
@@ -110,9 +125,24 @@ uploadArchives {
developer {
id = 'speiger'
name = 'Speiger'
email = 'speiger@gmx.net'
}
}
scm {
url = 'https://github.com/Speiger/Primitive-Collections'
}
issueManagement {
system = 'github'
url = 'https://github.com/Speiger/Primitive-Collections/issues'
}
}
}
}
repositories {
maven {
url version.endsWith('SNAPSHOT') ? "https://maven.speiger.com/repository/debug" : "https://maven.speiger.com/repository/main"
credentials(PasswordCredentials) {
username props.mavenUser
password props.mavenPassword
}
}
}
+402
View File
@@ -0,0 +1,402 @@
## Quality Of Life Features
New Specialized functions/classes that were added to increase performance and/or reduce allocations and/or for Quality of life.
# Functions
Functions that increase performance or are quality of life in their nature.
<details>
<summary>Iterable</summary>
<p>
## Functional Functions
Java adds themselves a lot of functional functions like,
- Stream:
- Map/FlatMap
- Filter/Distinct/Limit/Sorted
- Count/FindFirst/Collect
- Peek/ForEach/Reduce
- anyMatch/allMatch/NoneMatch
that allows to process a collection in a functional way.
But these require streams which have a lot of Overhead in their nature.
Luckly Primitive Collections adds replacement functions that provide the same functionality but with minimal overhead.
Here are some examples:
```java
public ObjectIterable<Path> toPath(ObjectIterable<String> iterable) {
return iterable.map(Paths::get).filter(Files::exist);
}
public Iterable<Path> toPath(Iterable<String> iterable) {
return ObjectIterables.map(iterable, Paths::get).filter(Files::exist);
}
public int sum(IntIterable iterable) {
return iterable.reduce(Integer::sum);
}
```
## AsyncAPI</summary>
The AsyncAPI is a Feature that simplifies the processing of Collections on a separate thread.
It uses the same concept as Javas Stream API but uses the light weight Functions from Primitive Collections to achieve the same thing.
Unlike Javas StreamAPI the AsyncAPI is always singleThreaded and more like Javas CompletableFuture, which you can await or let run Asynchronous.
The Goal is it to simplify the processing of Collections asynchronous.
Especially on tasks which don't have to be finished instantly but can be processed on the side.
Here is a example of how the API works.
```java
public void processFiles(ObjectCollection<String> potentialFiles) {
potentialFiles.asAsync()
.map(Paths::get).filter(Files::exists) //Modifies the collection (Optional)
.forEach(Files::delete) //Creates the action (Required)
.callback(T -> {}} //Callback on completion, still offthread (Optional)
.execute() //Starts the task. (Required)
}
```
</p>
</details>
<details>
<summary>Collection</summary>
<p>
These are functions specific to the Collections interface, stuff that everyone wished it was present to be in the first place.
## AddAll (Array)
Adding Elements to a Collection usually requires either a for loop or a Arrays.wrap().
This isn't an issue with Primitive Collections.
```java
public void addMonths(ObjectCollection<String> months) {
months.addAll("January", "February", "March", "April", "May", "June", "July", "August", "September, "October", November", "December");
}
public void addElements(ObjectCollection<String> result, String[] elements) {
result.addAll(elements, 0, 5); //elements, offset, length
}
```
## containsAny
Everyone hates comparing if 2 collections have part of each other included.
The solution usually requires for loops and keeping track if things were found or not.
And every Java Developer had this issue at least once and wished for a clean solution.
```java
public boolean hasMonths(ObjectCollection<Month> target, Collection<Month> toFind) {
return target.containsAny(toFind);
}
```
## Copy
Collections get copied every now and then. There is only 2 ways that this happens.
Javas Clone API or using Constructor that supports collections.
Javas Clone API is kinda in a Zombie state, where it is supported or not. Its not really clear if you should use it or not.
The Clone CloneNotSupportedException isn't helping either, causing more janky code.
While a Constructor can only support so much and testing for every case isn't really viable.
So the decision was made to straight out not support clone and instead add a copy function which doesn't use a checked exception.
It works exactly like the clone function. In a sense where it creates a shallow copy. (SubCollections do not work for obvious reasons)
```java
public IntCollection copy(IntCollection original) {
return original.copy();
}
```
## Primitive Streams
Since Javas Stream API is still really useful, even at its shortcomings, Primitive Collections provides easy access to it.
Generic Streams and the closest Primitive Stream will be provided. So a FloatCollection goes to a DoubleStream.
```java
public IntStream createStream(IntCollection source) {
return source.primitiveStream();
}
```
## RemoveAll/RetainAll with listener
Ever wanted use removeAll or retainAll and wanted to know what elements actually got deleted?
The usual solution is to create a copy and then apply it to the original and cross reference them.
Which leads to really messy code and just hasn't a clean solution.
Luckly Primitive Collections got you covered.
```java
public void removeInvalidFiles(ObjectCollections<Path> files, ObjectCollection<Path> toRemove) {
files.removeAll(toRemove, T -> System.out.println(T));
}
public void removeInvalidFiles(ObjectCollections<Path> files, ObjectCollection<Path> toKeep) {
files.retainFiles(toKeep, T -> System.out.println(T));
}
```
## ToArray
Primitive Collections supports primitive/generic toArray functions for its Primitive Collections.
On top of that the Object side gets a Java9 function ported back to java8, which uses a functional Interface to create the backing array.
```java
public Integer[] toArray(IntCollection c) {
return c.toArray(new Integer[c.size]);
}
public int[] toArray(IntCollection c) {
return c.toIntArray();
}
public String[] toArray(ObjectCollection<String> c) {
return c.toArray(String::new);
}
```
</p>
</details>
<details>
<summary>List</summary>
<p>
These functions are List specific functions, a couple of these are from FastUtil.
## add/get/remove/extractElements
These functions really useful helper functions. 3 of which are copied from FastUtil. (extract is from Primitive Collections)
They are basically array forms of addAll, getAll, removeRange and removeAndGetRange. This is the simplest way to describe it.
Here some example:
```java
public void addAll(DoubleList list) {
list.addElements(0D, 12.2D, 3.5D, 4.2D);
}
public double[] getAll(DoubleList list, int amount) {
double[] result = new double[amount];
list.getElements(0, result);
return result;
}
public void removeRange(FloatList list) {
list.removeElements(5, 14);
}
public float[] extractRange(FloatList list) {
return list.extractElements(5, 14); //Returns the removed elements
}
```
## addIfPresent/addIfAbsent
These two functions are simple helper functions that check internally if a element is present or absent before adding them to the List.
Removing the need for a contains or indexOf check every time you want to add a element.
While it is of course better to use a set, there is cases where this is still useful.
```java
public void addElements(IntList list, int... numbersToAdd) {
for(int e : numbersToAdd) {
list.addIfAbsent(e);
}
}
public void addExisting(ObjectList<String> list, String... textToAdd) {
for(String s : textToAdd) {
list.addIfPresent(s);
}
}
```
## SwapRemove
Lists when removing a Element shift usually the backing array to the left based to shrink the elements.
While that isn't computational expensive with LinkedLists, it is with ArrayLists.
Here comes swapRemove into play, which just removes the desired elements and instead of shifting left puts the last element in its place.
This reduces the data copying required down to 1 element instead of an array.
```java
public int remove(IntList elements, int indexToRemove) {
return elements.swapRemove(indexToRemove);
}
```
## Unstable Sort (From FastUtil)
Unstable Sort uses a Faster but not as stable sorting algorithm to sort the Collection.
Stable doesn't mean crashing, but more like that the result isn't exactly perfectly sorted.
```java
public void sort(List<Month> list, Comparator<Month> sorter) {
list.unstableSort(sorter);
}
```
</p>
</details>
<details>
<summary>Map</summary>
<p>
These functions are based on the Map interface. Useful functions you really would want.
## addTo/subFrom
addTo (from FastUtil) and subFrom are mathematically functions that either add or subtract from the value of a given key.
And if the key isn't present or would result in the default value it will either add or remove the entry from the Map. Given the circumstance.
This is a really useful function and I wish FastUtil made it accessible by default but sadly it isn't.
To simplify the explanation:
- addTo if no element is present puts in the desired number, otherwise it sums up the two values.
- subFrom if a element is present subtracts from it, if the element reaches the default value it removes the element from the map. If not present it will be ignored.
```java
public void addTo(Object2DoubleMap<Month> map, Month key, double averageTrainsRepaired) {
map.addTo(key, averageTrainsRepaired);
}
public void subFrom(Long2IntMap map, long key, double amount) {
map.subFrom(key, amount);
}
```
## addToAll
Simple bulk version of the addTo function since sometimes you want to merge 2 maps for summing.
Especially if your work is multi-threaded this can become useful.
```java
public void addTo(Object2DoubleMap<Month> map, Object2DoubleMap<Month> trainsRepaired) {
map.addToAll(trainsRepaired);
}
```
## mergeAll
This is a simple bulk version of merge since merging 2 maps is more frequent then people might think and leads to cleaner code too.
```java
public void merge(Long2ByteMap result, Long2ByteMap toMerge) {
result.mergeAll(toMerge);
}
```
## putAll (Array)
This allows to put keys and values as arrays instead of requiring a WrapperMap to insert the elements.
Not as useful as the Collections.addAll variant but still really useful.
```java
public void putAll(Int2DoubleMap map, int[] keys, double[] values) {
map.put(keys, values, 2, 15);
}
```
## putAllIfAbsent
putAll has this usual quirk where if a element is present it will replace the value, and sometimes this is not wanted.
While putIfAbsent exists it has no real mass form and makes iterative solutions really uneasy to use.
Here comes the helper function that gets rid of that problem.
```java
public void merge(Long2ObjectMap<String> regionFiles, Long2ObjectMap<String> toAdd) {
regionFiles.putAllIfAbsent(toAdd);
}
```
## removeOrDefault
getOrDefault is a really useful function that find use cases all the time.
Sadly by default there is no variant of removeOrDefault, while it has less cases still could be used every now and then.
This function basically tries to remove a element, if it is not present it will just return your desired default.
```java
public Path removeCache(Long2ObjectMap<Path> caches, long key) {
return caches.removeOrDefault(key, Paths.get("nuclearFun"));
}
```
## supplyIfAbsent
This one is one of my favorites. computeIfAbsent is a really useful function.
But in 90% of the cases I use it the value is a collection.
This becomes really annoying since methodReferences are faster/cleaner then Lambdas in my opinion.
supplyIfAbsent is basically computeIfAbsent but without a key, perfect for the default constructor of a collection.
This is the whole reason it exists.
```java
public void example(Int2ObjectMap<List<String>> map, Int2ObjectMap<String> toAdd) {
for(Entry<String> entry : toAdd.entrySet()) {
map.supplyIfAbsent(entry.getKey(), ObjectArrayList::new).add(entry.getValue());
}
}
```
</p>
</details>
# Interfaces
Interfaces that provide essential or quality of life features.
<details>
<summary>ITrimmable</summary>
<p>
The ITrimmable is Accessor interface that allows you to access a couple helper functions to control the size of your collections.
This was created for the constant casting requirement to implementations just to shrink collections which get annoying over time.
## trim
This function basically trims down the backing implementation to use as little memory as required to store the elements in the collection.
Optionally a desired minimum size can be provided as of how low it should go at worst.
## clearAndTrim
when you want to reset a Collection completely you have 2 options. Clear it and then call trim, or recreate the collection.
clearAndTrim solves this problem by clearing the collection and trimming it in one go, reducing overhead to achieve such a thing.
</p>
</details>
<details>
<summary>IArray</summary>
<p>
IArray is a Accessor interface that provides more access to collections by providing tools to grow your collection as needed.
While putAll/addAll try to ensure that you have enough room for your elements, this is not really a solution for all cases.
Sometimes you need to ensure the Collection is pre-initialized.
IArray grants you that control.
There is also a type specific that provides you access to the backing array implementation of Lists for faster Iteration but that is a really specific case.
## ensureCapacity
Ensures that your collection has enough storage for the elements you want to insert.
## elements (ITypeSpecificArray)
Allows you access to the backing array of a List which is for people who know what they are doing.
There is a lambda version of this function too which makes sure for synchronizedLists that you are the only one accessing the array.
</p>
</details>
<details>
<summary>OrderedMap</summary>
<p>
The OrderedMap is a real edge case interface that was born for a need.
FastUtil added functions that were like moveToFirst which were hardcoded to the implementation.
They didn't fit into something like a SortedMap because the Set wasn't sorted.
So OrderedMap was born, which isn't random but ordered in a specific way that can be changed.
## getAndMoveToFirst/getAndMoveToLast
Returns a desired element and removing it to the first/last spot in the Map. Moving the element that was at its spot after/before it.
## moveToFirst/moveToLast
Moves the element if present to the first/last spot in the Map. Moving the element that was at its spot after/before it.
Returns true if the element was actually moved.
## putAndMoveToFirst/putAndMoveToLast
Adds the desired element and moves it to first/last spot in the Map. Moving the element that was at its spot after/before it.
## firstKey/lastKey (Optional poll)
Provides access to the current first/last key of the Map.
Optionally can be polled if desired.
## firstValue/lastValue
Provides access to the current first/last value of the Map.
</p>
</details>
<details>
<summary>OrderedSet</summary>
<p>
The OrderedSet is a real edge case interface that was born for a need.
FastUtil added functions that were like moveToFirst which were hardcoded to the implementation.
They didn't fit into something like a SortedSet because the Set wasn't sorted.
So OrderedSet was born, which isn't random but ordered in a specific way that can be changed.
## addAndMoveToFirst/addAndMoveToLast
Adds the desired element and moves it to first/last spot in the Collection. Moving the element that was at its spot after/before it.
## moveToFirst/moveToLast
Moves the element if present to the first/last spot in the Collection. Moving the element that was at its spot after/before it.
Returns true if the element was actually moved.
## first/last (Optional poll)
Provides access to the current first/last element of the set.
Optionally can be polled if desired.
</p>
</details>
+1
View File
@@ -0,0 +1 @@
org.gradle.jvmargs=-Xmx3G
+1 -1
View File
@@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.0-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-7.3-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
+6
View File
@@ -0,0 +1,6 @@
jdk:
- openjdk9
install:
- chmod +x ./gradlew
- ./gradlew build publishToMavenLocal
@@ -158,6 +158,8 @@ public class GlobalVariables
//Final Classes
addClassMapper("ARRAY_LIST", "ArrayList");
addAbstractMapper("COPY_ON_WRITE_LIST", "CopyOnWrite%sArrayList");
addClassMapper("ASYNC_BUILDER", "AsyncBuilder");
addClassMapper("LINKED_LIST", "LinkedList");
addAbstractMapper("IMMUTABLE_LIST", "Immutable%sList");
addClassMapper("ARRAY_FIFO_QUEUE", "ArrayFIFOQueue");
@@ -172,6 +174,7 @@ public class GlobalVariables
addBiClassMapper("LINKED_CUSTOM_HASH_MAP", "LinkedOpenCustomHashMap", "2");
addBiClassMapper("LINKED_HASH_MAP", "LinkedOpenHashMap", "2");
addBiClassMapper("CUSTOM_HASH_MAP", "OpenCustomHashMap", "2");
addBiClassMapper("CONCURRENT_HASH_MAP", "ConcurrentOpenHashMap", "2");
addBiClassMapper("AVL_TREE_MAP", "AVLTreeMap", "2");
addBiClassMapper("RB_TREE_MAP", "RBTreeMap", "2");
addFunctionValueMappers("LINKED_ENUM_MAP", valueType.isObject() ? "LinkedEnum2ObjectMap" : "LinkedEnum2%sMap");
@@ -191,6 +194,7 @@ public class GlobalVariables
addAbstractMapper("ABSTRACT_LIST", "Abstract%sList");
addAbstractBiMapper("ABSTRACT_MAP", "Abstract%sMap", "2");
addClassMapper("SUB_LIST", "SubList");
addAbstractMapper("BASE_TASK", "Base%sTask");
//Helper Classes
addClassMapper("LISTS", "Lists");
@@ -218,7 +222,9 @@ public class GlobalVariables
addClassMapper("LIST_ITER", "ListIter");
addClassMapper("LIST", "List");
addBiClassMapper("NAVIGABLE_MAP", "NavigableMap", "2");
addBiClassMapper("ORDERED_MAP", "OrderedMap", "2");
addBiClassMapper("SORTED_MAP", "SortedMap", "2");
addBiClassMapper("CONCURRENT_MAP", "ConcurrentMap", "2");
addBiClassMapper("MAP", "Map", "2");
addClassMapper("NAVIGABLE_SET", "NavigableSet");
addBiClassMapper("PAIR", "Pair", "");
@@ -226,11 +232,13 @@ public class GlobalVariables
addClassMapper("PRIORITY_DEQUEUE", "PriorityDequeue");
addClassMapper("PREDICATE", "2BooleanFunction");
addClassMapper("SORTED_SET", "SortedSet");
addClassMapper("ORDERED_SET", "OrderedSet");
addClassMapper("SET", "Set");
addClassMapper("STRATEGY", "Strategy");
addClassMapper("STACK", "Stack");
addClassMapper("SUPPLIER", "Supplier");
addAbstractMapper("SINGLE_UNARY_OPERATOR", "%1$s%1$sUnaryOperator");
addClassMapper("TASK", "Task");
addBiClassMapper("UNARY_OPERATOR", "UnaryOperator", "");
if(type.isObject())
{
@@ -1,6 +1,8 @@
package speiger.src.builder;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
@@ -10,7 +12,9 @@ import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringJoiner;
import java.util.function.Consumer;
import java.util.stream.Stream;
import speiger.src.builder.processor.TemplateProcess;
import speiger.src.builder.processor.TemplateProcessor;
@@ -29,12 +33,22 @@ public class PrimitiveCollectionsBuilder extends TemplateProcessor
public PrimitiveCollectionsBuilder()
{
super(Paths.get("src/builder/resources/speiger/assets/collections/templates/"), Paths.get("src/main/java/speiger/src/collections/"), Paths.get("src/builder/resources/speiger/assets/collections/"));
this(false);
}
public PrimitiveCollectionsBuilder(boolean silencedSuccess)
{
super(silencedSuccess, Paths.get("src/builder/resources/speiger/assets/collections/templates/"), Paths.get("src/main/java/speiger/src/collections/"), Paths.get("src/builder/resources/speiger/assets/collections/"));
}
public PrimitiveCollectionsBuilder(Path sourceFolder, Path outputFolder, Path dataFolder)
{
super(sourceFolder, outputFolder, dataFolder);
this(false, sourceFolder, outputFolder, dataFolder);
}
public PrimitiveCollectionsBuilder(boolean silencedSuccess, Path sourceFolder, Path outputFolder, Path dataFolder)
{
super(silencedSuccess, sourceFolder, outputFolder, dataFolder);
}
@Override
@@ -55,6 +69,23 @@ public class PrimitiveCollectionsBuilder extends TemplateProcessor
return false;
}
@Override
protected void afterFinish()
{
if(getVersion() > 8)
{
Path basePath = Paths.get("src/main/java");
try(BufferedWriter writer = Files.newBufferedWriter(basePath.resolve("module-info.java")))
{
writer.write(getModuleInfo(basePath));
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
@Override
protected void init()
{
@@ -73,7 +104,7 @@ public class PrimitiveCollectionsBuilder extends TemplateProcessor
biRequired.put("Pair", "");
biRequired.put("MutablePair", "");
biRequired.put("ImmutablePair", "");
addBiClass("Function", "Maps", "Map", "SortedMap", "NavigableMap", "AbstractMap", "ImmutableOpenHashMap", "OpenHashMap", "LinkedOpenHashMap", "OpenCustomHashMap", "LinkedOpenCustomHashMap", "ArrayMap", "RBTreeMap", "AVLTreeMap");
addBiClass("Function", "Maps", "Map", "SortedMap", "OrderedMap", "NavigableMap", "ConcurrentMap", "AbstractMap", "ConcurrentOpenHashMap", "ImmutableOpenHashMap", "OpenHashMap", "LinkedOpenHashMap", "OpenCustomHashMap", "LinkedOpenCustomHashMap", "ArrayMap", "RBTreeMap", "AVLTreeMap");
nameRemapper.put("BiConsumer", "%sConsumer");
nameRemapper.put("IArray", "I%sArray");
nameRemapper.put("AbstractMap", "Abstract%sMap");
@@ -84,12 +115,13 @@ public class PrimitiveCollectionsBuilder extends TemplateProcessor
nameRemapper.put("EnumMap", "Enum2%sMap");
nameRemapper.put("LinkedEnumMap", "LinkedEnum2%sMap");
nameRemapper.put("ImmutableList", "Immutable%sList");
nameRemapper.put("CopyOnWriteList", "CopyOnWrite%sArrayList");
nameRemapper.put("ImmutableOpenHashSet", "Immutable%sOpenHashSet");
nameRemapper.put("ImmutableOpenHashMap", "Immutable%sOpenHashMap");
addBlockage(ClassType.OBJECT, "Consumer", "Comparator", "Stack");
addBlockage(ClassType.BOOLEAN, "ArraySet", "AVLTreeSet", "RBTreeSet", "SortedSet", "NavigableSet", "OpenHashSet", "OpenCustomHashSet", "LinkedOpenHashSet", "LinkedOpenCustomHashSet");
addBlockage(ClassType.BOOLEAN, "ImmutableOpenHashMap", "ImmutableOpenHashSet", "SortedMap", "NavigableMap", "OpenHashMap", "LinkedOpenHashMap", "OpenCustomHashMap", "LinkedOpenCustomHashMap", "ArrayMap", "RBTreeMap", "AVLTreeMap");
addBlockage(ClassType.BOOLEAN, "ArraySet", "AVLTreeSet", "RBTreeSet", "SortedSet", "OrderedSet", "NavigableSet", "OpenHashSet", "OpenCustomHashSet", "LinkedOpenHashSet", "LinkedOpenCustomHashSet");
addBlockage(ClassType.BOOLEAN, "ConcurrentOpenHashMap", "ImmutableOpenHashMap", "ImmutableOpenHashSet", "SortedMap", "OrderedMap", "NavigableMap", "ConcurrentMap", "OpenHashMap", "LinkedOpenHashMap", "OpenCustomHashMap", "LinkedOpenCustomHashMap", "ArrayMap", "RBTreeMap", "AVLTreeMap");
}
protected void create(ClassType mainType, ClassType subType)
@@ -151,6 +183,55 @@ public class PrimitiveCollectionsBuilder extends TemplateProcessor
return variables;
}
private String getModuleInfo(Path basePath) {
StringJoiner joiner = new StringJoiner("\n", "", "\n");
try(Stream<Path> stream = Files.walk(getOutputFolder()))
{
stream.filter(Files::isDirectory)
.filter(this::containsFiles)
.map(basePath::relativize)
.map(Path::toString)
.map(this::sanitize)
.forEach(T -> joiner.add("\texports "+T+";"));
}
catch(Exception e)
{
e.printStackTrace();
throw new RuntimeException(e);
}
StringBuilder builder = new StringBuilder();
builder.append("/** @author Speiger */\n");
builder.append("module ").append(sanitize(basePath.relativize(getOutputFolder()).toString())).append(" {\n");
builder.append(joiner.toString()).append("}");
return builder.toString();
}
private String sanitize(String input)
{
return input.replace("\\", ".").replace("/", ".");
}
private boolean containsFiles(Path path)
{
try(Stream<Path> stream = Files.walk(path, 1))
{
return stream.filter(Files::isRegularFile).findFirst().isPresent();
}
catch(Exception e)
{
e.printStackTrace();
}
return false;
}
private int getVersion()
{
String version = System.getProperty("java.version");
if(version.startsWith("1.")) return Integer.parseInt(version.substring(2, 3));
int dot = version.indexOf(".");
return Integer.parseInt(dot != -1 ? version.substring(0, dot) : version);
}
public static void main(String...args)
{
try
@@ -159,10 +240,14 @@ public class PrimitiveCollectionsBuilder extends TemplateProcessor
new PrimitiveCollectionsBuilder().process(false);
} else if(args.length == 1) {
new PrimitiveCollectionsBuilder().process(Boolean.parseBoolean(args[0]));
} else if(args.length == 2) {
new PrimitiveCollectionsBuilder(Boolean.parseBoolean(args[1])).process(Boolean.parseBoolean(args[0]));
} else if(args.length == 3) {
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]));
new PrimitiveCollectionsBuilder(false, Paths.get(args[0]), Paths.get(args[1]), Paths.get(args[2])).process(Boolean.parseBoolean(args[3]));
} else if(args.length == 4) {
new PrimitiveCollectionsBuilder(Boolean.parseBoolean(args[4]), Paths.get(args[0]), Paths.get(args[1]), Paths.get(args[2])).process(Boolean.parseBoolean(args[3]));
} else {
System.out.println("Invalid argument count passed in");
System.exit(1);
@@ -7,7 +7,6 @@ import java.util.AbstractCollection;
import java.util.function.Consumer;
#endif
import speiger.src.collections.PACKAGE.collections.COLLECTION;
#if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.functions.CONSUMER;
import speiger.src.collections.PACKAGE.utils.ITERATORS;
@@ -100,7 +99,6 @@ public abstract class ABSTRACT_COLLECTION KEY_GENERIC_TYPE extends AbstractColle
* This implementation iterates over the elements of the collection and checks if they are stored in this collection
* @param c the elements that should be checked for
* @return true if any element is in this collection
* @deprecated if this is a primitive collection
* @throws java.lang.NullPointerException if the collection is null
*/
@Override
@@ -232,6 +230,7 @@ public abstract class ABSTRACT_COLLECTION KEY_GENERIC_TYPE extends AbstractColle
for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) {
KEY_TYPE e = iter.NEXT();
if(!c.contains(e)) {
r.accept(e);
iter.remove();
modified = true;
}
@@ -258,6 +257,7 @@ public abstract class ABSTRACT_COLLECTION KEY_GENERIC_TYPE extends AbstractColle
public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] a) {
if(a == null || a.length < size()) a = new KEY_TYPE[size()];
ITERATORS.unwrap(a, iterator());
if (a.length > size()) a[size()] = EMPTY_KEY_VALUE;
return a;
}
#endif
@@ -5,16 +5,24 @@ import java.util.function.Consumer;
#if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.functions.CONSUMER;
import speiger.src.collections.PACKAGE.functions.COMPARATOR;
import speiger.src.collections.objects.collections.ObjectIterable;
#else
import java.util.function.BiFunction;
import java.util.Comparator;
#endif
import speiger.src.collections.PACKAGE.functions.function.TO_OBJECT_FUNCTION;
import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER;
import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR;
import speiger.src.collections.PACKAGE.collections.SPLIT_ITERATOR;
import speiger.src.collections.PACKAGE.lists.LIST;
import speiger.src.collections.PACKAGE.lists.ARRAY_LIST;
#if !TYPE_BOOLEAN
import speiger.src.collections.PACKAGE.sets.SET;
import speiger.src.collections.PACKAGE.sets.LINKED_HASH_SET;
#endif
import speiger.src.collections.PACKAGE.utils.ASYNC_BUILDER;
import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS;
import speiger.src.collections.PACKAGE.utils.ITERABLES;
import speiger.src.collections.PACKAGE.utils.ITERATORS;
@@ -83,6 +91,16 @@ public interface ITERABLE KEY_GENERIC_TYPE extends Iterable<CLASS_TYPE>
@Override
default SPLIT_ITERATOR KEY_GENERIC_TYPE spliterator() { return SPLIT_ITERATORS.createUnknownSplititerator(iterator(), 0); }
/**
* Creates a Async Builder for moving work of the thread.
* It is not designed to split the work to multithreaded work, so using this keep it singlethreaded, but it allows to be moved to another thread.
* @see ASYNC_BUILDER
* @return a AsyncBuilder
*/
default ASYNC_BUILDER KEY_GENERIC_TYPE asAsync() {
return new ASYNC_BUILDERBRACES(this);
}
/**
* A Helper function to reduce the usage of Streams and allows to convert a Iterable to something else.
* @param mapper the mapping function
@@ -140,6 +158,15 @@ public interface ITERABLE KEY_GENERIC_TYPE extends Iterable<CLASS_TYPE>
return ITERABLES.limit(this, limit);
}
/**
* A Helper function to reduce the usage of Streams and allows to sort the elements
* @param sorter that sorts the elements.
* @return a Iterable that is sorted
*/
default ITERABLE KEY_GENERIC_TYPE sorted(COMPARATOR KEY_GENERIC_TYPE sorter) {
return ITERABLES.sorted(this, sorter);
}
/**
* A Helper function to reduce the usage of Streams and allows to preview elements before they are iterated through
* @param action the action that should be applied
@@ -160,6 +187,24 @@ public interface ITERABLE KEY_GENERIC_TYPE extends Iterable<CLASS_TYPE>
return collection;
}
/**
* A Helper function that reduces the usage of streams and allows to collect all elements as a ArrayList
* @return a new ArrayList of all elements
*/
default LIST KEY_GENERIC_TYPE pourAsList() {
return pour(new ARRAY_LISTBRACES());
}
#if !TYPE_BOOLEAN
/**
* A Helper function that reduces the usage of streams and allows to collect all elements as a LinkedHashSet
* @return a new LinkedHashSet of all elements
*/
default SET KEY_GENERIC_TYPE pourAsSet() {
return pour(new LINKED_HASH_SETBRACES());
}
#endif
/**
* Helper function to reduce stream usage that allows to filter for any matches.
* @param filter that should be applied
@@ -50,6 +50,10 @@ public interface COMPARATOR extends Comparator<CLASS_TYPE>
{
COMPARATOR original;
/**
* default constructor
* @param original that is going to be reversed
*/
public Reversed(COMPARATOR original) {
this.original = original;
}
@@ -0,0 +1,92 @@
package speiger.src.collections.PACKAGE.functions;
import java.util.concurrent.RunnableFuture;
#if !TYPE_OBJECT
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
#endif
/**
*
* A Type Specific Task interface that allows you to keep track of the task that is currently running.<br>
* It extends Runnable future and supports said functions but also provides quality of life functions like:<br>
*
* - isSuccesfull: which allows to detect if the task was completed properly and not interrupted or crashed.
* - pause/resume: which allows to pause/resume the task at any moment, making it easier to create thread-safe actions.
* @Type(T)
*/
public interface TASK KEY_GENERIC_TYPE extends RunnableFuture<CLASS_TYPE> {
/**
* Helper function to detect if the task is currently paused.
* @return true if paused
*/
public boolean isPaused();
/**
* Pauses the task, which lets the thread finish without completing the task.
* Tasks are written in the way where they can pause without any issues.
* This won't be instant, as this function is applied asynchronous and doesn't check if the thread paused.
* So make sure it had the time to pause.
*/
public void pause();
/**
* Pauses the task, which lets the thread finish without completing the task.
* Tasks are written in the way where they can pause without any issues.
* This won't be instant, as this function is applied asynchronous.
* It will await the pausing of the task.
*/
public void awaitPausing();
/**
* Continues the task if it wasn't already completed.
* This is done by resubmitting the task to the executor provided.
*/
public void resume();
/**
* Quality of life function that allows to detect if no cancellation/exception was applied to this task and it completed on its own.
* @return true if it was properly completed
*/
public boolean isSuccessful();
#if !TYPE_OBJECT
/**
* A Type Specific get method that allows to reduce (un)boxing of primtives.
*
* Waits if necessary for the computation to complete, and then
* retrieves its result.
*
* @return the computed result as primitive
* @throws CancellationException if the computation was cancelled
* @throws ExecutionException if the computation threw an exception
* @throws InterruptedException if the current thread was interrupted
* while waiting
*/
public KEY_TYPE GET_KEY() throws InterruptedException, ExecutionException;
/**
* Waits if necessary for at most the given time for the computation
* to complete, and then retrieves its result, if available.
*
* @param timeout the maximum time to wait
* @param unit the time unit of the timeout argument
* @return the computed result as primitive
* @throws CancellationException if the computation was cancelled
* @throws ExecutionException if the computation threw an exception
* @throws InterruptedException if the current thread was interrupted while waiting
* @throws TimeoutException if the wait timed out
*/
public KEY_TYPE GET_KEY(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException;
@Override
@Deprecated
public default CLASS_TYPE get() throws InterruptedException, ExecutionException { return KEY_TO_OBJ(GET_KEY()); }
@Override
@Deprecated
public default CLASS_TYPE get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return KEY_TO_OBJ(GET_KEY(timeout, unit)); }
#endif
}
@@ -75,7 +75,7 @@ public abstract class ABSTRACT_LIST KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION
* The IndexOf implementation iterates over all elements and compares them to the search value.
* @param o the value that the index is searched for.
* @return index of the value that was searched for. -1 if not found
* @deprecated it is highly suggested not to use this with Primitives because of boxing. But it is still supported because of ObjectComparason that are custom objects and allow to find the contents.
* @note it is highly suggested not to use this with Primitives because of boxing. But it is still supported because of ObjectComparason that are custom objects and allow to find the contents.
*/
@Override
@Primitive
@@ -103,7 +103,7 @@ public abstract class ABSTRACT_LIST KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION
* The lastIndexOf implementation iterates over all elements and compares them to the search value.
* @param o the value that the index is searched for.
* @return the last index of the value that was searched for. -1 if not found
* @deprecated it is highly suggested not to use this with Primitives because of boxing. But it is still supported because of ObjectComparason that are custom objects and allow to find the contents.
* @note it is highly suggested not to use this with Primitives because of boxing. But it is still supported because of ObjectComparason that are custom objects and allow to find the contents.
*/
@Override
@Primitive
@@ -315,7 +315,7 @@ public abstract class ABSTRACT_LIST KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION
public void removeElements(int from, int to) {
if(to-from <= 0) return;
checkSubRange(from);
checkSubRange(to);
checkAddSubRange(to);
list.removeElements(from+parentOffset, to+parentOffset);
size -= to - from;
}
@@ -324,9 +324,9 @@ public abstract class ABSTRACT_LIST KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION
@Override
public <K> K[] extractElements(int from, int to, Class<K> type) {
checkSubRange(from);
checkSubRange(to);
checkAddSubRange(to);
K[] result = list.extractElements(from+parentOffset, to+parentOffset, type);
size -= to - from;
size -= result.length;
return result;
}
@@ -334,9 +334,9 @@ public abstract class ABSTRACT_LIST KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION
@Override
public KEY_TYPE[] extractElements(int from, int to) {
checkSubRange(from);
checkSubRange(to);
checkAddSubRange(to);
KEY_TYPE[] result = list.extractElements(from+parentOffset, to+parentOffset);
size -= to - from;
size -= result.length;
return result;
}
@@ -188,12 +188,25 @@ public class ARRAY_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
return list;
}
/**
* Creates a new ArrayList with a EmptyObject array of the Type requested
* @param c the type of the array
* @param size the initial size of the backing array
* @Type(T)
* @return a typed List
*/
public static GENERIC_KEY_BRACES ARRAY_LIST KEY_GENERIC_TYPE of(Class<KEY_TYPE> c, int size) {
ARRAY_LIST KEY_GENERIC_TYPE list = new ARRAY_LISTBRACES();
list.data = (KEY_TYPE[])ObjectArrays.newArray(c, size);
return list;
}
#endif
/**
* Appends the specified element to the end of this list.
*
* @param e element to be appended to this list
* @return <tt>true</tt> (as specified by {@link Collection#add})
* @return true (as specified by {@link Collection#add})
*/
@Override
public boolean add(KEY_TYPE e) {
@@ -232,6 +245,7 @@ public class ARRAY_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
* @param index the index where to append the elements to
* @param c the elements to append to the list
* @throws IndexOutOfBoundsException if index is outside of the lists range
* @throws NullPointerException if collection contains a null element
*/
@Override
@Primitive
@@ -239,6 +253,9 @@ public class ARRAY_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
if(c instanceof COLLECTION) return addAll(index, (COLLECTION KEY_GENERIC_TYPE)c);
int add = c.size();
if(add <= 0) return false;
#if !TYPE_OBJECT
if(c.contains(null)) throw new NullPointerException();
#endif
grow(size + add);
if(index != size) System.arraycopy(data, index, data, index+add, size - index);
size+=add;
@@ -307,8 +324,9 @@ public class ARRAY_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
public void addElements(int from, KEY_TYPE[] a, int offset, int length) {
if(length <= 0) return;
checkAddRange(from);
SanityChecks.checkArrayCapacity(a.length, offset, length);
grow(size + length);
if(from != size) System.arraycopy(data, from, data, from+length, size - length);
if(from != size) System.arraycopy(data, from, data, from+length, size - from);
size+=length;
System.arraycopy(a, offset, data, from, length);
}
@@ -344,11 +362,11 @@ public class ARRAY_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
int length = to - from;
if(length <= 0) return;
if(to != size) System.arraycopy(data, to, data, from, size - to);
size -= length;
#if TYPE_OBJECT
for(int i = 0;i<length;i++)
data[i+to] = null;
data[i+size] = null;
#endif
size -= length;
}
#if TYPE_OBJECT
@@ -364,13 +382,13 @@ public class ARRAY_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
checkRange(from);
checkAddRange(to);
int length = to - from;
if(length <= 0) return ARRAYS.newArray(type, 0);
K[] a = ARRAYS.newArray(type, length);
if(length <= 0) return a;
System.arraycopy(data, from, a, 0, length);
if(to != size) System.arraycopy(data, to, data, from, size - to);
for(int i = 0;i<length;i++)
data[i+to] = null;
size -= length;
for(int i = 0;i<length;i++)
data[i+size] = null;
return a;
}
@@ -1126,7 +1144,7 @@ public class ARRAY_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
}
protected void grow(int capacity) {
if(capacity < data.length) return;
if(capacity <= data.length) return;
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));
}
@@ -152,10 +152,16 @@ public class LINKED_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
int length = c.size();
if(length == 0) return false;
checkAddRange(index);
Entry KEY_GENERIC_TYPE next = null;
Entry KEY_GENERIC_TYPE prev = null;
if(index == size) prev = last;
else if(index == 0) next = first;
Entry KEY_GENERIC_TYPE next;
Entry KEY_GENERIC_TYPE prev;
if(index == size) {
prev = last;
next = null;
}
else if(index == 0) {
next = first;
prev = null;
}
else {
next = getNode(index);
prev = next.prev;
@@ -180,10 +186,16 @@ public class LINKED_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
int length = c.size();
if(length == 0) return false;
checkAddRange(index);
Entry KEY_GENERIC_TYPE next = null;
Entry KEY_GENERIC_TYPE prev = null;
if(index == size) prev = last;
else if(index == 0) next = first;
Entry KEY_GENERIC_TYPE next;
Entry KEY_GENERIC_TYPE prev;
if(index == size) {
prev = last;
next = null;
}
else if(index == 0) {
next = first;
prev = null;
}
else {
next = getNode(index);
prev = next.prev;
@@ -210,10 +222,16 @@ public class LINKED_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
int length = c.size();
if(length == 0) return false;
checkAddRange(index);
Entry KEY_GENERIC_TYPE next = null;
Entry KEY_GENERIC_TYPE prev = null;
if(index == size) prev = last;
else if(index == 0) next = first;
Entry KEY_GENERIC_TYPE next;
Entry KEY_GENERIC_TYPE prev;
if(index == size) {
prev = last;
next = null;
}
else if(index == 0) {
next = first;
prev = null;
}
else {
next = getNode(index);
prev = next.prev;
@@ -258,12 +276,19 @@ public class LINKED_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
@Override
public void addElements(int from, KEY_TYPE[] a, int offset, int length) {
if(length <= 0) return;
SanityChecks.checkArrayCapacity(a.length, offset, length);
checkAddRange(from);
Entry KEY_GENERIC_TYPE next = null;
Entry KEY_GENERIC_TYPE prev = null;
if(from == size) prev = last;
else if(from == 0) next = first;
Entry KEY_GENERIC_TYPE next;
Entry KEY_GENERIC_TYPE prev;
if(from == size) {
prev = last;
next = null;
}
else if(from == 0) {
next = first;
prev = null;
}
else {
next = getNode(from);
prev = next.prev;
@@ -593,12 +618,14 @@ public class LINKED_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
first = temp;
return result;
}
Entry KEY_GENERIC_TYPE temp = last;
last = temp.prev;
last.next = null;
temp.next = before.next;
temp.prev = before;
before.next = temp;
else if(before.next != last) {
Entry KEY_GENERIC_TYPE temp = last;
last = temp.prev;
last.next = null;
temp.next = before.next;
temp.prev = before;
before.next = temp;
}
return result;
}
@@ -623,12 +650,14 @@ public class LINKED_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
first = temp;
return true;
}
Entry KEY_GENERIC_TYPE temp = last;
last = temp.prev;
last.next = null;
temp.next = before.next;
temp.prev = before;
before.next = temp;
else if(before.next != last) {
Entry KEY_GENERIC_TYPE temp = last;
last = temp.prev;
last.next = null;
temp.next = before.next;
temp.prev = before;
before.next = temp;
}
return true;
}
}
@@ -671,16 +700,18 @@ public class LINKED_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
if(from < size - to) {
Entry KEY_GENERIC_TYPE entry = getNode(from);
while(length > 0) {
entry = entry.next;
unlink(entry.prev);
Entry KEY_GENERIC_TYPE next = entry.next;
unlink(entry);
entry = next;
length--;
}
return;
}
Entry KEY_GENERIC_TYPE entry = getNode(to);
while(length > 0) {
entry = entry.prev;
unlink(entry.next);
Entry KEY_GENERIC_TYPE prev = entry.prev;
unlink(entry);
entry = prev;
length--;
}
}
@@ -691,20 +722,22 @@ public class LINKED_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
checkRange(from);
checkAddRange(to);
int length = to - from;
if(length <= 0) return ARRAYS.newArray(type, 0);
K[] a = ARRAYS.newArray(type, length);
if(length <= 0) return a;
if(from < size - to) {
Entry KEY_GENERIC_TYPE entry = getNode(from);
for(int i = 0;length > 0;i++, length--) {
entry = entry.next;
a[i] = (K)unlink(entry.prev);
Entry KEY_GENERIC_TYPE next = entry.next;
a[i] = (K)unlink(entry);
entry = next;
}
return a;
}
Entry KEY_GENERIC_TYPE entry = getNode(to);
for(int i = length-1;length > 0;i--) {
entry = entry.prev;
a[i] = (K)unlink(entry.next);
for(int i = length-1;length > 0;i--, length--) {
Entry KEY_GENERIC_TYPE prev = entry.prev;
a[i] = (K)unlink(entry);
entry = prev;
}
return a;
}
@@ -720,15 +753,17 @@ public class LINKED_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
if(from < size - to) {
Entry KEY_GENERIC_TYPE entry = getNode(from);
for(int i = 0;length > 0;i++, length--) {
entry = entry.next;
d[i] = unlink(entry.prev);
Entry KEY_GENERIC_TYPE next = entry.next;
d[i] = unlink(entry);
entry = next;
}
return d;
}
Entry KEY_GENERIC_TYPE entry = getNode(to);
for(int i = length-1;length > 0;i--) {
entry = entry.prev;
d[i] = unlink(entry.next);
for(int i = length-1;length > 0;i--, length--) {
Entry KEY_GENERIC_TYPE prev = entry.prev;
d[i] = unlink(entry);
entry = prev;
}
return d;
}
@@ -1239,7 +1274,7 @@ public class LINKED_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
@Override
public long estimateSize() {
return list.size - index;
return (long)list.size - (long)index;
}
@Override
@@ -1305,7 +1340,7 @@ public class LINKED_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
@Override
public long estimateSize() {
return list.size - index;
return (long)list.size - (long)index;
}
@Override
@@ -1,7 +1,6 @@
package speiger.src.collections.PACKAGE.maps.impl.customHash;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.function.Consumer;
@@ -10,7 +9,6 @@ import java.util.Objects;
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;
import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER;
#endif
@@ -21,9 +19,9 @@ import speiger.src.collections.PACKAGE.functions.consumer.BI_CONSUMER;
import speiger.src.collections.PACKAGE.functions.function.SINGLE_UNARY_OPERATOR;
import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR;
import speiger.src.collections.PACKAGE.maps.interfaces.MAP;
import speiger.src.collections.PACKAGE.maps.interfaces.SORTED_MAP;
import speiger.src.collections.PACKAGE.maps.interfaces.ORDERED_MAP;
import speiger.src.collections.PACKAGE.sets.ABSTRACT_SET;
import speiger.src.collections.PACKAGE.sets.SORTED_SET;
import speiger.src.collections.PACKAGE.sets.ORDERED_SET;
import speiger.src.collections.PACKAGE.sets.SET;
import speiger.src.collections.PACKAGE.utils.STRATEGY;
import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ABSTRACT_COLLECTION;
@@ -59,7 +57,6 @@ import speiger.src.collections.objects.functions.function.ObjectObjectUnaryOpera
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
import speiger.src.collections.utils.HashUtil;
@@ -71,7 +68,7 @@ import speiger.src.collections.utils.HashUtil;
* @Type(T)
* @ValueType(V)
*/
public class LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE implements SORTED_MAP KEY_VALUE_GENERIC_TYPE
public class LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE implements ORDERED_MAP KEY_VALUE_GENERIC_TYPE
{
/** The Backing array for links between nodes. Left 32 Bits => Previous Entry, Right 32 Bits => Next Entry */
protected transient long[] links;
@@ -363,20 +360,6 @@ public class LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends CUSTOM_HASH_M
return map;
}
@Override
public COMPARATOR KEY_GENERIC_TYPE comparator() {
return null;
}
@Override
public SORTED_MAP KEY_VALUE_GENERIC_TYPE subMap(KEY_TYPE fromKey, KEY_TYPE toKey) { throw new UnsupportedOperationException(); }
@Override
public SORTED_MAP KEY_VALUE_GENERIC_TYPE headMap(KEY_TYPE toKey) { throw new UnsupportedOperationException(); }
@Override
public SORTED_MAP KEY_VALUE_GENERIC_TYPE tailMap(KEY_TYPE fromKey) { throw new UnsupportedOperationException(); }
@Override
public KEY_TYPE FIRST_ENTRY_KEY() {
if(size == 0) throw new NoSuchElementException();
@@ -620,7 +603,7 @@ public class LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends CUSTOM_HASH_M
values = newValues;
}
private class MapEntrySet extends AbstractObjectSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> implements SORTED_MAP.FastSortedSet KEY_VALUE_GENERIC_TYPE {
private class MapEntrySet extends AbstractObjectSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> implements ORDERED_MAP.FastOrderedSet KEY_VALUE_GENERIC_TYPE {
@Override
public boolean addAndMoveToFirst(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); }
@Override
@@ -860,20 +843,9 @@ public class LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends CUSTOM_HASH_M
public void clear() {
LINKED_CUSTOM_HASH_MAP.this.clear();
}
@Override
public Comparator<MAP.Entry KEY_VALUE_GENERIC_TYPE> comparator() {
return null;
}
@Override
public ObjectSortedSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> subSet(MAP.Entry KEY_VALUE_GENERIC_TYPE fromElement, MAP.Entry KEY_VALUE_GENERIC_TYPE toElement) { throw new UnsupportedOperationException(); }
@Override
public ObjectSortedSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> headSet(MAP.Entry KEY_VALUE_GENERIC_TYPE toElement) { throw new UnsupportedOperationException(); }
@Override
public ObjectSortedSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> tailSet(MAP.Entry KEY_VALUE_GENERIC_TYPE fromElement) { throw new UnsupportedOperationException(); }
}
private final class KeySet extends ABSTRACT_SET KEY_GENERIC_TYPE implements SORTED_SET KEY_GENERIC_TYPE {
private final class KeySet extends ABSTRACT_SET KEY_GENERIC_TYPE implements ORDERED_SET KEY_GENERIC_TYPE {
#if TYPE_OBJECT
@Override
@Deprecated
@@ -1092,18 +1064,6 @@ public class LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends CUSTOM_HASH_M
}
return result;
}
@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(); }
}
private class Values extends VALUE_ABSTRACT_COLLECTION VALUE_GENERIC_TYPE {
@@ -286,6 +286,15 @@ public class CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VAL
return oldValue;
}
@Override
public VALUE_TYPE subFrom(KEY_TYPE key, VALUE_TYPE value) {
int slot = findIndex(key);
if(slot < 0) return getDefaultReturnValue();
VALUE_TYPE oldValue = values[slot];
values[slot] -= value;
if(value < 0 ? (values[slot] >= getDefaultReturnValue()) : (values[slot] <= getDefaultReturnValue())) removeIndex(slot);
return oldValue;
}
#endif
#if !TYPE_OBJECT
@Override
@@ -307,6 +316,7 @@ public class CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VAL
#if !VALUE_OBJECT
@Override
public boolean containsValue(VALUE_TYPE value) {
if(containsNull && VALUE_EQUALS(values[nullIndex], value)) return true;
for(int i = nullIndex;i >= 0;i--)
if(!strategy.equals(keys[i], EMPTY_KEY_VALUE) && VALUE_EQUALS(values[i], value)) return true;
return false;
@@ -316,7 +326,12 @@ public class CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VAL
@Override
@ValuePrimitive
public boolean containsValue(Object value) {
for(int i = nullIndex;i >= 0;i--)
#if VALUE_OBJECT
if(containsNull && VALUE_EQUALS(values[nullIndex], value)) return true;
#else
if(containsNull && ((value == null && values[nullIndex] == getDefaultReturnValue()) || EQUALS_VALUE_TYPE(values[nullIndex], value))) return true;
#endif
for(int i = nullIndex-1;i >= 0;i--)
#if VALUE_OBJECT
if(!strategy.equals(keys[i], EMPTY_KEY_VALUE) && EQUALS_VALUE_TYPE(values[i], value)) return true;
#else
@@ -1,7 +1,6 @@
package speiger.src.collections.PACKAGE.maps.impl.hash;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.function.Consumer;
@@ -10,7 +9,6 @@ import java.util.Objects;
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;
import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER;
#endif
@@ -21,9 +19,9 @@ import speiger.src.collections.PACKAGE.functions.consumer.BI_CONSUMER;
import speiger.src.collections.PACKAGE.functions.function.SINGLE_UNARY_OPERATOR;
import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR;
import speiger.src.collections.PACKAGE.maps.interfaces.MAP;
import speiger.src.collections.PACKAGE.maps.interfaces.SORTED_MAP;
import speiger.src.collections.PACKAGE.maps.interfaces.ORDERED_MAP;
import speiger.src.collections.PACKAGE.sets.ABSTRACT_SET;
import speiger.src.collections.PACKAGE.sets.SORTED_SET;
import speiger.src.collections.PACKAGE.sets.ORDERED_SET;
import speiger.src.collections.PACKAGE.sets.SET;
import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ABSTRACT_COLLECTION;
import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_COLLECTION;
@@ -58,7 +56,6 @@ import speiger.src.collections.objects.functions.function.ObjectObjectUnaryOpera
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
import speiger.src.collections.utils.HashUtil;
@@ -70,7 +67,7 @@ import speiger.src.collections.utils.HashUtil;
* @Type(T)
* @ValueType(V)
*/
public class LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE extends HASH_MAP KEY_VALUE_GENERIC_TYPE implements SORTED_MAP KEY_VALUE_GENERIC_TYPE
public class LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE extends HASH_MAP KEY_VALUE_GENERIC_TYPE implements ORDERED_MAP KEY_VALUE_GENERIC_TYPE
{
/** The Backing array for links between nodes. Left 32 Bits => Previous Entry, Right 32 Bits => Next Entry */
protected transient long[] links;
@@ -367,20 +364,6 @@ public class LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE extends HASH_MAP KEY_VALUE_G
return map;
}
@Override
public COMPARATOR KEY_GENERIC_TYPE comparator() {
return null;
}
@Override
public SORTED_MAP KEY_VALUE_GENERIC_TYPE subMap(KEY_TYPE fromKey, KEY_TYPE toKey) { throw new UnsupportedOperationException(); }
@Override
public SORTED_MAP KEY_VALUE_GENERIC_TYPE headMap(KEY_TYPE toKey) { throw new UnsupportedOperationException(); }
@Override
public SORTED_MAP KEY_VALUE_GENERIC_TYPE tailMap(KEY_TYPE fromKey) { throw new UnsupportedOperationException(); }
@Override
public KEY_TYPE FIRST_ENTRY_KEY() {
if(size == 0) throw new NoSuchElementException();
@@ -624,7 +607,7 @@ public class LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE extends HASH_MAP KEY_VALUE_G
values = newValues;
}
private class MapEntrySet extends AbstractObjectSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> implements SORTED_MAP.FastSortedSet KEY_VALUE_GENERIC_TYPE {
private class MapEntrySet extends AbstractObjectSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> implements ORDERED_MAP.FastOrderedSet KEY_VALUE_GENERIC_TYPE {
@Override
public boolean addAndMoveToFirst(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); }
@Override
@@ -861,20 +844,9 @@ public class LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE extends HASH_MAP KEY_VALUE_G
public void clear() {
LINKED_HASH_MAP.this.clear();
}
@Override
public Comparator<MAP.Entry KEY_VALUE_GENERIC_TYPE> comparator() {
return null;
}
@Override
public ObjectSortedSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> subSet(MAP.Entry KEY_VALUE_GENERIC_TYPE fromElement, MAP.Entry KEY_VALUE_GENERIC_TYPE toElement) { throw new UnsupportedOperationException(); }
@Override
public ObjectSortedSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> headSet(MAP.Entry KEY_VALUE_GENERIC_TYPE toElement) { throw new UnsupportedOperationException(); }
@Override
public ObjectSortedSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> tailSet(MAP.Entry KEY_VALUE_GENERIC_TYPE fromElement) { throw new UnsupportedOperationException(); }
}
private final class KeySet extends ABSTRACT_SET KEY_GENERIC_TYPE implements SORTED_SET KEY_GENERIC_TYPE {
private final class KeySet extends ABSTRACT_SET KEY_GENERIC_TYPE implements ORDERED_SET KEY_GENERIC_TYPE {
#if TYPE_OBJECT
@Override
@Deprecated
@@ -904,9 +876,7 @@ public class LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE extends HASH_MAP KEY_VALUE_G
#endif
@Override
public boolean add(KEY_TYPE o) {
throw new UnsupportedOperationException();
}
public boolean add(KEY_TYPE o) { throw new UnsupportedOperationException(); }
@Override
public boolean addAndMoveToFirst(KEY_TYPE o) { throw new UnsupportedOperationException(); }
@@ -1088,23 +1058,11 @@ public class LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE extends HASH_MAP KEY_VALUE_G
int result = 0;
int index = firstIndex;
while(index != -1){
if(filter.TEST_VALUE(keys[index])) return result++;
if(filter.TEST_VALUE(keys[index])) result++;
index = (int)links[index];
}
return result;
}
@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(); }
}
private class Values extends VALUE_ABSTRACT_COLLECTION VALUE_GENERIC_TYPE {
@@ -1370,7 +1328,6 @@ public class LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE extends HASH_MAP KEY_VALUE_G
@Override
public void add(VALUE_TYPE e) { throw new UnsupportedOperationException(); }
}
private class MapIterator {
@@ -1440,7 +1397,7 @@ public class LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE extends HASH_MAP KEY_VALUE_G
if(previous == -1) firstIndex = next;
else links[previous] ^= ((links[previous] ^ (next & 0xFFFFFFFFL)) & 0xFFFFFFFFL);
if (next == -1) lastIndex = previous;
if(next == -1) lastIndex = previous;
else links[next] ^= ((links[next] ^ ((previous & 0xFFFFFFFFL) << 32)) & 0xFFFFFFFF00000000L);
if(current == nullIndex) {
current = -1;
@@ -261,6 +261,15 @@ public class HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENE
return oldValue;
}
@Override
public VALUE_TYPE subFrom(KEY_TYPE key, VALUE_TYPE value) {
int slot = findIndex(key);
if(slot < 0) return getDefaultReturnValue();
VALUE_TYPE oldValue = values[slot];
values[slot] -= value;
if(value < 0 ? (values[slot] >= getDefaultReturnValue()) : (values[slot] <= getDefaultReturnValue())) removeIndex(slot);
return oldValue;
}
#endif
#if !TYPE_OBJECT
@Override
@@ -278,7 +287,8 @@ public class HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENE
#if !VALUE_OBJECT
@Override
public boolean containsValue(VALUE_TYPE value) {
for(int i = nullIndex;i >= 0;i--)
if(containsNull && VALUE_EQUALS(values[nullIndex], value)) return true;
for(int i = nullIndex-1;i >= 0;i--)
if(KEY_EQUALS_NOT_NULL(keys[i]) && VALUE_EQUALS(values[i], value)) return true;
return false;
}
@@ -287,7 +297,12 @@ public class HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENE
@Override
@ValuePrimitive
public boolean containsValue(Object value) {
for(int i = nullIndex;i >= 0;i--)
#if VALUE_OBJECT
if(containsNull && VALUE_EQUALS(values[nullIndex], value)) return true;
#else
if(containsNull && ((value == null && values[nullIndex] == getDefaultReturnValue()) || EQUALS_VALUE_TYPE(values[nullIndex], value))) return true;
#endif
for(int i = nullIndex-1;i >= 0;i--)
#if VALUE_OBJECT
if(KEY_EQUALS_NOT_NULL(keys[i]) && EQUALS_VALUE_TYPE(values[i], value)) return true;
#else
@@ -1,7 +1,6 @@
package speiger.src.collections.PACKAGE.maps.impl.immutable;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Objects;
@@ -11,7 +10,6 @@ import java.util.function.BiFunction;
#if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.collections.BI_ITERATOR;
import speiger.src.collections.PACKAGE.functions.CONSUMER;
import speiger.src.collections.PACKAGE.functions.COMPARATOR;
import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER;
#endif
#if !TYPE_OBJECT && !VALUE_BOOLEAN
@@ -24,10 +22,10 @@ import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR;
import speiger.src.collections.PACKAGE.functions.function.SINGLE_UNARY_OPERATOR;
#endif
import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR;
import speiger.src.collections.PACKAGE.maps.interfaces.SORTED_MAP;
import speiger.src.collections.PACKAGE.maps.interfaces.ORDERED_MAP;
import speiger.src.collections.PACKAGE.maps.abstracts.ABSTRACT_MAP;
import speiger.src.collections.PACKAGE.maps.interfaces.MAP;
import speiger.src.collections.PACKAGE.sets.SORTED_SET;
import speiger.src.collections.PACKAGE.sets.ORDERED_SET;
import speiger.src.collections.PACKAGE.utils.maps.MAPS;
#if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.utils.ARRAYS;
@@ -70,7 +68,6 @@ import speiger.src.collections.objects.functions.function.ObjectObjectUnaryOpera
#endif
import speiger.src.collections.objects.lists.ObjectListIterator;
import speiger.src.collections.objects.sets.ObjectSortedSet;
#endif
import speiger.src.collections.objects.sets.AbstractObjectSet;
import speiger.src.collections.objects.sets.ObjectSet;
@@ -84,7 +81,7 @@ import speiger.src.collections.utils.SanityChecks;
* @Type(T)
* @ValueType(V)
*/
public class IMMUTABLE_HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE implements SORTED_MAP KEY_VALUE_GENERIC_TYPE
public class IMMUTABLE_HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GENERIC_TYPE implements ORDERED_MAP KEY_VALUE_GENERIC_TYPE
{
/** The Backing keys array */
protected transient KEY_TYPE[] keys;
@@ -297,11 +294,11 @@ public class IMMUTABLE_HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_
public VALUE_TYPE put(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); }
@Override
public VALUE_TYPE putIfAbsent(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); }
#if VALUE_PRIMITIVES
@Override
public VALUE_TYPE addTo(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); }
@Override
public VALUE_TYPE subFrom(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); }
#endif
@Override
public VALUE_TYPE putAndMoveToFirst(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); }
@@ -464,15 +461,6 @@ public class IMMUTABLE_HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_
return map;
}
@Override
public COMPARATOR KEY_GENERIC_TYPE comparator() { return null; }
@Override
public SORTED_MAP KEY_VALUE_GENERIC_TYPE subMap(KEY_TYPE fromKey, KEY_TYPE toKey) { throw new UnsupportedOperationException(); }
@Override
public SORTED_MAP KEY_VALUE_GENERIC_TYPE headMap(KEY_TYPE toKey) { throw new UnsupportedOperationException(); }
@Override
public SORTED_MAP KEY_VALUE_GENERIC_TYPE tailMap(KEY_TYPE fromKey) { throw new UnsupportedOperationException(); }
@Override
public void forEach(BI_CONSUMER KEY_VALUE_GENERIC_TYPE action) {
int index = firstIndex;
@@ -596,7 +584,7 @@ public class IMMUTABLE_HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_
}
}
private class MapEntrySet extends AbstractObjectSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> implements SORTED_MAP.FastSortedSet KEY_VALUE_GENERIC_TYPE {
private class MapEntrySet extends AbstractObjectSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> implements ORDERED_MAP.FastOrderedSet KEY_VALUE_GENERIC_TYPE {
@Override
public boolean addAndMoveToFirst(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); }
@Override
@@ -809,20 +797,9 @@ public class IMMUTABLE_HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_
@Override
public void clear() { throw new UnsupportedOperationException(); }
@Override
public Comparator<MAP.Entry KEY_VALUE_GENERIC_TYPE> comparator() {
return null;
}
@Override
public ObjectSortedSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> subSet(MAP.Entry KEY_VALUE_GENERIC_TYPE fromElement, MAP.Entry KEY_VALUE_GENERIC_TYPE toElement) { throw new UnsupportedOperationException(); }
@Override
public ObjectSortedSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> headSet(MAP.Entry KEY_VALUE_GENERIC_TYPE toElement) { throw new UnsupportedOperationException(); }
@Override
public ObjectSortedSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> tailSet(MAP.Entry KEY_VALUE_GENERIC_TYPE fromElement) { throw new UnsupportedOperationException(); }
}
private final class KeySet extends ABSTRACT_SET KEY_GENERIC_TYPE implements SORTED_SET KEY_GENERIC_TYPE {
private final class KeySet extends ABSTRACT_SET KEY_GENERIC_TYPE implements ORDERED_SET KEY_GENERIC_TYPE {
#if TYPE_OBJECT
@Override
@Deprecated
@@ -1023,18 +1000,6 @@ public class IMMUTABLE_HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_
}
return result;
}
@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(); }
}
private class Values extends VALUE_ABSTRACT_COLLECTION VALUE_GENERIC_TYPE {
@@ -180,6 +180,18 @@ public class ENUM_MAP KEY_ENUM_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE
return getDefaultReturnValue();
}
@Override
public VALUE_TYPE subFrom(T key, VALUE_TYPE value) {
int index = key.ordinal();
if(!isSet(index)) return getDefaultReturnValue();
VALUE_TYPE oldValue = values[index];
values[index] -= value;
if(value < 0 ? (values[index] >= getDefaultReturnValue()) : (values[index] <= getDefaultReturnValue())) {
clear(index);
values[index] = EMPTY_VALUE;
}
return oldValue;
}
#endif
@Override
public boolean containsKey(Object key) {
@@ -1,6 +1,5 @@
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;
@@ -10,15 +9,14 @@ import java.util.Objects;
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.maps.interfaces.ORDERED_MAP;
import speiger.src.collections.PACKAGE.sets.ABSTRACT_SET;
import speiger.src.collections.PACKAGE.sets.SORTED_SET;
import speiger.src.collections.PACKAGE.sets.ORDERED_SET;
import speiger.src.collections.PACKAGE.sets.SET;
import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_ABSTRACT_COLLECTION;
import speiger.src.collections.VALUE_PACKAGE.collections.VALUE_COLLECTION;
@@ -31,7 +29,6 @@ import speiger.src.collections.VALUE_PACKAGE.lists.VALUE_LIST_ITERATOR;
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
@@ -42,7 +39,7 @@ import speiger.src.collections.objects.sets.ObjectSet;
* @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
public class LINKED_ENUM_MAP KEY_ENUM_VALUE_GENERIC_TYPE extends ENUM_MAP KEY_VALUE_GENERIC_TYPE implements ORDERED_MAP KEY_VALUE_GENERIC_TYPE
{
/** The Backing array for links between nodes. Left 32 Bits => Previous Entry, Right 32 Bits => Next Entry */
protected long[] links;
@@ -269,20 +266,6 @@ public class LINKED_ENUM_MAP KEY_ENUM_VALUE_GENERIC_TYPE extends ENUM_MAP KEY_VA
return map;
}
@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();
@@ -433,7 +416,7 @@ public class LINKED_ENUM_MAP KEY_ENUM_VALUE_GENERIC_TYPE extends ENUM_MAP KEY_VA
}
}
private class MapEntrySet extends AbstractObjectSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> implements SORTED_MAP.FastSortedSet KEY_VALUE_GENERIC_TYPE {
private class MapEntrySet extends AbstractObjectSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> implements ORDERED_MAP.FastOrderedSet KEY_VALUE_GENERIC_TYPE {
@Override
public boolean addAndMoveToFirst(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); }
@Override
@@ -558,20 +541,9 @@ public class LINKED_ENUM_MAP KEY_ENUM_VALUE_GENERIC_TYPE extends ENUM_MAP KEY_VA
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 {
private final class KeySet extends ABSTRACT_SET KEY_GENERIC_TYPE implements ORDERED_SET KEY_GENERIC_TYPE {
#if TYPE_OBJECT
@Override
@Deprecated
@@ -684,17 +656,6 @@ public class LINKED_ENUM_MAP KEY_ENUM_VALUE_GENERIC_TYPE extends ENUM_MAP KEY_VA
}
#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 {
@@ -0,0 +1,95 @@
package speiger.src.collections.PACKAGE.maps.interfaces;
import java.util.concurrent.ConcurrentMap;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Function;
/**
* A type specific ConcurrentMap interface that reduces boxing/unboxing.
* Since the interface adds nothing new. It is there just for completion sake.
* @Type(T)
* @ValueType(V)
*/
public interface CONCURRENT_MAP KEY_VALUE_GENERIC_TYPE extends ConcurrentMap<CLASS_TYPE, CLASS_VALUE_TYPE>, MAP KEY_VALUE_GENERIC_TYPE
{
@Override
@Primitive
public default CLASS_VALUE_TYPE compute(CLASS_TYPE key, BiFunction<? super CLASS_TYPE, ? super CLASS_VALUE_TYPE, ? extends CLASS_VALUE_TYPE> mappingFunction) {
return MAP.super.compute(key, mappingFunction);
}
@Override
@Primitive
public default CLASS_VALUE_TYPE computeIfAbsent(CLASS_TYPE key, Function<? super CLASS_TYPE, ? extends CLASS_VALUE_TYPE> mappingFunction) {
return MAP.super.computeIfAbsent(key, mappingFunction);
}
@Override
@Primitive
public default CLASS_VALUE_TYPE computeIfPresent(CLASS_TYPE key, BiFunction<? super CLASS_TYPE, ? super CLASS_VALUE_TYPE, ? extends CLASS_VALUE_TYPE> mappingFunction) {
return MAP.super.computeIfPresent(key, mappingFunction);
}
@Override
@Primitive
public default void forEach(BiConsumer<? super CLASS_TYPE, ? super CLASS_VALUE_TYPE> action) {
MAP.super.forEach(action);
}
@Override
@Primitive
public default CLASS_VALUE_TYPE merge(CLASS_TYPE key, CLASS_VALUE_TYPE value, BiFunction<? super CLASS_VALUE_TYPE, ? super CLASS_VALUE_TYPE, ? extends CLASS_VALUE_TYPE> mappingFunction) {
return MAP.super.merge(key, value, mappingFunction);
}
#if TYPE_OBJECT && VALUE_OBJECT
@Override
public CLASS_VALUE_TYPE getOrDefault(Object key, CLASS_VALUE_TYPE defaultValue);
@Override
public CLASS_VALUE_TYPE putIfAbsent(CLASS_TYPE key, CLASS_VALUE_TYPE value);
@Override
public boolean remove(Object key, Object value);
@Override
public boolean replace(CLASS_TYPE key, CLASS_VALUE_TYPE oldValue, CLASS_VALUE_TYPE newValue);
@Override
public CLASS_VALUE_TYPE replace(CLASS_TYPE key, CLASS_VALUE_TYPE value);
#else
@Primitive
@Override
public default CLASS_VALUE_TYPE getOrDefault(Object key, CLASS_VALUE_TYPE defaultValue) {
return MAP.super.getOrDefault(key, defaultValue);
}
@Override
@Primitive
public default CLASS_VALUE_TYPE putIfAbsent(CLASS_TYPE key, CLASS_VALUE_TYPE value) {
return MAP.super.putIfAbsent(key, value);
}
@Override
@Deprecated
public default boolean remove(Object key, Object value) {
return MAP.super.remove(key, value);
}
@Override
@Deprecated
public default boolean replace(CLASS_TYPE key, CLASS_VALUE_TYPE oldValue, CLASS_VALUE_TYPE newValue) {
return MAP.super.replace(key, oldValue, newValue);
}
@Override
@Deprecated
public default CLASS_VALUE_TYPE replace(CLASS_TYPE key, CLASS_VALUE_TYPE value) {
return MAP.super.replace(key, value);
}
#endif
@Override
@Deprecated
public default void replaceAll(BiFunction<? super CLASS_TYPE, ? super CLASS_VALUE_TYPE, ? extends CLASS_VALUE_TYPE> mappingFunction) {
MAP.super.replaceAll(mappingFunction);
}
}
@@ -31,6 +31,7 @@ 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.maps.impl.misc.ARRAY_MAP;
import speiger.src.collections.PACKAGE.maps.impl.concurrent.CONCURRENT_HASH_MAP;
#if TYPE_OBJECT
import speiger.src.collections.PACKAGE.maps.impl.misc.ENUM_MAP;
import speiger.src.collections.PACKAGE.maps.impl.misc.LINKED_ENUM_MAP;
@@ -179,6 +180,17 @@ public interface MAP KEY_VALUE_GENERIC_TYPE extends Map<CLASS_TYPE, CLASS_VALUE_
*/
public void addToAll(MAP KEY_VALUE_GENERIC_TYPE m);
/**
* A Helper method to subtract from primitive from each other. If the key is not present it will just return the defaultValue
* How the implementation works is that it will subtract from the current value (if not present it will do nothing) and fence it to the {@link #getDefaultReturnValue()}
* If the fence is reached the element will be automaticall removed
*
* @param key that should be subtract from
* @param value that should be subtract
* @return the last present or default return value
*/
public VALUE_TYPE subFrom(KEY_TYPE key, VALUE_TYPE value);
#endif
/**
* Type Specific function for the bull putting of values
@@ -1497,6 +1509,14 @@ public interface MAP KEY_VALUE_GENERIC_TYPE extends Map<CLASS_TYPE, CLASS_VALUE_
return putElements(new LINKED_CUSTOM_HASH_MAPKV_BRACES(size, strategy));
}
/**
* Builds the Keys and Values into a Concurrent Hash Map
* @return a CONCURRENT_HASH_MAP
*/
public CONCURRENT_HASH_MAP KEY_VALUE_GENERIC_TYPE concurrentMap() {
return putElements(new CONCURRENT_HASH_MAPKV_BRACES(size));
}
/**
* Builds the Keys and Values into a Array Map
* @return a ARRAY_MAP
@@ -207,13 +207,13 @@ public interface NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE extends SORTED_MAP KEY_VAL
default NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE tailMap(CLASS_TYPE fromKey) { return tailMap(OBJ_TO_KEY(fromKey), true); }
#else
@Override
default MAP.Entry KEY_VALUE_GENERIC_TYPE lowerEntry(CLASS_TYPE key) { return lowerEntry(OBJ_TO_KEY(key)); }
MAP.Entry KEY_VALUE_GENERIC_TYPE lowerEntry(CLASS_TYPE key);
@Override
default MAP.Entry KEY_VALUE_GENERIC_TYPE floorEntry(CLASS_TYPE key) { return floorEntry(OBJ_TO_KEY(key)); }
MAP.Entry KEY_VALUE_GENERIC_TYPE floorEntry(CLASS_TYPE key);
@Override
default MAP.Entry KEY_VALUE_GENERIC_TYPE ceilingEntry(CLASS_TYPE key) { return ceilingEntry(OBJ_TO_KEY(key)); }
MAP.Entry KEY_VALUE_GENERIC_TYPE ceilingEntry(CLASS_TYPE key);
@Override
default MAP.Entry KEY_VALUE_GENERIC_TYPE higherEntry(CLASS_TYPE key) { return higherEntry(OBJ_TO_KEY(key)); }
MAP.Entry KEY_VALUE_GENERIC_TYPE higherEntry(CLASS_TYPE key);
@Override
public NAVIGABLE_MAP KEY_VALUE_GENERIC_TYPE subMap(CLASS_TYPE fromKey, boolean fromInclusive, CLASS_TYPE toKey, boolean toInclusive);
@@ -0,0 +1,138 @@
package speiger.src.collections.PACKAGE.maps.interfaces;
import speiger.src.collections.PACKAGE.utils.maps.MAPS;
import speiger.src.collections.objects.collections.ObjectBidirectionalIterator;
import speiger.src.collections.objects.sets.ObjectOrderedSet;
/**
* A Special Map Interface giving Access to some really usefull functions
* The Idea behind this interface is to allow access to functions that give control to the Order of elements.
* Since Linked implementations as examples can be reordered outside of the Insertion Order.
* This interface provides basic access to such functions while also providing some Sorted/NaivgableMap implementations that still fit into here.
*
* @Type(T)
* @ValueType(V)
*/
public interface ORDERED_MAP KEY_VALUE_GENERIC_TYPE extends MAP KEY_VALUE_GENERIC_TYPE
{
/**
* A customized put method that allows you to insert into the first index.
* @param key the key that should be inserted
* @param value the value that should be inserted
* @return the previous present or default return value
* @see java.util.Map#put(Object, Object)
*/
public VALUE_TYPE putAndMoveToFirst(KEY_TYPE key, VALUE_TYPE value);
/**
* A customized put method that allows you to insert into the last index. (This may be nessesary depending on the implementation)
* @param key the key that should be inserted
* @param value the value that should be inserted
* @return the previous present or default return value
* @see java.util.Map#put(Object, Object)
*/
public VALUE_TYPE putAndMoveToLast(KEY_TYPE key, VALUE_TYPE value);
/**
* A specific move method to move a given key/value to the first index.
* @param key that should be moved to the first index
* @return true if the value was moved.
* @note returns false if the value was not present in the first place
*/
public boolean moveToFirst(KEY_TYPE key);
/**
* A specific move method to move a given key/value to the last index.
* @param key that should be moved to the first last
* @return true if the value was moved.
* @note returns false if the value was not present in the first place
*/
public boolean moveToLast(KEY_TYPE key);
/**
* A Specific get method that allows to move teh given key/value int the first index.
* @param key that is searched for
* @return the given value for the requested key or default return value
*/
public VALUE_TYPE getAndMoveToFirst(KEY_TYPE key);
/**
* A Specific get method that allows to move teh given key/value int the last index.
* @param key that is searched for
* @return the given value for the requested key or default return value
*/
public VALUE_TYPE getAndMoveToLast(KEY_TYPE key);
/**
* A method to get the first Key of a Map.
* @return the first key in the map
*/
public KEY_TYPE FIRST_ENTRY_KEY();
/**
* A method to get and remove the first Key of a Map.
* @return the first key in the map
*/
public KEY_TYPE POLL_FIRST_ENTRY_KEY();
/**
* A method to get the last Key of a Map.
* @return the last key in the map
*/
public KEY_TYPE LAST_ENTRY_KEY();
/**
* A method to get and remove the last Key of a Map.
* @return the last key in the map
*/
public KEY_TYPE POLL_LAST_ENTRY_KEY();
/**
* A method to get the first Value of a Map.
* @return the first key in the map
*/
public VALUE_TYPE FIRST_ENTRY_VALUE();
/**
* A method to get the last Value of a Map.
* @return the last key in the map
*/
public VALUE_TYPE LAST_ENTRY_VALUE();
@Override
public ORDERED_MAP KEY_VALUE_GENERIC_TYPE copy();
/**
* Creates a Wrapped SortedMap that is Synchronized
* @return a new SortedMap that is synchronized
* @see MAPS#synchronize
*/
@Override
public default ORDERED_MAP KEY_VALUE_GENERIC_TYPE synchronize() { return MAPS.synchronize(this); }
/**
* Creates a Wrapped SortedMap that is Synchronized
* @param mutex is the controller of the synchronization block
* @return a new SortedMap Wrapper that is synchronized
* @see MAPS#synchronize
*/
@Override
public default ORDERED_MAP KEY_VALUE_GENERIC_TYPE synchronize(Object mutex) { return MAPS.synchronize(this, mutex); }
/**
* Creates a Wrapped SortedMap that is unmodifiable
* @return a new SortedMap Wrapper that is unmodifiable
* @see MAPS#unmodifiable
*/
@Override
public default ORDERED_MAP KEY_VALUE_GENERIC_TYPE unmodifiable() { return MAPS.unmodifiable(this); }
/**
* Fast Ordered Entry Set that allows for a faster Entry Iterator by recycling the Entry Object and just exchanging 1 internal value
* @Type(T)
* @ValueType(V)
*/
interface FastOrderedSet KEY_VALUE_GENERIC_TYPE extends MAP.FastEntrySet KEY_VALUE_GENERIC_TYPE, ObjectOrderedSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> {
@Override
public ObjectBidirectionalIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> fastIterator();
/**
* Fast iterator that recycles the given Entry object to improve speed and reduce object allocation
* @param fromElement that is going to be started from.
* @return a improved iterator that starts from the desired element
*/
public ObjectBidirectionalIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> fastIterator(KEY_TYPE fromElement);
}
}
@@ -19,60 +19,11 @@ import speiger.src.collections.objects.collections.ObjectBidirectionalIterator;
*
* @Type(T)
* @ValueType(V)
* @note ORDERED_MAP is only extended until 0.6.0 for Compat reasons.
* The supported classes already implement ORDERED_MAP directly and will remove SORTED_MAP implementations in favor of ORDERED_MAP instead
*/
public interface SORTED_MAP KEY_VALUE_GENERIC_TYPE extends SortedMap<CLASS_TYPE, CLASS_VALUE_TYPE>, MAP KEY_VALUE_GENERIC_TYPE
{
/**
* A customized put method that allows you to insert into the first index.
* @param key the key that should be inserted
* @param value the value that should be inserted
* @return the previous present or default return value
* @see java.util.Map#put(Object, Object)
* @note some implementations do not support this method
*/
public VALUE_TYPE putAndMoveToFirst(KEY_TYPE key, VALUE_TYPE value);
/**
* A customized put method that allows you to insert into the last index. (This may be nessesary depending on the implementation)
* @param key the key that should be inserted
* @param value the value that should be inserted
* @return the previous present or default return value
* @see java.util.Map#put(Object, Object)
* @note some implementations do not support this method
*/
public VALUE_TYPE putAndMoveToLast(KEY_TYPE key, VALUE_TYPE value);
/**
* A specific move method to move a given key/value to the first index.
* @param key that should be moved to the first index
* @return true if the value was moved.
* @note returns false if the value was not present in the first place
* @note some implementations do not support this method
*/
public boolean moveToFirst(KEY_TYPE key);
/**
* A specific move method to move a given key/value to the last index.
* @param key that should be moved to the first last
* @return true if the value was moved.
* @note returns false if the value was not present in the first place
* @note some implementations do not support this method
*/
public boolean moveToLast(KEY_TYPE key);
/**
* A Specific get method that allows to move teh given key/value int the first index.
* @param key that is searched for
* @return the given value for the requested key or default return value
* @note some implementations do not support this method
*/
public VALUE_TYPE getAndMoveToFirst(KEY_TYPE key);
/**
* A Specific get method that allows to move teh given key/value int the last index.
* @param key that is searched for
* @return the given value for the requested key or default return value
* @note some implementations do not support this method
*/
public VALUE_TYPE getAndMoveToLast(KEY_TYPE key);
@Override
public COMPARATOR KEY_GENERIC_TYPE comparator();
@@ -204,11 +155,11 @@ public interface SORTED_MAP KEY_VALUE_GENERIC_TYPE extends SortedMap<CLASS_TYPE,
public VALUE_TYPE LAST_ENTRY_VALUE();
@Override
public default SORTED_MAP KEY_VALUE_GENERIC_TYPE subMap(CLASS_TYPE fromKey, CLASS_TYPE toKey) { return subMap(OBJ_TO_KEY(fromKey), OBJ_TO_KEY(toKey)); }
public SORTED_MAP KEY_VALUE_GENERIC_TYPE subMap(CLASS_TYPE fromKey, CLASS_TYPE toKey);
@Override
public default SORTED_MAP KEY_VALUE_GENERIC_TYPE headMap(CLASS_TYPE toKey) { return headMap(OBJ_TO_KEY(toKey)); }
public SORTED_MAP KEY_VALUE_GENERIC_TYPE headMap(CLASS_TYPE toKey);
@Override
public default SORTED_MAP KEY_VALUE_GENERIC_TYPE tailMap(CLASS_TYPE fromKey) { return tailMap(OBJ_TO_KEY(fromKey)); }
public SORTED_MAP KEY_VALUE_GENERIC_TYPE tailMap(CLASS_TYPE fromKey);
#endif
/**
@@ -219,6 +170,11 @@ public interface SORTED_MAP KEY_VALUE_GENERIC_TYPE extends SortedMap<CLASS_TYPE,
interface FastSortedSet KEY_VALUE_GENERIC_TYPE extends MAP.FastEntrySet KEY_VALUE_GENERIC_TYPE, ObjectSortedSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> {
@Override
public ObjectBidirectionalIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> fastIterator();
/**
* Fast iterator that recycles the given Entry object to improve speed and reduce object allocation
* @param fromElement that is going to be started from.
* @return a improved iterator that starts from the desired element
*/
public ObjectBidirectionalIterator<MAP.Entry KEY_VALUE_GENERIC_TYPE> fastIterator(KEY_TYPE fromElement);
}
}
@@ -82,7 +82,7 @@ public class ARRAY_FIFO_QUEUE KEY_GENERIC_TYPE extends ABSTRACT_PRIORITY_QUEUE K
*/
public ARRAY_FIFO_QUEUE(int capacity) {
if (capacity < 0) throw new IllegalArgumentException("Initial capacity (" + capacity + ") is negative");
array = NEW_KEY_ARRAY(Math.max(MIN_CAPACITY, capacity));
array = NEW_KEY_ARRAY(Math.max(MIN_CAPACITY, capacity+1));
minCapacity = array.length;
}
@@ -106,16 +106,21 @@ public class ARRAY_FIFO_QUEUE KEY_GENERIC_TYPE extends ABSTRACT_PRIORITY_QUEUE K
@Override
public void clear() {
if(first != last) {
#if TYPE_OBJECT
Arrays.fill(array, null);
Arrays.fill(array, null);
#endif
first = last = 0;
first = last = 0;
}
else if(first != 0) {
first = last = 0;
}
}
@Override
public void enqueue(KEY_TYPE e) {
array[last] = e;
last = ++last % array.length;
array[last++] = e;
if(last == array.length) last = 0;
if(last == first) expand();
}
@@ -133,7 +138,7 @@ public class ARRAY_FIFO_QUEUE KEY_GENERIC_TYPE extends ABSTRACT_PRIORITY_QUEUE K
#if TYPE_OBJECT
array[first] = null;
#endif
first = ++first % array.length;
if(++first == array.length) first = 0;
reduce();
return data;
}
@@ -152,8 +157,9 @@ public class ARRAY_FIFO_QUEUE KEY_GENERIC_TYPE extends ABSTRACT_PRIORITY_QUEUE K
@Override
public KEY_TYPE peek(int index) {
if(first == last || index < 0 || index > size()) throw new NoSuchElementException();
return array[(first + index) % array.length];
if(first == last || index < 0 || index >= size()) throw new NoSuchElementException();
index += first;
return index >= array.length ? array[index-array.length] : array[index];
}
@Override
@@ -428,6 +434,7 @@ public class ARRAY_FIFO_QUEUE KEY_GENERIC_TYPE extends ABSTRACT_PRIORITY_QUEUE K
@Override
public KEY_TYPE NEXT() {
if(!hasNext()) throw new NoSuchElementException();
KEY_TYPE value = array[index];
removeIndex(index);
index = ++index % array.length;
@@ -19,6 +19,7 @@ import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUME
import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR;
import speiger.src.collections.PACKAGE.utils.ARRAYS;
import speiger.src.collections.utils.SanityChecks;
/**
* A Array Priority Queue, this is a very unoptimized implementation of the PriorityQueue for very specific usecases.
@@ -70,7 +71,6 @@ public class ARRAY_PRIORITY_QUEUE KEY_GENERIC_TYPE extends ABSTRACT_PRIORITY_QUE
public ARRAY_PRIORITY_QUEUE(int size, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) {
if(size < 0) throw new IllegalAccessError("Size has to be 0 or positive");
if(size > 0) array = NEW_KEY_ARRAY(size);
this.size = size;
comparator = comp;
}
@@ -187,7 +187,7 @@ public class ARRAY_PRIORITY_QUEUE KEY_GENERIC_TYPE extends ABSTRACT_PRIORITY_QUE
@Override
public void enqueue(KEY_TYPE e) {
if(size == array.length) array = Arrays.copyOf(array, size+1);
if(size == array.length) array = Arrays.copyOf(array, (int)Math.max(Math.min((long)array.length + (long)(array.length >> 1), (long)SanityChecks.MAX_ARRAY_SIZE), size+1));
if(firstIndex != -1){
int compare = comparator == null ? COMPAREABLE_TO_KEY(e, array[firstIndex]) : comparator.compare(e, array[firstIndex]);
if(compare < 0) firstIndex = size;
@@ -414,6 +414,7 @@ public class ARRAY_PRIORITY_QUEUE KEY_GENERIC_TYPE extends ABSTRACT_PRIORITY_QUE
@Override
public KEY_TYPE NEXT() {
if(!hasNext()) throw new NoSuchElementException();
return dequeue();
}
}
@@ -19,6 +19,7 @@ import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUME
import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR;
import speiger.src.collections.PACKAGE.utils.ARRAYS;
import speiger.src.collections.utils.SanityChecks;
/**
* A Simple Heap base Priority Queue implementation
@@ -66,7 +67,6 @@ public class HEAP_PRIORITY_QUEUE KEY_GENERIC_TYPE extends ABSTRACT_PRIORITY_QUEU
*/
public HEAP_PRIORITY_QUEUE(int size, COMPARATOR KEY_SUPER_GENERIC_TYPE comp) {
if(size > 0) array = NEW_KEY_ARRAY(size);
this.size = size;
comparator = comp;
}
@@ -207,7 +207,7 @@ public class HEAP_PRIORITY_QUEUE KEY_GENERIC_TYPE extends ABSTRACT_PRIORITY_QUEU
@Override
public void enqueue(KEY_TYPE e) {
if(size == array.length) array = Arrays.copyOf(array, size + 1);
if(size == array.length) array = Arrays.copyOf(array, (int)Math.max(Math.min((long)array.length + (long)(array.length >> 1), (long)SanityChecks.MAX_ARRAY_SIZE), size+1));
array[size++] = e;
ARRAYS.shiftUp(array, size-1, comparator);
}
@@ -389,6 +389,7 @@ public class HEAP_PRIORITY_QUEUE KEY_GENERIC_TYPE extends ABSTRACT_PRIORITY_QUEU
@Override
public KEY_TYPE NEXT() {
if(!hasNext()) throw new NoSuchElementException();
return dequeue();
}
}
File diff suppressed because it is too large Load Diff
@@ -14,6 +14,11 @@ import speiger.src.collections.PACKAGE.collections.ITERATOR;
*/
public abstract class ABSTRACT_SET KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION KEY_GENERIC_TYPE implements SET KEY_GENERIC_TYPE
{
#if TYPE_OBJECT
@Override
public KEY_TYPE addOrGet(KEY_TYPE o) { throw new UnsupportedOperationException(); }
#endif
@Override
public abstract ITERATOR KEY_GENERIC_TYPE iterator();
@Override
@@ -3,7 +3,6 @@ package speiger.src.collections.PACKAGE.sets;
import java.util.Arrays;
import java.util.Collection;
#if TYPE_OBJECT
import java.util.Comparator;
import java.util.function.Consumer;
import java.util.function.BiFunction;
#endif
@@ -21,7 +20,6 @@ import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUME
import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR;
#if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.functions.COMPARATOR;
import speiger.src.collections.PACKAGE.functions.CONSUMER;
import speiger.src.collections.objects.utils.ObjectArrays;
#endif
@@ -36,7 +34,7 @@ import speiger.src.collections.PACKAGE.utils.ARRAYS;
* This implementation does not shrink the backing array
* @Type(T)
*/
public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE implements SORTED_SET KEY_GENERIC_TYPE
public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE implements ORDERED_SET KEY_GENERIC_TYPE
{
/** The Backing Array */
protected transient KEY_TYPE[] data;
@@ -132,6 +130,17 @@ public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE im
return false;
}
#if TYPE_OBJECT
@Override
public KEY_TYPE addOrGet(KEY_TYPE o) {
int index = findIndex(o);
if(index != -1) return data[index];
if(data.length == size) data = Arrays.copyOf(data, size == 0 ? 2 : size * 2);
data[size++] = o;
return o;
}
#endif
@Override
public boolean addAndMoveToFirst(KEY_TYPE o) {
int index = findIndex(o);
@@ -499,28 +508,6 @@ public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE im
throw new NoSuchElementException();
}
@Override
public SORTED_SET KEY_GENERIC_TYPE subSet(KEY_TYPE fromElement, KEY_TYPE toElement) {
int fromIndex = findIndex(fromElement);
int toIndex = findIndex(toElement);
if(fromIndex == -1 || toIndex == -1) throw new NoSuchElementException();
return new SubSet(fromIndex, toIndex - fromIndex + 1);
}
@Override
public SORTED_SET KEY_GENERIC_TYPE headSet(KEY_TYPE toElement) {
int toIndex = findIndex(toElement);
if(toIndex == -1) throw new NoSuchElementException();
return new SubSet(0, toIndex+1);
}
@Override
public SORTED_SET KEY_GENERIC_TYPE tailSet(KEY_TYPE fromElement) {
int fromIndex = findIndex(fromElement);
if(fromIndex == -1) throw new NoSuchElementException();
return new SubSet(fromIndex, size - fromIndex);
}
public ARRAY_SET KEY_GENERIC_TYPE copy() {
ARRAY_SET KEY_GENERIC_TYPE set = new ARRAY_SETBRACES();
set.data = Arrays.copyOf(data, data.length);
@@ -528,11 +515,6 @@ public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE im
return set;
}
@Override
public COMPARATOR KEY_GENERIC_TYPE comparator() {
return null;
}
@Override
public void clear() {
size = 0;
@@ -573,345 +555,346 @@ public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE im
return a;
}
private class SubSet extends ABSTRACT_SET KEY_GENERIC_TYPE implements SORTED_SET KEY_GENERIC_TYPE {
int offset;
int length;
SubSet(int offset, int length) {
this.offset = offset;
this.length = length;
}
int end() { return offset+length; }
@Override
public boolean add(KEY_TYPE o) {
int index = findIndex(o);
if(index == -1) {
if(data.length == size) data = Arrays.copyOf(data, size == 0 ? 2 : size * 2);
if(end() != size) System.arraycopy(data, end(), data, end()+1, size-(offset+length));
data[end()] = o;
size++;
length++;
return true;
}
return false;
}
@Override
public boolean addAndMoveToFirst(KEY_TYPE o) {
int index = findIndex(o);
if(index == -1) {
if(data.length == size) data = Arrays.copyOf(data, size == 0 ? 2 : size * 2);
System.arraycopy(data, offset, data, offset+1, size-offset);
data[offset] = o;
size++;
length++;
return true;
}
else if(index != 0) {
o = data[index];
System.arraycopy(data, offset, data, offset+1, index-offset);
data[offset] = o;
}
return false;
}
@Override
public boolean addAndMoveToLast(KEY_TYPE o) {
int index = findIndex(o);
if(index == -1) {
if(data.length == size) data = Arrays.copyOf(data, size == 0 ? 2 : size * 2);
System.arraycopy(data, end()+1, data, end(), size-end());
data[end()] = o;
size++;
length++;
return true;
}
else if(index != 0) {
o = data[index];
System.arraycopy(data, offset+1, data, offset, index-offset);
data[offset+length] = o;
}
return false;
}
@Override
public boolean moveToFirst(KEY_TYPE o) {
int index = findIndex(o);
if(index > offset) {
o = data[index];
System.arraycopy(data, offset, data, offset+1, index-offset);
data[offset] = o;
return true;
}
return false;
}
@Override
public boolean moveToLast(KEY_TYPE o) {
int index = findIndex(o);
if(index != -1 && index < end()-1) {
o = data[index];
System.arraycopy(data, index+1, data, index, end()-index-1);
data[end()-1] = o;
return true;
}
return false;
}
#if !TYPE_OBJECT
@Override
public boolean contains(KEY_TYPE e) {
return findIndex(e) != -1;
}
#endif
@Override
public boolean contains(Object e) {
return findIndex(e) != -1;
}
@Override
public KEY_TYPE FIRST_KEY() {
if(length == 0) throw new NoSuchElementException();
return data[offset];
}
@Override
public KEY_TYPE LAST_KEY() {
if(length == 0) throw new NoSuchElementException();
return data[end()-1];
}
#if !TYPE_OBJECT
@Override
public boolean remove(KEY_TYPE o) {
int index = findIndex(o);
if(index != -1) {
size--;
length--;
if(index != size) System.arraycopy(data, index+1, data, index, size - index);
return true;
}
return false;
}
#endif
@Override
public boolean remove(Object o) {
int index = findIndex(o);
if(index != -1) {
size--;
length--;
if(index != size) System.arraycopy(data, index+1, data, index, size - index);
#if TYPE_OBJECT
data[size] = EMPTY_KEY_VALUE;
#endif
return true;
}
return false;
}
@Override
public KEY_TYPE POLL_FIRST_KEY() {
if(length == 0) throw new NoSuchElementException();
size--;
length--;
KEY_TYPE result = data[offset];
System.arraycopy(data, offset+1, data, offset, size-offset);
#if TYPE_OBJECT
data[size] = EMPTY_KEY_VALUE;
#endif
return result;
}
@Override
public KEY_TYPE POLL_LAST_KEY() {
if(length == 0) throw new NoSuchElementException();
KEY_TYPE result = data[offset+length];
size--;
length--;
System.arraycopy(data, end()+1, data, end(), size-end());
#if TYPE_OBJECT
data[size] = EMPTY_KEY_VALUE;
#endif
return result;
}
@Override
public COMPARATOR KEY_GENERIC_TYPE comparator() {
return null;
}
@Override
public BI_ITERATOR KEY_GENERIC_TYPE iterator() {
return new SetIterator(offset);
}
@Override
public BI_ITERATOR KEY_GENERIC_TYPE iterator(KEY_TYPE fromElement) {
int index = findIndex(fromElement);
if(index != -1) return new SetIterator(index);
throw new NoSuchElementException();
}
@Override
public SubSet copy() { throw new UnsupportedOperationException(); }
@Override
public SORTED_SET KEY_GENERIC_TYPE subSet(KEY_TYPE fromElement, KEY_TYPE toElement) {
int fromIndex = findIndex(fromElement);
int toIndex = findIndex(toElement);
if(fromIndex == -1 || toIndex == -1) throw new NoSuchElementException();
return new SubSet(fromIndex, toIndex - fromIndex + 1);
}
@Override
public SORTED_SET KEY_GENERIC_TYPE headSet(KEY_TYPE toElement) {
int toIndex = findIndex(toElement);
if(toIndex == -1) throw new NoSuchElementException();
return new SubSet(0, toIndex+1);
}
@Override
public SORTED_SET KEY_GENERIC_TYPE tailSet(KEY_TYPE fromElement) {
int fromIndex = findIndex(fromElement);
if(fromIndex == -1) throw new NoSuchElementException();
return new SubSet(fromIndex, size - fromIndex);
}
@Override
public int size() {
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
protected int findIndex(KEY_TYPE o) {
for(int i = length-1;i>=0;i--)
if(KEY_EQUALS(data[offset+i], o)) return i + offset;
return -1;
}
#endif
protected int findIndex(Object o) {
for(int i = length-1;i>=0;i--)
if(EQUALS_KEY_TYPE(data[offset+i], o)) return i + offset;
return -1;
}
private class SetIterator implements LIST_ITERATOR KEY_GENERIC_TYPE {
int index;
int lastReturned = -1;
public SetIterator(int index) {
this.index = index;
}
@Override
public boolean hasNext() {
return index < size();
}
@Override
public KEY_TYPE NEXT() {
if(!hasNext()) throw new NoSuchElementException();
lastReturned = index;
return data[index++];
}
@Override
public boolean hasPrevious() {
return index > 0;
}
@Override
public KEY_TYPE PREVIOUS() {
if(!hasPrevious()) throw new NoSuchElementException();
lastReturned = index;
return data[index--];
}
@Override
public int nextIndex() {
return index;
}
@Override
public int previousIndex() {
return index-1;
}
@Override
public void remove() {
if(lastReturned == -1)
throw new IllegalStateException();
SubSet.this.remove(data[lastReturned]);
if(lastReturned < index)
index--;
lastReturned = -1;
}
#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
@Override
public int skip(int amount) {
if(amount < 0) throw new IllegalStateException("Negative Numbers are not allowed");
int steps = Math.min(amount, (size() - 1) - index);
index += steps;
return steps;
}
@Override
public int back(int amount) {
if(amount < 0) throw new IllegalStateException("Negative Numbers are not allowed");
int steps = Math.min(amount, index);
index -= steps;
return steps;
}
}
}
// Disabled until a Proper Implementation can be thought out or it is decided that the interface is thrown out.
// private class SubSet extends ABSTRACT_SET KEY_GENERIC_TYPE implements SORTED_SET KEY_GENERIC_TYPE {
// int offset;
// int length;
//
// SubSet(int offset, int length) {
// this.offset = offset;
// this.length = length;
// }
//
// int end() { return offset+length; }
//
// @Override
// public boolean add(KEY_TYPE o) {
// int index = findIndex(o);
// if(index == -1) {
// if(data.length == size) data = Arrays.copyOf(data, size == 0 ? 2 : size * 2);
// if(end() != size) System.arraycopy(data, end(), data, end()+1, size-(offset+length));
// data[end()] = o;
// size++;
// length++;
// return true;
// }
// return false;
// }
//
// @Override
// public boolean addAndMoveToFirst(KEY_TYPE o) {
// int index = findIndex(o);
// if(index == -1) {
// if(data.length == size) data = Arrays.copyOf(data, size == 0 ? 2 : size * 2);
// System.arraycopy(data, offset, data, offset+1, size-offset);
// data[offset] = o;
// size++;
// length++;
// return true;
// }
// else if(index != 0) {
// o = data[index];
// System.arraycopy(data, offset, data, offset+1, index-offset);
// data[offset] = o;
// }
// return false;
// }
//
// @Override
// public boolean addAndMoveToLast(KEY_TYPE o) {
// int index = findIndex(o);
// if(index == -1) {
// if(data.length == size) data = Arrays.copyOf(data, size == 0 ? 2 : size * 2);
// System.arraycopy(data, end()+1, data, end(), size-end());
// data[end()] = o;
// size++;
// length++;
// return true;
// }
// else if(index != 0) {
// o = data[index];
// System.arraycopy(data, offset+1, data, offset, index-offset);
// data[offset+length] = o;
// }
// return false;
// }
//
// @Override
// public boolean moveToFirst(KEY_TYPE o) {
// int index = findIndex(o);
// if(index > offset) {
// o = data[index];
// System.arraycopy(data, offset, data, offset+1, index-offset);
// data[offset] = o;
// return true;
// }
// return false;
// }
//
// @Override
// public boolean moveToLast(KEY_TYPE o) {
// int index = findIndex(o);
// if(index != -1 && index < end()-1) {
// o = data[index];
// System.arraycopy(data, index+1, data, index, end()-index-1);
// data[end()-1] = o;
// return true;
// }
// return false;
// }
//
//#if !TYPE_OBJECT
// @Override
// public boolean contains(KEY_TYPE e) {
// return findIndex(e) != -1;
// }
//
//#endif
// @Override
// public boolean contains(Object e) {
// return findIndex(e) != -1;
// }
//
// @Override
// public KEY_TYPE FIRST_KEY() {
// if(length == 0) throw new NoSuchElementException();
// return data[offset];
// }
//
// @Override
// public KEY_TYPE LAST_KEY() {
// if(length == 0) throw new NoSuchElementException();
// return data[end()-1];
// }
//
//#if !TYPE_OBJECT
// @Override
// public boolean remove(KEY_TYPE o) {
// int index = findIndex(o);
// if(index != -1) {
// size--;
// length--;
// if(index != size) System.arraycopy(data, index+1, data, index, size - index);
// return true;
// }
// return false;
// }
//
//#endif
// @Override
// public boolean remove(Object o) {
// int index = findIndex(o);
// if(index != -1) {
// size--;
// length--;
// if(index != size) System.arraycopy(data, index+1, data, index, size - index);
//#if TYPE_OBJECT
// data[size] = EMPTY_KEY_VALUE;
//#endif
// return true;
// }
// return false;
// }
//
// @Override
// public KEY_TYPE POLL_FIRST_KEY() {
// if(length == 0) throw new NoSuchElementException();
// size--;
// length--;
// KEY_TYPE result = data[offset];
// System.arraycopy(data, offset+1, data, offset, size-offset);
//#if TYPE_OBJECT
// data[size] = EMPTY_KEY_VALUE;
//#endif
// return result;
// }
//
// @Override
// public KEY_TYPE POLL_LAST_KEY() {
// if(length == 0) throw new NoSuchElementException();
// KEY_TYPE result = data[offset+length];
// size--;
// length--;
// System.arraycopy(data, end()+1, data, end(), size-end());
//#if TYPE_OBJECT
// data[size] = EMPTY_KEY_VALUE;
//#endif
// return result;
// }
//
// @Override
// public COMPARATOR KEY_GENERIC_TYPE comparator() {
// return null;
// }
//
// @Override
// public BI_ITERATOR KEY_GENERIC_TYPE iterator() {
// return new SetIterator(offset);
// }
//
// @Override
// public BI_ITERATOR KEY_GENERIC_TYPE iterator(KEY_TYPE fromElement) {
// int index = findIndex(fromElement);
// if(index != -1) return new SetIterator(index);
// throw new NoSuchElementException();
// }
//
// @Override
// public SubSet copy() { throw new UnsupportedOperationException(); }
//
// @Override
// public SORTED_SET KEY_GENERIC_TYPE subSet(KEY_TYPE fromElement, KEY_TYPE toElement) {
// int fromIndex = findIndex(fromElement);
// int toIndex = findIndex(toElement);
// if(fromIndex == -1 || toIndex == -1) throw new NoSuchElementException();
// return new SubSet(fromIndex, toIndex - fromIndex + 1);
// }
//
// @Override
// public SORTED_SET KEY_GENERIC_TYPE headSet(KEY_TYPE toElement) {
// int toIndex = findIndex(toElement);
// if(toIndex == -1) throw new NoSuchElementException();
// return new SubSet(0, toIndex+1);
// }
//
// @Override
// public SORTED_SET KEY_GENERIC_TYPE tailSet(KEY_TYPE fromElement) {
// int fromIndex = findIndex(fromElement);
// if(fromIndex == -1) throw new NoSuchElementException();
// return new SubSet(fromIndex, size - fromIndex);
// }
//
// @Override
// public int size() {
// 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
// protected int findIndex(KEY_TYPE o) {
// for(int i = length-1;i>=0;i--)
// if(KEY_EQUALS(data[offset+i], o)) return i + offset;
// return -1;
// }
//
//#endif
// protected int findIndex(Object o) {
// for(int i = length-1;i>=0;i--)
// if(EQUALS_KEY_TYPE(data[offset+i], o)) return i + offset;
// return -1;
// }
//
// private class SetIterator implements LIST_ITERATOR KEY_GENERIC_TYPE {
// int index;
// int lastReturned = -1;
//
// public SetIterator(int index) {
// this.index = index;
// }
//
// @Override
// public boolean hasNext() {
// return index < size();
// }
//
// @Override
// public KEY_TYPE NEXT() {
// if(!hasNext()) throw new NoSuchElementException();
// lastReturned = index;
// return data[index++];
// }
//
// @Override
// public boolean hasPrevious() {
// return index > 0;
// }
//
// @Override
// public KEY_TYPE PREVIOUS() {
// if(!hasPrevious()) throw new NoSuchElementException();
// lastReturned = index;
// return data[index--];
// }
//
// @Override
// public int nextIndex() {
// return index;
// }
//
// @Override
// public int previousIndex() {
// return index-1;
// }
//
// @Override
// public void remove() {
// if(lastReturned == -1)
// throw new IllegalStateException();
// SubSet.this.remove(data[lastReturned]);
// if(lastReturned < index)
// index--;
// lastReturned = -1;
// }
//
// #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
// @Override
// public int skip(int amount) {
// if(amount < 0) throw new IllegalStateException("Negative Numbers are not allowed");
// int steps = Math.min(amount, (size() - 1) - index);
// index += steps;
// return steps;
// }
//
// @Override
// public int back(int amount) {
// if(amount < 0) throw new IllegalStateException("Negative Numbers are not allowed");
// int steps = Math.min(amount, index);
// index -= steps;
// return steps;
// }
// }
// }
private class SetIterator implements LIST_ITERATOR KEY_GENERIC_TYPE {
int index;
@@ -1,7 +1,6 @@
package speiger.src.collections.PACKAGE.sets;
#if TYPE_OBJECT
import java.util.Comparator;
import java.util.function.Consumer;
import java.util.function.BiFunction;
#endif
@@ -15,7 +14,6 @@ import speiger.src.collections.PACKAGE.collections.BI_ITERATOR;
import speiger.src.collections.PACKAGE.collections.COLLECTION;
import speiger.src.collections.PACKAGE.collections.ITERATOR;
#if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.functions.COMPARATOR;
import speiger.src.collections.PACKAGE.functions.CONSUMER;
#endif
import speiger.src.collections.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER;
@@ -34,7 +32,7 @@ import speiger.src.collections.utils.SanityChecks;
* 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
public class IMMUTABLE_HASH_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE implements ORDERED_SET KEY_GENERIC_TYPE
{
/** The Backing keys array */
protected transient KEY_TYPE[] keys;
@@ -241,6 +239,10 @@ public class IMMUTABLE_HASH_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERI
@Override
public boolean add(KEY_TYPE o) { throw new UnsupportedOperationException(); }
#if TYPE_OBJECT
@Override
public KEY_TYPE addOrGet(KEY_TYPE o) { throw new UnsupportedOperationException(); }
#endif
@Override
@Primitive
public boolean addAll(Collection<? extends CLASS_TYPE> c) { throw new UnsupportedOperationException(); }
@@ -257,7 +259,12 @@ public class IMMUTABLE_HASH_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERI
@Override
public boolean contains(Object o) {
#if TYPE_OBJECT
if(o == null) return containsNull;
#else
if(o == null) return false;
if(o instanceof CLASS_TYPE && KEY_EQUALS(CLASS_TO_KEY(o), EMPTY_KEY_VALUE)) return containsNull;
#endif
int pos = HashUtil.mix(o.hashCode()) & mask;
KEY_TYPE current = keys[pos];
if(KEY_EQUALS_NULL(current)) return false;
@@ -450,18 +457,6 @@ public class IMMUTABLE_HASH_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERI
return set;
}
@Override
public COMPARATOR KEY_GENERIC_TYPE comparator() { return null; }
@Override
public SORTED_SET KEY_GENERIC_TYPE subSet(KEY_TYPE fromElement, KEY_TYPE toElement) { throw new UnsupportedOperationException(); }
@Override
public SORTED_SET KEY_GENERIC_TYPE headSet(KEY_TYPE toElement) { throw new UnsupportedOperationException(); }
@Override
public SORTED_SET KEY_GENERIC_TYPE tailSet(KEY_TYPE fromElement) { throw new UnsupportedOperationException(); }
@Override
public void clear() { throw new UnsupportedOperationException(); }
@@ -1,7 +1,6 @@
package speiger.src.collections.PACKAGE.sets;
#if TYPE_OBJECT
import java.util.Comparator;
import java.util.function.Consumer;
import java.util.function.BiFunction;
#endif
@@ -16,9 +15,6 @@ import speiger.src.collections.PACKAGE.collections.COLLECTION;
import speiger.src.collections.PACKAGE.collections.ITERATOR;
#endif
import speiger.src.collections.PACKAGE.collections.BI_ITERATOR;
#if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.functions.COMPARATOR;
#endif
import speiger.src.collections.PACKAGE.lists.LIST_ITERATOR;
#if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.utils.ITERATORS;
@@ -37,7 +33,7 @@ import speiger.src.collections.utils.SanityChecks;
* This implementation of SortedSet does not support SubSet of any kind. It implements the interface due to sortability and first/last access
* @Type(T)
*/
public class LINKED_CUSTOM_HASH_SET KEY_GENERIC_TYPE extends CUSTOM_HASH_SET KEY_GENERIC_TYPE implements SORTED_SET KEY_GENERIC_TYPE
public class LINKED_CUSTOM_HASH_SET KEY_GENERIC_TYPE extends CUSTOM_HASH_SET KEY_GENERIC_TYPE implements ORDERED_SET KEY_GENERIC_TYPE
{
/** The Backing array for links between nodes. Left 32 Bits => Previous Entry, Right 32 Bits => Next Entry */
protected transient long[] links;
@@ -241,6 +237,7 @@ public class LINKED_CUSTOM_HASH_SET KEY_GENERIC_TYPE extends CUSTOM_HASH_SET KEY
}
containsNull = true;
onNodeAdded(nullIndex);
moveToFirstIndex(nullIndex);
}
else {
int pos = HashUtil.mix(strategy.hashCode(o)) & mask;
@@ -253,6 +250,7 @@ public class LINKED_CUSTOM_HASH_SET KEY_GENERIC_TYPE extends CUSTOM_HASH_SET KEY
}
keys[pos] = o;
onNodeAdded(pos);
moveToFirstIndex(pos);
}
if(size++ >= maxFill) rehash(HashUtil.arraySize(size+1, loadFactor));
return true;
@@ -672,18 +670,6 @@ public class LINKED_CUSTOM_HASH_SET KEY_GENERIC_TYPE extends CUSTOM_HASH_SET KEY
return set;
}
@Override
public COMPARATOR KEY_GENERIC_TYPE comparator() { return null; }
@Override
public SORTED_SET KEY_GENERIC_TYPE subSet(KEY_TYPE fromElement, KEY_TYPE toElement) { throw new UnsupportedOperationException(); }
@Override
public SORTED_SET KEY_GENERIC_TYPE headSet(KEY_TYPE toElement) { throw new UnsupportedOperationException(); }
@Override
public SORTED_SET KEY_GENERIC_TYPE tailSet(KEY_TYPE fromElement) { throw new UnsupportedOperationException(); }
private class SetIterator implements LIST_ITERATOR KEY_GENERIC_TYPE {
int previous = -1;
int next = -1;
@@ -1,8 +1,5 @@
package speiger.src.collections.PACKAGE.sets;
#if TYPE_OBJECT
import java.util.Comparator;
#endif
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
@@ -19,7 +16,6 @@ import speiger.src.collections.PACKAGE.collections.ITERATOR;
#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.objects.functions.consumer.BI_FROM_OBJECT_CONSUMER;
@@ -38,7 +34,7 @@ import speiger.src.collections.utils.SanityChecks;
* This implementation of SortedSet does not support SubSet of any kind. It implements the interface due to sortability and first/last access
* @Type(T)
*/
public class LINKED_HASH_SET KEY_GENERIC_TYPE extends HASH_SET KEY_GENERIC_TYPE implements SORTED_SET KEY_GENERIC_TYPE
public class LINKED_HASH_SET KEY_GENERIC_TYPE extends HASH_SET KEY_GENERIC_TYPE implements ORDERED_SET KEY_GENERIC_TYPE
{
/** The Backing array for links between nodes. Left 32 Bits => Previous Entry, Right 32 Bits => Next Entry */
protected transient long[] links;
@@ -212,6 +208,7 @@ public class LINKED_HASH_SET KEY_GENERIC_TYPE extends HASH_SET KEY_GENERIC_TYPE
}
containsNull = true;
onNodeAdded(nullIndex);
moveToFirstIndex(nullIndex);
}
else {
int pos = HashUtil.mix(KEY_TO_HASH(o)) & mask;
@@ -224,6 +221,7 @@ public class LINKED_HASH_SET KEY_GENERIC_TYPE extends HASH_SET KEY_GENERIC_TYPE
}
keys[pos] = o;
onNodeAdded(pos);
moveToFirstIndex(pos);
}
if(size++ >= maxFill) rehash(HashUtil.arraySize(size+1, loadFactor));
return true;
@@ -643,18 +641,6 @@ public class LINKED_HASH_SET KEY_GENERIC_TYPE extends HASH_SET KEY_GENERIC_TYPE
return set;
}
@Override
public COMPARATOR KEY_GENERIC_TYPE comparator() { return null; }
@Override
public SORTED_SET KEY_GENERIC_TYPE subSet(KEY_TYPE fromElement, KEY_TYPE toElement) { throw new UnsupportedOperationException(); }
@Override
public SORTED_SET KEY_GENERIC_TYPE headSet(KEY_TYPE toElement) { throw new UnsupportedOperationException(); }
@Override
public SORTED_SET KEY_GENERIC_TYPE tailSet(KEY_TYPE fromElement) { throw new UnsupportedOperationException(); }
private class SetIterator implements LIST_ITERATOR KEY_GENERIC_TYPE {
int previous = -1;
int next = -1;
@@ -171,10 +171,10 @@ public interface NAVIGABLE_SET KEY_GENERIC_TYPE extends NavigableSet<CLASS_TYPE>
default CLASS_TYPE last() { return SORTED_SET.super.last(); }
@Override
@Deprecated
public default CLASS_TYPE pollFirst() { return KEY_TO_OBJ(POLL_FIRST_KEY()); }
public default CLASS_TYPE pollFirst() { return isEmpty() ? null : KEY_TO_OBJ(POLL_FIRST_KEY()); }
@Override
@Deprecated
public default CLASS_TYPE pollLast() { return KEY_TO_OBJ(POLL_LAST_KEY()); }
public default CLASS_TYPE pollLast() { return isEmpty() ? null : KEY_TO_OBJ(POLL_LAST_KEY()); }
@Override
@Deprecated
@@ -277,6 +277,30 @@ public class CUSTOM_HASH_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_T
return true;
}
#if TYPE_OBJECT
@Override
public KEY_TYPE addOrGet(KEY_TYPE o) {
if(strategy.equals(o, EMPTY_KEY_VALUE)) {
if(containsNull) return EMPTY_KEY_VALUE;
containsNull = true;
onNodeAdded(nullIndex);
}
else {
int pos = HashUtil.mix(strategy.hashCode(o)) & mask;
KEY_TYPE current = keys[pos];
if(!strategy.equals(current, EMPTY_KEY_VALUE)) {
if(strategy.equals(current, o)) return current;
while(!strategy.equals((current = keys[pos = (++pos & mask)]), EMPTY_KEY_VALUE))
if(strategy.equals(current, o)) return current;
}
keys[pos] = o;
onNodeAdded(pos);
}
if(size++ >= maxFill) rehash(HashUtil.arraySize(size+1, loadFactor));
return o;
}
#endif
@Override
@Primitive
public boolean addAll(Collection<? extends CLASS_TYPE> c) {
@@ -235,6 +235,30 @@ public class HASH_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE imp
return true;
}
#if TYPE_OBJECT
@Override
public KEY_TYPE addOrGet(KEY_TYPE o) {
if(KEY_EQUALS_NULL(o)) {
if(containsNull) return null;
containsNull = true;
onNodeAdded(nullIndex);
}
else {
int pos = HashUtil.mix(KEY_TO_HASH(o)) & mask;
KEY_TYPE current = keys[pos];
if(KEY_EQUALS_NOT_NULL(current)) {
if(KEY_EQUALS(current, o)) return current;
while(KEY_EQUALS_NOT_NULL((current = keys[pos = (++pos & mask)])))
if(KEY_EQUALS(current, o)) return current;
}
keys[pos] = o;
onNodeAdded(pos);
}
if(size++ >= maxFill) rehash(HashUtil.arraySize(size+1, loadFactor));
return o;
}
#endif
@Override
@Primitive
public boolean addAll(Collection<? extends CLASS_TYPE> c) {
@@ -252,7 +276,12 @@ public class HASH_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE imp
@Override
public boolean contains(Object o) {
#if TYPE_OBJECT
if(o == null) return containsNull;
#else
if(o == null) return false;
if(o instanceof CLASS_TYPE && KEY_EQUALS(CLASS_TO_KEY(o), EMPTY_KEY_VALUE)) return containsNull;
#endif
int pos = HashUtil.mix(o.hashCode()) & mask;
KEY_TYPE current = keys[pos];
if(KEY_EQUALS_NULL(current)) return false;
@@ -265,7 +294,12 @@ public class HASH_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE imp
@Override
public boolean remove(Object o) {
#if TYPE_OBJECT
if(o == null) return (containsNull ? removeNullIndex() : false);
#else
if(o == null) return false;
if(o instanceof CLASS_TYPE && KEY_EQUALS(CLASS_TO_KEY(o), EMPTY_KEY_VALUE)) return (containsNull ? removeNullIndex() : false);
#endif
int pos = HashUtil.mix(o.hashCode()) & mask;
KEY_TYPE current = keys[pos];
if(KEY_EQUALS_NULL(current)) return false;
@@ -0,0 +1,114 @@
package speiger.src.collections.PACKAGE.sets;
import speiger.src.collections.PACKAGE.collections.BI_ITERATOR;
import speiger.src.collections.PACKAGE.collections.SPLIT_ITERATOR;
import speiger.src.collections.PACKAGE.utils.SETS;
import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS;
/**
* A Special Set Interface giving Access to some really usefull functions
* The Idea behind this interface is to allow access to functions that give control to the Order of elements.
* Since Linked implementations as examples can be reordered outside of the Insertion Order.
* This interface provides basic access to such functions while also providing some Sorted/NaivgableSet implementations that still fit into here.
*
* @Type(T)
*/
public interface ORDERED_SET KEY_GENERIC_TYPE extends SET KEY_GENERIC_TYPE
{
/**
* A customized add method that allows you to insert into the first index.
* @param o the element that should be inserted
* @return true if it was added
* @see java.util.Set#add(Object)
*/
public boolean addAndMoveToFirst(KEY_TYPE o);
/**
* A customized add method that allows you to insert into the last index.
* @param o the element that should be inserted
* @return true if it was added
* @see java.util.Set#add(Object)
*/
public boolean addAndMoveToLast(KEY_TYPE o);
/**
* A specific move method to move a given key to the first index.
* @param o that should be moved to the first index
* @return true if the value was moved.
* @note returns false if the value was not present in the first place
*/
public boolean moveToFirst(KEY_TYPE o);
/**
* A specific move method to move a given key to the last index.
* @param o that should be moved to the first last
* @return true if the value was moved.
* @note returns false if the value was not present in the first place
*/
public boolean moveToLast(KEY_TYPE o);
@Override
public ORDERED_SET KEY_GENERIC_TYPE copy();
@Override
public BI_ITERATOR KEY_GENERIC_TYPE iterator();
/**
* A type Specific Iterator starting from a given key
* @param fromElement the element the iterator should start from
* @return a iterator starting from the given element
* @throws java.util.NoSuchElementException if fromElement isn't found
*/
public BI_ITERATOR KEY_GENERIC_TYPE iterator(KEY_TYPE fromElement);
/**
* A Type Specific Type Splititerator to reduce boxing/unboxing
* @return type specific splititerator
*/
@Override
default SPLIT_ITERATOR KEY_GENERIC_TYPE spliterator() { return SPLIT_ITERATORS.createSplititerator(this, 0); }
/**
* A method to get the first element in the set
* @return first element in the set
*/
public KEY_TYPE FIRST_KEY();
/**
* A method to get and remove the first element in the set
* @return first element in the set
*/
public KEY_TYPE POLL_FIRST_KEY();
/**
* A method to get the last element in the set
* @return last element in the set
*/
public KEY_TYPE LAST_KEY();
/**
* A method to get and remove the last element in the set
* @return last element in the set
*/
public KEY_TYPE POLL_LAST_KEY();
#if !TYPE_BOOLEAN
/**
* Creates a Wrapped OrderedSet that is Synchronized
* @return a new OrderedSet that is synchronized
* @see SETS#synchronize
*/
public default ORDERED_SET KEY_GENERIC_TYPE synchronize() { return SETS.synchronize(this); }
/**
* Creates a Wrapped OrderedSet that is Synchronized
* @param mutex is the controller of the synchronization block
* @return a new OrderedSet Wrapper that is synchronized
* @see SETS#synchronize
*/
public default ORDERED_SET KEY_GENERIC_TYPE synchronize(Object mutex) { return SETS.synchronize(this, mutex); }
/**
* Creates a Wrapped OrderedSet that is unmodifiable
* @return a new OrderedSet Wrapper that is unmodifiable
* @see SETS#unmodifiable
*/
public default ORDERED_SET KEY_GENERIC_TYPE unmodifiable() { return SETS.unmodifiable(this); }
#endif
}
File diff suppressed because it is too large Load Diff
@@ -54,6 +54,15 @@ public interface SET KEY_GENERIC_TYPE extends Set<CLASS_TYPE>, COLLECTION KEY_GE
return COLLECTION.super.remove(o);
}
#else
/**
* A Helper method that allows to add a element or getting the already present implement.
* Allowing to make unique references reuseable.
* @param o the element to add
* @return either the inserted element or the present element.
*/
public KEY_TYPE addOrGet(KEY_TYPE o);
#endif
#if !TYPE_BOOLEAN
/**
@@ -16,44 +16,11 @@ import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS;
* A Type Specific SortedSet implementation to reduce boxing/unboxing
* with a couple extra methods that allow greater control over sets.
* @Type(T)
* @note ORDERED_SET is only extended until 0.6.0 for Compat reasons.
* The supported classes already implement ORDERED_SET directly and will remove SORTED_SET implementations in favor of ORDERED_SET instead
*/
public interface SORTED_SET KEY_GENERIC_TYPE extends SET KEY_GENERIC_TYPE, SortedSet<CLASS_TYPE>
{
/**
* A customized add method that allows you to insert into the first index.
* @param o the element that should be inserted
* @return true if it was added
* @see java.util.Set#add(Object)
* @note some implementations do not support this method
*/
public boolean addAndMoveToFirst(KEY_TYPE o);
/**
* A customized add method that allows you to insert into the last index.
* @param o the element that should be inserted
* @return true if it was added
* @see java.util.Set#add(Object)
* @note some implementations do not support this method
*/
public boolean addAndMoveToLast(KEY_TYPE o);
/**
* A specific move method to move a given key to the first index.
* @param o that should be moved to the first index
* @return true if the value was moved.
* @note returns false if the value was not present in the first place
* @note some implementations do not support this method
*/
public boolean moveToFirst(KEY_TYPE o);
/**
* A specific move method to move a given key to the last index.
* @param o that should be moved to the first last
* @return true if the value was moved.
* @note returns false if the value was not present in the first place
* @note some implementations do not support this method
*/
public boolean moveToLast(KEY_TYPE o);
/**
* A Type Specific Comparator method
* @return the type specific comparator
@@ -348,9 +348,11 @@ public class ARRAYS
* @param array the array that needs to be sorted
* @ArrayType(T)
* @param comp the Comparator that decides the sorting order
* @return input array.
*/
public static GENERIC_KEY_BRACES void stableSort(KEY_TYPE[] array, COMPARATOR KEY_GENERIC_TYPE comp) {
public static GENERIC_KEY_BRACES KEY_TYPE[] stableSort(KEY_TYPE[] array, COMPARATOR KEY_GENERIC_TYPE comp) {
stableSort(array, 0, array.length, comp);
return array;
}
/**
@@ -386,9 +388,11 @@ public class ARRAYS
* Stable sort referres to Mergesort or Insertionsort
* @param array the array that needs to be sorted
* @ArrayType(T)
* @return input array
*/
public static GENERIC_KEY_BRACES void stableSort(KEY_TYPE[] array) {
public static GENERIC_KEY_BRACES KEY_TYPE[] stableSort(KEY_TYPE[] array) {
stableSort(array, 0, array.length);
return array;
}
/**
@@ -423,9 +427,11 @@ public class ARRAYS
* @param array the array that needs to be sorted
* @param comp the Comparator that decides the sorting order
* @ArrayType(T)
* @return input array
*/
public static GENERIC_KEY_BRACES void unstableSort(KEY_TYPE[] array, COMPARATOR KEY_GENERIC_TYPE comp) {
public static GENERIC_KEY_BRACES KEY_TYPE[] unstableSort(KEY_TYPE[] array, COMPARATOR KEY_GENERIC_TYPE comp) {
unstableSort(array, 0, array.length, comp);
return array;
}
/**
@@ -461,9 +467,11 @@ public class ARRAYS
* Unstable sort referres to QuickSort or SelectionSort
* @param array the array that needs to be sorted
* @ArrayType(T)
* @return input array
*/
public static GENERIC_KEY_BRACES void unstableSort(KEY_TYPE[] array) {
public static GENERIC_KEY_BRACES KEY_TYPE[] unstableSort(KEY_TYPE[] array) {
unstableSort(array, 0, array.length);
return array;
}
/**
@@ -496,9 +504,11 @@ public class ARRAYS
* @param array the array that needs to be sorted
* @param comp the Comparator that decides the sorting order
* @ArrayType(T)
* @return input array
*/
public static GENERIC_KEY_BRACES void insertionSort(KEY_TYPE[] array, COMPARATOR KEY_GENERIC_TYPE comp) {
public static GENERIC_KEY_BRACES KEY_TYPE[] insertionSort(KEY_TYPE[] array, COMPARATOR KEY_GENERIC_TYPE comp) {
insertionSort(array, 0, array.length, comp);
return array;
}
/**
@@ -535,9 +545,11 @@ public class ARRAYS
* Sorts an array according to the natural ascending order using InsertionSort,
* @param array the array that needs to be sorted
* @ArrayType(T)
* @return input array
*/
public static GENERIC_KEY_BRACES void insertionSort(KEY_TYPE[] array) {
public static GENERIC_KEY_BRACES KEY_TYPE[] insertionSort(KEY_TYPE[] array) {
insertionSort(array, 0, array.length);
return array;
}
/**
@@ -573,9 +585,11 @@ public class ARRAYS
* @param array the array that needs to be sorted
* @param comp the Comparator that decides the sorting order
* @ArrayType(T)
* @return input array
*/
public static GENERIC_KEY_BRACES void selectionSort(KEY_TYPE[] array, COMPARATOR KEY_GENERIC_TYPE comp) {
public static GENERIC_KEY_BRACES KEY_TYPE[] selectionSort(KEY_TYPE[] array, COMPARATOR KEY_GENERIC_TYPE comp) {
selectionSort(array, 0, array.length, comp);
return array;
}
/**
@@ -617,9 +631,11 @@ public class ARRAYS
* Sorts an array according to the natural ascending order using Selection Sort,
* @param array the array that needs to be sorted
* @ArrayType(T)
* @return input array
*/
public static GENERIC_KEY_BRACES void selectionSort(KEY_TYPE[] array) {
public static GENERIC_KEY_BRACES KEY_TYPE[] selectionSort(KEY_TYPE[] array) {
selectionSort(array, 0, array.length);
return array;
}
/**
@@ -661,9 +677,11 @@ public class ARRAYS
* @param array the array that needs to be sorted
* @param comp the Comparator that decides the sorting order
* @ArrayType(T)
* @return input array
*/
public static GENERIC_KEY_BRACES void mergeSort(KEY_TYPE[] array, COMPARATOR KEY_GENERIC_TYPE comp) {
public static GENERIC_KEY_BRACES KEY_TYPE[] mergeSort(KEY_TYPE[] array, COMPARATOR KEY_GENERIC_TYPE comp) {
mergeSort(array, null, 0, array.length, comp);
return array;
}
/**
@@ -713,9 +731,11 @@ public class ARRAYS
* This implementation was copied from <a href="https://github.com/vigna/fastutil">FastUtil</a> with a couple custom optimizations
* @param array the array that needs to be sorted
* @ArrayType(T)
* @return input array
*/
public static GENERIC_KEY_BRACES void mergeSort(KEY_TYPE[] array) {
public static GENERIC_KEY_BRACES KEY_TYPE[] mergeSort(KEY_TYPE[] array) {
mergeSort(array, null, 0, array.length);
return array;
}
/**
@@ -922,9 +942,11 @@ public class ARRAYS
* @author Speiger
* @param array the array that needs to be sorted
* @ArrayType(T)
* @return input array
*/
public static GENERIC_KEY_BRACES void memFreeMergeSort(KEY_TYPE[] array) {
public static GENERIC_KEY_BRACES KEY_TYPE[] memFreeMergeSort(KEY_TYPE[] array) {
memFreeMergeSort(array, 0, array.length);
return array;
}
/**
@@ -1099,9 +1121,11 @@ public class ARRAYS
* @param array the array that needs to be sorted
* @param comp the Comparator that decides the sorting order
* @ArrayType(T)
* @return input array
*/
public static GENERIC_KEY_BRACES void quickSort(KEY_TYPE[] array, COMPARATOR KEY_GENERIC_TYPE comp) {
public static GENERIC_KEY_BRACES KEY_TYPE[] quickSort(KEY_TYPE[] array, COMPARATOR KEY_GENERIC_TYPE comp) {
quickSort(array, 0, array.length, comp);
return array;
}
/**
@@ -1157,9 +1181,11 @@ public class ARRAYS
* and that sorting Algorithm is based on the tuned quicksort adapted from Jon L. Bentley and M. DouglasMcIlroy, "Engineering a Sort Function", Software: Practice and Experience, 23(11), pages12491265, 1993.
* @param array the array that needs to be sorted
* @ArrayType(T)
* @return input array
*/
public static GENERIC_KEY_BRACES void quickSort(KEY_TYPE[] array) {
public static GENERIC_KEY_BRACES KEY_TYPE[] quickSort(KEY_TYPE[] array) {
quickSort(array, 0, array.length);
return array;
}
/**
@@ -0,0 +1,913 @@
package speiger.src.collections.PACKAGE.utils;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.locks.LockSupport;
import java.util.function.Consumer;
#if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.functions.CONSUMER;
import speiger.src.collections.PACKAGE.functions.COMPARATOR;
#else
import java.util.function.BiFunction;
import java.util.Comparator;
#endif
import speiger.src.collections.PACKAGE.collections.ITERABLE;
import speiger.src.collections.PACKAGE.collections.COLLECTION;
import speiger.src.collections.PACKAGE.collections.ITERATOR;
import speiger.src.collections.PACKAGE.functions.TASK;
import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
import speiger.src.collections.PACKAGE.functions.function.TO_OBJECT_FUNCTION;
import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR;
import speiger.src.collections.PACKAGE.lists.ARRAY_LIST;
import speiger.src.collections.PACKAGE.lists.LIST;
#if !TYPE_BOOLEAN
import speiger.src.collections.PACKAGE.sets.SET;
import speiger.src.collections.PACKAGE.sets.LINKED_HASH_SET;
#endif
#if !TYPE_BOOLEAN
import speiger.src.collections.booleans.utils.BooleanAsyncBuilder;
import speiger.src.collections.booleans.utils.BooleanAsyncBuilder.BaseBooleanTask;
#endif
#if !TYPE_OBJECT
import speiger.src.collections.objects.utils.ObjectAsyncBuilder;
import speiger.src.collections.objects.utils.ObjectAsyncBuilder.BaseObjectTask;
#endif
#if !TYPE_INT
import speiger.src.collections.ints.utils.IntAsyncBuilder;
import speiger.src.collections.ints.utils.IntAsyncBuilder.BaseIntTask;
#endif
import speiger.src.collections.utils.SanityChecks;
/**
*
*
* The Async API allows you to process collections on a different thread without having to deal with the Multithreading complexity. <br>
* It uses the Lightweight Stream Replace API to do its work, which can make it faster then sequential streams. <br>
* This feature isn't designed to do Multithreading work, but to allow moving work off the main thread into a worker thread. <br>
* So anything executed on this is still Singlethreaded. <br>
* <br>
* How it works is you create the AsyncBuilder using a Iterable of the Type. <br>
* Then select things you want to use on the Iterable. <br>
* - For example: map/filter/peek/limit/etc <br>
* <br>
* After that you select your action the Iterable should be applied on. <br>
* - For Example: forEach/findFirst/matchAny/etc <br>
* <br>
* Then optionally a custom Executor or callback can be applied <br>
* At the end either execute or join can be called to start the task. <br>
* - execute will return the Task reference so that the task can be traced back. <br>
* - join will await the completion of the task and return the return value <br>
* <br>
* During Construction a couple Disposable Builder Objects will be created. <br>
* These will be only used during construction. <br>
* <br>
* The Task Object is also pause-able/Interruptable at any moment during the Processing. <br>
*
* A small example
* <pre><code>
* public void processFiles(ObjectCollection&#60;String&#62; potentialFiles) {
* potentialFiles.asAsync()
* .map(Paths::get).filter(Files::exists) //Modifies the collection (Optional)
* .forEach(Files::delete) //Creates the action (Required)
* .onCompletion(T -&#62; {}} //Callback on completion (Optional)
* .execute() //Starts the task. (Required)
* }
* </code></pre>
* @author Speiger
*
* @Type(T)
*/
public class ASYNC_BUILDER KEY_GENERIC_TYPE
{
ITERABLE KEY_GENERIC_TYPE iterable;
BASE_TASK KEY_GENERIC_TYPE task;
/**
* Main Constructor that uses a Iterable to build a Offthread Task.
* @param iterable that should be processed
*/
public ASYNC_BUILDER(ITERABLE KEY_GENERIC_TYPE iterable) {
this.iterable = iterable;
}
/**
* Helper constructor.
* @param task that had been build
*/
public ASYNC_BUILDER(BASE_TASK KEY_GENERIC_TYPE task) {
this.task = task;
}
/**
* Helper function that automatically wraps a Iterable into a AsyncBuilder since it forces this collections Iterable.
* @param iterable that should be wrapped
* @Type(T)
* @return a AsyncBuilder with the iterable wrapped
*/
public static GENERIC_KEY_BRACES ASYNC_BUILDER KEY_GENERIC_TYPE of(Iterable<CLASS_TYPE> iterable) {
return new ASYNC_BUILDERBRACES(ITERABLES.wrap(iterable));
}
/**
* Helper function that automatically wraps a array into a AsyncBuilder since it forces this collections Iterable.
* @param values that should be wrapped
* @Type(T)
* @return a AsyncBuilder with the values wrapped
*/
public static GENERIC_KEY_BRACES ASYNC_BUILDER KEY_GENERIC_TYPE of(KEY_TYPE...values) {
return new ASYNC_BUILDERBRACES(ARRAY_LIST.wrap(values));
}
/**
* Maps the elements to something else
* @param mapper the mapping function
* @param <E> The return type.
* @return a new Builder Object with the mapped Iterable
*/
public <E> ObjectAsyncBuilder<E> map(TO_OBJECT_FUNCTION KKS_GENERIC_TYPE<E> mapper) {
return new ObjectAsyncBuilder<>(ITERABLES.map(iterable, mapper));
}
/**
* Maps the elements to something else
* @param mapper the flatMapping function
* @param <V> The return type supplier.
* @param <E> The return type.
* @return a new Builder Object with the mapped Iterable
*/
public <E, V extends Iterable<E>> ObjectAsyncBuilder<E> flatMap(TO_OBJECT_FUNCTION KKS_GENERIC_TYPE<V> mapper) {
return new ObjectAsyncBuilder<>(ITERABLES.flatMap(iterable, mapper));
}
/**
* Maps the elements to something else
* @param mapper the flatMapping function
* @param <E> The return type.
* @return a new Builder Object with the mapped Iterable
*/
public <E> ObjectAsyncBuilder<E> arrayflatMap(TO_OBJECT_FUNCTION KKS_GENERIC_TYPE<E[]> mapper) {
return new ObjectAsyncBuilder<>(ITERABLES.arrayFlatMap(iterable, mapper));
}
/**
* Filters out the unwanted elements out of the Iterable
* @param filter the elements that should be kept
* @return Self with a filter applied
*/
public ASYNC_BUILDER KEY_GENERIC_TYPE filter(PREDICATE KEY_GENERIC_TYPE filter) {
iterable = ITERABLES.filter(iterable, filter);
return this;
}
/**
* Removes duplicated elements out of the Iterable
* @return Self with a deduplicator applied
*/
public ASYNC_BUILDER KEY_GENERIC_TYPE distinct() {
iterable = ITERABLES.distinct(iterable);
return this;
}
/**
* Limits how many elements are inside of the Iterable
* @param limit how many elements should max be iterated through
* @return self with a limiter applied
*/
public ASYNC_BUILDER KEY_GENERIC_TYPE limit(long limit) {
iterable = ITERABLES.limit(iterable, limit);
return this;
}
/**
* Sorts the elements inside of the Iterable.
* This operation is heavily hurting performance because it rebuilds the entire iterator and then sorts it, and this will affect the pausing feature.
* @param sorter that sorts the elements.
* @return self with a sorter applied
*/
public ASYNC_BUILDER KEY_GENERIC_TYPE sorted(COMPARATOR KEY_GENERIC_TYPE sorter) {
iterable = ITERABLES.sorted(iterable, sorter);
return this;
}
/**
* Allows to preview elements before they are processed
* @param action the action that should be applied
* @return self with a preview applied
*/
public ASYNC_BUILDER KEY_GENERIC_TYPE peek(CONSUMER KEY_GENERIC_TYPE action) {
iterable = ITERABLES.peek(iterable, action);
return this;
}
/**
* Iterates over the Iterable with a desired action
* @param action that should be applied
* @return a new Builder with the forEach action applied.
*/
public ObjectAsyncBuilder<Void> forEach(CONSUMER KEY_GENERIC_TYPE action) {
return new ObjectAsyncBuilder<>(new ForEachTask<>(iterable.iterator(), action));
}
/**
* Reduces the elements inside of the Iterable down to one element
* @param operator that reduces the elements.
* @return self with the reduce action applied
*/
public ASYNC_BUILDER KEY_GENERIC_TYPE reduce(UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
task = new SimpleReduceTaskBRACES(iterable.iterator(), operator);
return this;
}
#if TYPE_OBJECT
/**
* Reduces the elements inside of the Iterable down to one element using a identity element.
* @param <E> the return type
* @param identity the element the reduce function should start with
* @param operator that reduces the elements.
* @return a new Builder with the reduce function applied
*/
public <KEY_SPECIAL_TYPE> ASYNC_BUILDER<KEY_SPECIAL_TYPE> reduce(KEY_SPECIAL_TYPE identity, BiFunction<KEY_SPECIAL_TYPE, KEY_TYPE, KEY_SPECIAL_TYPE> operator) {
return new ASYNC_BUILDERBRACES(new ReduceTaskBRACES(iterable.iterator(), operator, identity));
}
#else
/**
* Reduces the elements inside of the Iterable down to one element using a identity element.
* @param identity the element the reduce function should start with
* @param operator that reduces the elements.
* @return a new Builder with the reduce function applied
*/
public ASYNC_BUILDER reduce(KEY_TYPE identity, UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
return new ASYNC_BUILDERBRACES(new ReduceTaskBRACES(iterable.iterator(), operator, identity));
}
#endif
/**
* Pours all elements into a List that can be later
* @return a new Builder with the pour function applied
*/
public ObjectAsyncBuilder<LIST KEY_GENERIC_TYPE> pourAsList() {
return pour(new ARRAY_LISTBRACES());
}
#if !TYPE_BOOLEAN
/**
* Pours all elements into a Set that can be later
* @return a new Builder with the pour function applied
*/
public ObjectAsyncBuilder<SET KEY_GENERIC_TYPE> pourAsSet() {
return pour(new LINKED_HASH_SETBRACES());
}
#endif
/**
* Pours all elements into a collection that can be later
* @param <E> the return type
* @param collection the collection the elements
* @return a new Builder with the pour function applied
*/
public <E extends COLLECTION KEY_GENERIC_TYPE> ObjectAsyncBuilder<E> pour(E collection) {
return new ObjectAsyncBuilder<>(new CollectTask<>(iterable.iterator(), collection));
}
/**
* Searches through the elements of the Iterable to find if the desired element is present.
* @param filter that decides the desired elements
* @return a new Builder with the matchAny function applied
*/
public BooleanAsyncBuilder matchAny(PREDICATE KEY_GENERIC_TYPE filter) {
return new BooleanAsyncBuilder(new MatchTaskBRACES(iterable.iterator(), filter, 0));
}
/**
* Searches through the elements of the Iterable to find if unwanted elements are present.
* @param filter that decides the unwanted elements
* @return a new Builder with the matchNone function applied
*/
public BooleanAsyncBuilder matchNone(PREDICATE KEY_GENERIC_TYPE filter) {
return new BooleanAsyncBuilder(new MatchTaskBRACES(iterable.iterator(), filter, 1));
}
/**
* Searches through the elements of the Iterable to find if all the desired elements are present.
* @param filter that decides the desired elements
* @return a new Builder with the matchAll function applied
*/
public BooleanAsyncBuilder matchAll(PREDICATE KEY_GENERIC_TYPE filter) {
return new BooleanAsyncBuilder(new MatchTaskBRACES(iterable.iterator(), filter, 2));
}
/**
* Searches through the elements of the Iterable to find if the desired element.
* If not present it will return the default value of the type
* @param filter that decides the desired elements
* @return self with the findFirst function applied
*/
public ASYNC_BUILDER KEY_GENERIC_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) {
task = new FindFirstTaskBRACES(iterable.iterator(), filter);
return this;
}
/**
* Counts all desired elements inside the Iterable
* @param filter that decides the desired elements
* @return a new Builder with the count function applied
*/
public IntAsyncBuilder count(PREDICATE KEY_GENERIC_TYPE filter) {
return new IntAsyncBuilder(new CountTaskBRACES(iterable.iterator(), filter));
}
/**
* Optional way to add a custom executor that runs this offthread task.
* Can only be set after the action was decided on.
* @param executor that executes the task, defaults to {@link SanityChecks#invokeAsyncTask(Runnable) }
* @return self with the executor set
* @note has to be NonNull
*/
public ASYNC_BUILDER KEY_GENERIC_TYPE executor(Executor executor) {
if(task == null) throw new IllegalStateException("Action is missing");
task.withExecutor(executor);
return this;
}
/**
* Optional way to set a callback that allows to compute actions after the task was completed.
* The state of the task has to be validated by the callback.
* @param callback that should be notified after completion of the task
* @return self with the callback set
* @note can be null
*/
public ASYNC_BUILDER KEY_GENERIC_TYPE onCompletion(Consumer<TASK KEY_GENERIC_TYPE> callback) {
if(task == null) throw new IllegalStateException("Action is missing");
task.withCallback(callback);
return this;
}
/**
* Starts the Execution of the task without awaiting its result
* @return the task object that allow to trace it.
*/
public TASK KEY_GENERIC_TYPE execute() {
BASE_TASK KEY_GENERIC_TYPE toRun = task;
toRun.begin();
task = null;
return toRun;
}
/**
* Starts the Execution of the task and will await its completion, returning the result.
* @return the result of the task provided.
* @throws ExecutionException if the task threw a exception
* @throws InterruptedException if the caller thread was interrupted
*/
public KEY_TYPE join() throws ExecutionException, InterruptedException {
BASE_TASK KEY_GENERIC_TYPE toRun = task;
task = null;
toRun.begin();
return toRun.GET_KEY();
}
/**
* Starts the Execution of the task and will await its completion with a timeout, returning the result.
* @param timeout of how long the thread should wait the task to be completed
* @param unit of the desired waiting time.
* @return the result of the provided task
* @throws InterruptedException if the caller thread was interrupted
* @throws ExecutionException if the task threw a exception
* @throws TimeoutException if the timeout was reached before the task was finished
*/
public KEY_TYPE join(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
BASE_TASK KEY_GENERIC_TYPE toRun = task;
task = null;
toRun.begin();
return toRun.GET_KEY(timeout, unit);
}
#if !TYPE_OBJECT
private static class ReduceTask extends BASE_TASK
{
ITERATOR KEY_GENERIC_TYPE iter;
UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator;
KEY_TYPE value;
public ReduceTask(ITERATOR KEY_GENERIC_TYPE iter, UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator, KEY_TYPE value) {
this.iter = iter;
this.operator = operator;
this.value = value;
}
@Override
protected boolean execute() throws Exception {
while(shouldRun() && iter.hasNext()) {
value = operator.apply(value, iter.NEXT());
}
if(!iter.hasNext()) {
setResult(value);
return true;
}
return false;
}
@Override
protected void onCompletion() {
super.onCompletion();
iter = null;
operator = null;
#if TYPE_OBJECT
value = null;
#endif
}
}
#else
private static class ReduceTask<T, E> extends BaseObjectTask<E>
{
ObjectIterator<T> iter;
BiFunction<E, T, E> operator;
E value;
public ReduceTask(ITERATOR KEY_GENERIC_TYPE iter, BiFunction<E, T, E> operator, E value) {
this.iter = iter;
this.operator = operator;
this.value = value;
}
@Override
protected boolean execute() throws Exception {
while(shouldRun() && iter.hasNext()) {
value = operator.apply(value, iter.NEXT());
}
if(!iter.hasNext()) {
setResult(value);
return true;
}
return false;
}
@Override
protected void onCompletion() {
super.onCompletion();
iter = null;
operator = null;
#if TYPE_OBJECT
value = null;
#endif
}
}
#endif
private static class SimpleReduceTask KEY_GENERIC_TYPE extends BASE_TASK KEY_GENERIC_TYPE
{
ITERATOR KEY_GENERIC_TYPE iter;
UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator;
boolean first = true;
KEY_TYPE value;
public SimpleReduceTask(ITERATOR KEY_GENERIC_TYPE iter, UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
this.iter = iter;
this.operator = operator;
}
@Override
protected boolean execute() throws Exception {
while(shouldRun() && iter.hasNext()) {
if(first) {
first = false;
value = iter.NEXT();
}
else {
value = operator.APPLY_VALUE(value, iter.NEXT());
}
}
if(!iter.hasNext()) {
setResult(value);
return true;
}
return false;
}
@Override
protected void onCompletion() {
super.onCompletion();
iter = null;
operator = null;
#if TYPE_OBJECT
value = null;
#endif
}
}
private static class MatchTask KEY_GENERIC_TYPE extends BaseBooleanTask
{
ITERATOR KEY_GENERIC_TYPE iter;
PREDICATE KEY_GENERIC_TYPE filter;
int type;
public MatchTask(ITERATOR KEY_GENERIC_TYPE iter, PREDICATE KEY_GENERIC_TYPE filter, int type) {
this.iter = iter;
this.filter = filter;
this.type = type;
if(type < 0 || type > 2) throw new IllegalArgumentException("Type is not allowed has to be between 0-2");
}
@Override
protected boolean execute() throws Exception {
switch(type) {
case 0:
while(shouldRun() && iter.hasNext()) {
#if TYPE_OBJECT
if(filter.getBoolean(iter.NEXT())) {
#else
if(filter.GET_VALUE(iter.NEXT())) {
#endif
setResult(true);
return true;
}
}
break;
case 1:
while(shouldRun() && iter.hasNext()) {
#if TYPE_OBJECT
if(filter.getBoolean(iter.NEXT())) {
#else
if(filter.GET_VALUE(iter.NEXT())) {
#endif
setResult(false);
return true;
}
}
break;
case 2:
while(shouldRun() && iter.hasNext()) {
#if TYPE_OBJECT
if(!filter.getBoolean(iter.NEXT())) {
#else
if(!filter.GET_VALUE(iter.NEXT())) {
#endif
setResult(false);
return true;
}
}
break;
}
if(!iter.hasNext()) {
setResult(type >= 1);
return true;
}
return false;
}
@Override
protected void onCompletion() {
super.onCompletion();
iter = null;
filter = null;
}
}
private static class FindFirstTask KEY_GENERIC_TYPE extends BASE_TASK KEY_GENERIC_TYPE
{
ITERATOR KEY_GENERIC_TYPE iter;
PREDICATE KEY_GENERIC_TYPE filter;
public FindFirstTask(ITERATOR KEY_GENERIC_TYPE iter, PREDICATE KEY_GENERIC_TYPE filter) {
this.iter = iter;
this.filter = filter;
}
@Override
protected boolean execute() throws Exception {
while(shouldRun() && iter.hasNext()) {
KEY_TYPE entry = iter.NEXT();
#if TYPE_OBJECT
if(filter.getBoolean(iter.NEXT())) {
#else
if(filter.GET_VALUE(iter.NEXT())) {
#endif
setResult(entry);
return true;
}
}
return !iter.hasNext();
}
@Override
protected void onCompletion() {
super.onCompletion();
iter = null;
filter = null;
}
}
private static class CountTask KEY_GENERIC_TYPE extends BaseIntTask
{
ITERATOR KEY_GENERIC_TYPE iter;
PREDICATE KEY_GENERIC_TYPE filter;
int counted = 0;
public CountTask(ITERATOR KEY_GENERIC_TYPE iter, PREDICATE KEY_GENERIC_TYPE filter) {
this.iter = iter;
this.filter = filter;
}
@Override
protected boolean execute() throws Exception {
while(shouldRun() && iter.hasNext()) {
if(filter.TEST_VALUE(iter.NEXT())) {
counted++;
}
}
if(!iter.hasNext())
{
setResult(counted);
return true;
}
return false;
}
@Override
protected void onCompletion() {
super.onCompletion();
iter = null;
filter = null;
}
}
private static class CollectTask KSS_GENERIC_TYPE<V, T extends COLLECTION KEY_SPECIAL_GENERIC_TYPE<V>> extends BaseObjectTask<T>
{
ITERATOR KEY_SPECIAL_GENERIC_TYPE<V> iter;
T collection;
public CollectTask(ITERATOR KEY_SPECIAL_GENERIC_TYPE<V> iter, T collection) {
this.iter = iter;
this.collection = collection;
}
@Override
protected boolean execute() throws Exception {
while(shouldRun() && iter.hasNext()) {
collection.add(iter.NEXT());
}
if(!iter.hasNext()) {
setResult(collection);
collection = null;
return true;
}
return false;
}
@Override
protected void onCompletion() {
super.onCompletion();
iter = null;
}
}
private static class ForEachTask<T> extends BaseObjectTask<Void>
{
ITERATOR KEY_GENERIC_TYPE iter;
CONSUMER KEY_GENERIC_TYPE listener;
public ForEachTask(ITERATOR KEY_GENERIC_TYPE iter, CONSUMER KEY_GENERIC_TYPE listener) {
this.iter = iter;
this.listener = listener;
}
@Override
protected boolean execute() throws Exception {
while(shouldRun() && iter.hasNext()) {
listener.accept(iter.NEXT());
}
return !iter.hasNext();
}
@Override
protected void onCompletion() {
super.onCompletion();
iter = null;
listener = null;
}
}
/**
* Base Task of the Actions that can be performed.
* Allows to simplify the actions that get executed.
* @Type(T)
*/
public abstract static class BASE_TASK KEY_GENERIC_TYPE implements TASK KEY_GENERIC_TYPE
{
private static final int CREATED = 0;
private static final int RUNNING = 1;
private static final int PAUSING = 2;
private static final int PAUSED = 3;
private static final int FINISHING = 4;
private static final int FINISHED = 5;
private static final int EXCEPTIONALLY = 6;
private static final int CANCELLED = 7;
private volatile WaitNode waiter;
private volatile int state = CREATED;
Consumer<TASK KEY_GENERIC_TYPE> callback;
Executor executor = SanityChecks::invokeAsyncTask;
KEY_TYPE result;
Throwable excpetion;
void withCallback(Consumer<TASK KEY_GENERIC_TYPE> callback) {
this.callback = callback;
}
void withExecutor(Executor executor) {
this.executor = executor;
}
void begin() {
executor.execute(this);
}
protected abstract boolean execute() throws Exception;
protected void onCompletion() {
if(callback != null) {
callback.accept(this);
callback = null;
}
executor = null;
}
protected void setResult(KEY_TYPE result) {
this.result = result;
}
@Override
public void run() {
state = RUNNING;
try {
if(execute()) {
state = FINISHING;
finishCompletion(FINISHED);
}
else if(state == PAUSING) {
state = PAUSED;
}
}
catch(Exception e) {
state = EXCEPTIONALLY;
this.excpetion = e;
finishCompletion(EXCEPTIONALLY);
}
}
private void finishCompletion(int nextState) {
WaitNode current = waiter;
waiter = null;
while(current != null) {
Thread t = current.thread;
if (t != null) {
current.thread = null;
LockSupport.unpark(t);
}
WaitNode next = current.next;
if (next == null)
break;
current.next = null;
current = next;
}
state = nextState;
onCompletion();
}
@Override
public boolean cancel(boolean cancelIfRunnning) {
if(state == RUNNING && !cancelIfRunnning) return false;
state = CANCELLED;
finishCompletion(CANCELLED);
return true;
}
@Override
public KEY_TYPE GET_KEY() throws InterruptedException, ExecutionException {
int s = state;
return report(s <= FINISHING ? awaitDone(false, 0L) : s);
}
@Override
public KEY_TYPE GET_KEY(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
if (unit == null) throw new NullPointerException();
int s = state;
if (s <= FINISHING && (s = awaitDone(true, unit.toNanos(timeout))) <= FINISHING) throw new TimeoutException();
return report(s);
}
private KEY_TYPE report(int s) throws ExecutionException {
if (s == FINISHED) return result;
if (s >= CANCELLED) throw new CancellationException();
throw new ExecutionException(excpetion);
}
private int awaitDone(boolean timed, long nanos) throws InterruptedException {
final long deadline = timed ? System.nanoTime() + nanos : 0L;
WaitNode q = null;
boolean queued = false;
while(true) {
if(Thread.interrupted()) {
removeWaiter(q);
throw new InterruptedException();
}
int s = state;
if(s > FINISHING) {
if(q != null) q.thread = null;
return s;
}
else if(s == FINISHING) Thread.yield();
else if(q == null) q = new WaitNode();
else if(!queued) {
q.next = waiter;
waiter = q;
queued = true;
}
else if(timed) {
nanos = deadline - System.nanoTime();
if(nanos <= 0L) {
removeWaiter(q);
return state;
}
LockSupport.parkNanos(this, nanos);
}
else LockSupport.park(this);
}
}
private void removeWaiter(WaitNode node) {
if(node == null) return;
node.thread = null;
retry:
while(true) {
for(WaitNode prev = null, current = waiter, next = null; current != null; current = next) {
next = current.next;
if(current.thread != null) prev = current;
else if(prev != null) {
prev.next = next;
if(prev.thread == null) continue retry; //Previous element got removed which means another thread was editing this while we were editing.
}
else if(waiter == current) {
waiter = next;
continue retry;
}
}
break;
}
}
@Override
public boolean isCancelled() { return state >= CANCELLED; }
@Override
public boolean isDone() { return state >= FINISHING; }
@Override
public boolean isPaused() { return state == PAUSED; }
@Override
public boolean isSuccessful() { return state == FINISHED; }
protected boolean shouldRun() { return state == RUNNING; }
@Override
public void pause() {
if(state == PAUSED || state == PAUSING || state >= FINISHING) return;
state = PAUSING;
}
@Override
public void awaitPausing() {
if(state == PAUSED) return;
pause();
if(state == PAUSING) {
while(state == PAUSING) {
Thread.yield();
}
}
}
@Override
public void resume() {
if(state != PAUSED && state != PAUSING) return;
if(state == PAUSING) {
while(state == PAUSING) {
Thread.yield();
}
}
state = RUNNING;
executor.execute(this);
}
static final class WaitNode {
volatile Thread thread;
volatile WaitNode next;
WaitNode() {
thread = Thread.currentThread();
}
}
}
}
@@ -3,6 +3,8 @@ package speiger.src.collections.PACKAGE.utils;
import java.util.Objects;
#if TYPE_BOOLEAN
import java.util.concurrent.atomic.AtomicInteger;
#else if TYPE_OBJECT
import java.util.Comparator;
#endif
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Consumer;
@@ -12,8 +14,11 @@ import speiger.src.collections.PACKAGE.collections.ITERABLE;
import speiger.src.collections.objects.collections.ObjectIterable;
import speiger.src.collections.objects.collections.ObjectIterator;
import speiger.src.collections.PACKAGE.functions.CONSUMER;
import speiger.src.collections.PACKAGE.functions.COMPARATOR;
#endif
import speiger.src.collections.PACKAGE.collections.ITERATOR;
import speiger.src.collections.PACKAGE.lists.LIST;
import speiger.src.collections.PACKAGE.lists.ARRAY_LIST;
import speiger.src.collections.PACKAGE.functions.function.TO_OBJECT_FUNCTION;
import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
#if !TYPE_BOOLEAN
@@ -164,6 +169,30 @@ public class ITERABLES
return new LimitedIterableBRACES(wrap(iterable), limit);
}
/**
* A Helper function that sorts the Iterable.
* This operation is heavily hurting performance because it rebuilds the entire iterator and then sorts it.
* @param iterable that should be sorted
* @param sorter that sorts the iterable. Can be null.
* @Type(T)
* @return a sorted iterable.
*/
public static GENERIC_KEY_BRACES ITERABLE KEY_GENERIC_TYPE sorted(ITERABLE KEY_GENERIC_TYPE iterable, COMPARATOR KEY_GENERIC_TYPE sorter) {
return new SortedIterableBRACES(iterable, sorter);
}
/**
* A Helper function that sorts the Iterable from a Java Iterable
* This operation is heavily hurting performance because it rebuilds the entire iterator and then sorts it.
* @param iterable that should be sorted
* @param sorter that sorts the iterable. Can be null.
* @Type(T)
* @return a sorted iterable.
*/
public static GENERIC_KEY_BRACES ITERABLE KEY_GENERIC_TYPE sorted(Iterable<? extends CLASS_TYPE> iterable, COMPARATOR KEY_GENERIC_TYPE sorter) {
return new SortedIterableBRACES(wrap(iterable), sorter);
}
/**
* A Helper function that allows to preview the result of a Iterable.
* @param iterable that should be peeked at
@@ -359,6 +388,42 @@ public class ITERABLES
#endif
}
private static class SortedIterable KEY_GENERIC_TYPE implements ITERABLE KEY_GENERIC_TYPE
{
ITERABLE KEY_GENERIC_TYPE iterable;
COMPARATOR KEY_GENERIC_TYPE sorter;
public SortedIterable(ITERABLE KEY_GENERIC_TYPE iterable, COMPARATOR KEY_GENERIC_TYPE sorter) {
this.iterable = iterable;
this.sorter = sorter;
}
@Override
public ITERATOR KEY_GENERIC_TYPE iterator() {
return ITERATORS.sorted(iterable.iterator(), sorter);
}
#if !TYPE_OBJECT
@Override
public void forEach(CONSUMER action) {
Objects.requireNonNull(action);
LIST KEY_GENERIC_TYPE list = new ARRAY_LISTBRACES();
iterable.forEach(list::add);
list.unstableSort(sorter);
list.forEach(action);
}
#else
@Override
public void forEach(Consumer<? super CLASS_TYPE> action) {
Objects.requireNonNull(action);
LIST KEY_GENERIC_TYPE list = new ARRAY_LISTBRACES();
iterable.forEach(list::add);
list.unstableSort(sorter);
list.forEach(action);
}
#endif
}
private static class DistinctIterable KEY_GENERIC_TYPE implements ITERABLE KEY_GENERIC_TYPE
{
ITERABLE KEY_GENERIC_TYPE iterable;
@@ -3,6 +3,7 @@ package speiger.src.collections.PACKAGE.utils;
import java.util.Iterator;
import java.util.NoSuchElementException;
#if TYPE_OBJECT
import java.util.Comparator;
import java.util.function.CONSUMER;
#endif
@@ -11,6 +12,7 @@ import speiger.src.collections.PACKAGE.collections.ITERATOR;
import speiger.src.collections.objects.collections.ObjectIterator;
import speiger.src.collections.objects.utils.ObjectIterators;
import speiger.src.collections.PACKAGE.functions.CONSUMER;
import speiger.src.collections.PACKAGE.functions.COMPARATOR;
#endif
import speiger.src.collections.PACKAGE.functions.function.TO_OBJECT_FUNCTION;
import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
@@ -32,7 +34,7 @@ public class ITERATORS
/**
* Empty Iterator Reference
*/
public static final EmptyIterator NO_GENERIC_TYPE EMPTY = new EmptyIteratorBRACES();
private static final EmptyIterator NO_GENERIC_TYPE EMPTY = new EmptyIteratorBRACES();
/**
* Returns a Immutable EmptyIterator instance that is automatically casted.
@@ -235,6 +237,30 @@ public class ITERATORS
return new LimitedIteratorBRACES(wrap(iterator), limit);
}
/**
* A Helper function that sorts the Iterator beforehand.
* This operation is heavily hurting performance because it rebuilds the entire iterator and then sorts it.
* @param iterator that should be sorted.
* @param sorter the sorter of the iterator. Can be null.
* @Type(T)
* @return a new sorted iterator
*/
public static GENERIC_KEY_BRACES ITERATOR KEY_GENERIC_TYPE sorted(ITERATOR KEY_GENERIC_TYPE iterator, COMPARATOR KEY_GENERIC_TYPE sorter) {
return new SortedIteratorBRACES(iterator, sorter);
}
/**
* A Helper function that sorts the Iterator beforehand from a Java Iterator.
* This operation is heavily hurting performance because it rebuilds the entire iterator and then sorts it.
* @param iterator that should be sorted.
* @param sorter the sorter of the iterator. Can be null.
* @Type(T)
* @return a new sorted iterator
*/
public static GENERIC_KEY_BRACES ITERATOR KEY_GENERIC_TYPE sorted(Iterator<? extends CLASS_TYPE> iterator, COMPARATOR KEY_GENERIC_TYPE sorter) {
return new SortedIteratorBRACES(wrap(iterator), sorter);
}
/**
* A Helper function that allows to preview the result of a Iterator.
* @param iterator that should be peeked at
@@ -709,7 +735,7 @@ public class ITERATORS
@Override
public KEY_TYPE NEXT() {
return EMPTY_KEY_VALUE;
throw new NoSuchElementException();
}
@Override
@@ -719,7 +745,7 @@ public class ITERATORS
@Override
public KEY_TYPE PREVIOUS() {
return EMPTY_KEY_VALUE;
throw new NoSuchElementException();
}
@Override
@@ -761,6 +787,7 @@ public class ITERATORS
@Override
public KEY_TYPE NEXT() {
if(!hasNext()) throw new NoSuchElementException();
return a[from++];
}
@@ -828,7 +855,7 @@ public class ITERATORS
@Override
public T next() {
if(!hasNext()) throw new IllegalStateException("End of Iterator");
if(!hasNext()) throw new NoSuchElementException();
T result = last.next();
foundNext = false;
return result;
@@ -864,13 +891,42 @@ public class ITERATORS
@Override
public T next() {
if(!hasNext()) throw new IllegalStateException("End of Iterator");
if(!hasNext()) throw new NoSuchElementException();
T result = last.next();
foundNext = false;
return result;
}
}
private static class SortedIterator KEY_GENERIC_TYPE implements ITERATOR KEY_GENERIC_TYPE
{
ITERATOR KEY_GENERIC_TYPE iterator;
COMPARATOR KEY_GENERIC_TYPE sorter;
LIST KEY_GENERIC_TYPE sortedElements = null;
int index = 0;
public SortedIterator(ITERATOR KEY_GENERIC_TYPE iterator, COMPARATOR KEY_GENERIC_TYPE sorter) {
this.iterator = iterator;
this.sorter = sorter;
}
@Override
public boolean hasNext() {
if(sortedElements == null) {
boolean hasNext = iterator.hasNext();
sortedElements = hasNext ? pour(iterator) : LISTS.empty();
if(hasNext) sortedElements.unstableSort(sorter);
}
return index < sortedElements.size();
}
@Override
public KEY_TYPE NEXT() {
if(!hasNext()) throw new NoSuchElementException();
return sortedElements.GET_KEY(index++);
}
}
private static class DistinctIterator KEY_GENERIC_TYPE implements ITERATOR KEY_GENERIC_TYPE
{
ITERATOR KEY_GENERIC_TYPE iterator;
@@ -916,7 +972,7 @@ public class ITERATORS
@Override
public KEY_TYPE NEXT() {
if(!hasNext()) throw new IllegalStateException("End of Iterator");
if(!hasNext()) throw new NoSuchElementException();
foundNext = false;
return lastFound;
}
@@ -953,7 +1009,7 @@ public class ITERATORS
@Override
public KEY_TYPE NEXT() {
if(!hasNext()) throw new IllegalStateException("End of Iterator");
if(!hasNext()) throw new NoSuchElementException();
foundNext = false;
return lastFound;
}
@@ -976,7 +1032,7 @@ public class ITERATORS
@Override
public KEY_TYPE NEXT() {
if(!hasNext()) throw new IllegalStateException("End of Iterator");
if(!hasNext()) throw new NoSuchElementException();
limit--;
return iterator.NEXT();
}
@@ -999,7 +1055,7 @@ public class ITERATORS
@Override
public KEY_TYPE NEXT() {
if(!hasNext()) throw new IllegalStateException("End of Iterator");
if(!hasNext()) throw new NoSuchElementException();
KEY_TYPE result = iterator.NEXT();
action.accept(result);
return result;
@@ -27,7 +27,7 @@ public class LISTS
/**
* Empty List reference
*/
public static final EmptyList NO_GENERIC_TYPE EMPTY = new EmptyListBRACES();
private static final EmptyList NO_GENERIC_TYPE EMPTY = new EmptyListBRACES();
/**
* Returns a Immutable EmptyList instance that is automatically casted.
@@ -1,5 +1,6 @@
package speiger.src.collections.PACKAGE.utils;
import java.util.NoSuchElementException;
#if TYPE_BOOLEAN
import speiger.src.collections.booleans.collections.BooleanIterator;
import speiger.src.collections.booleans.sets.AbstractBooleanSet;
@@ -18,6 +19,7 @@ import speiger.src.collections.PACKAGE.collections.ITERATOR;
import speiger.src.collections.PACKAGE.sets.NAVIGABLE_SET;
import speiger.src.collections.PACKAGE.sets.ABSTRACT_SET;
import speiger.src.collections.PACKAGE.sets.SET;
import speiger.src.collections.PACKAGE.sets.ORDERED_SET;
import speiger.src.collections.PACKAGE.sets.SORTED_SET;
import speiger.src.collections.PACKAGE.utils.COLLECTIONS.EmptyCollection;
import speiger.src.collections.PACKAGE.utils.COLLECTIONS.SynchronizedCollection;
@@ -33,7 +35,7 @@ public class SETS
/**
* Empty Set Variable
*/
public static final SET NO_GENERIC_TYPE EMPTY = new EmptySetBRACES();
private static final SET NO_GENERIC_TYPE EMPTY = new EmptySetBRACES();
/**
* EmptySet getter
@@ -95,6 +97,29 @@ public class SETS
return s instanceof SynchronizedSortedSet ? s : (s instanceof ITrimmable ? new SynchronizedSortedTrimSetBRACES(s, mutex) : new SynchronizedSortedSetBRACES(s, mutex));
}
/**
* Creates a Synchronized OrderedSet while preserving the ITrimmable interface
* @param s the set that should be synchronized
* @Type(T)
* @return a OrderedSet that is synchronized
* @note if the set is already synchronized then it will just self return it
*/
public static GENERIC_KEY_BRACES ORDERED_SET KEY_GENERIC_TYPE synchronize(ORDERED_SET KEY_GENERIC_TYPE s) {
return s instanceof SynchronizedOrderedSet ? s : (s instanceof ITrimmable ? new SynchronizedOrderedTrimSetBRACES(s) : new SynchronizedOrderedSetBRACES(s));
}
/**
* Creates a Synchronized OrderedSet while preserving the ITrimmable interface
* @param s the set that should be synchronized
* @param mutex controller for access
* @Type(T)
* @return a OrderedSet that is synchronized
* @note if the set is already synchronized then it will just self return it
*/
public static GENERIC_KEY_BRACES ORDERED_SET KEY_GENERIC_TYPE synchronize(ORDERED_SET KEY_GENERIC_TYPE s, Object mutex) {
return s instanceof SynchronizedOrderedSet ? s : (s instanceof ITrimmable ? new SynchronizedOrderedTrimSetBRACES(s, mutex) : new SynchronizedOrderedSetBRACES(s, mutex));
}
/**
* Creates a Synchronized NavigableSet while preserving the ITrimmable interface
* @param s the set that should be synchronized
@@ -138,6 +163,16 @@ public class SETS
return s instanceof UnmodifiableSortedSet ? s : new UnmodifiableSortedSetBRACES(s);
}
/**
* Creates Unmodifyable OrderedSet wrapper
* @param s OrderedSet that should be made unmodifiable
* @Type(T)
* @return a UnmodifyableOrderedSet, if the set is already unmodifiable then it returns itself
*/
public static GENERIC_KEY_BRACES ORDERED_SET KEY_GENERIC_TYPE unmodifiable(ORDERED_SET KEY_GENERIC_TYPE s) {
return s instanceof UnmodifiableOrderedSet ? s : new UnmodifiableOrderedSetBRACES(s);
}
/**
* Creates Unmodifyable NavigableSet wrapper
* @param s navigableSet that should be made unmodifiable
@@ -173,16 +208,19 @@ public class SETS
#endif
@Override
public boolean add(KEY_TYPE o) { throw new UnsupportedOperationException(); }
#if TYPE_OBJECT
public KEY_TYPE addOrGet(KEY_TYPE o) { throw new UnsupportedOperationException(); }
#endif
@Override
public ITERATOR KEY_GENERIC_TYPE iterator()
{
return new ITERATOR KEY_GENERIC_TYPE() {
boolean next = true;
@Override
public boolean hasNext() { return next = false; }
public boolean hasNext() { return next; }
@Override
public KEY_TYPE NEXT() {
if(!next) throw new IllegalStateException();
if(!hasNext()) throw new NoSuchElementException();
next = false;
return element;
}
@@ -200,6 +238,9 @@ public class SETS
#if !TYPE_OBJECT
@Override
public boolean remove(KEY_TYPE o) { throw new UnsupportedOperationException(); }
#else
@Override
public KEY_TYPE addOrGet(KEY_TYPE o) { throw new UnsupportedOperationException(); }
#endif
@Override
public EmptySet KEY_GENERIC_TYPE copy() { return this; }
@@ -278,6 +319,39 @@ public class SETS
public NAVIGABLE_SET KEY_GENERIC_TYPE tailSet(KEY_TYPE fromElement) { return SETS.unmodifiable(n.tailSet(fromElement)); }
}
private static class UnmodifiableOrderedSet KEY_GENERIC_TYPE extends UnmodifiableSet KEY_GENERIC_TYPE implements ORDERED_SET KEY_GENERIC_TYPE
{
ORDERED_SET KEY_GENERIC_TYPE s;
UnmodifiableOrderedSet(ORDERED_SET KEY_GENERIC_TYPE c)
{
super(c);
s = c;
}
@Override
public boolean addAndMoveToFirst(KEY_TYPE o) { throw new UnsupportedOperationException(); }
@Override
public boolean addAndMoveToLast(KEY_TYPE o) { throw new UnsupportedOperationException(); }
@Override
public boolean moveToFirst(KEY_TYPE o) { throw new UnsupportedOperationException(); }
@Override
public boolean moveToLast(KEY_TYPE o) { throw new UnsupportedOperationException(); }
@Override
public BI_ITERATOR KEY_GENERIC_TYPE iterator() { return ITERATORS.unmodifiable(s.iterator()); }
@Override
public BI_ITERATOR KEY_GENERIC_TYPE iterator(KEY_TYPE fromElement) { return ITERATORS.unmodifiable(s.iterator(fromElement)); }
@Override
public ORDERED_SET KEY_GENERIC_TYPE copy() { return s.copy(); }
@Override
public KEY_TYPE FIRST_KEY() { return s.FIRST_KEY(); }
@Override
public KEY_TYPE POLL_FIRST_KEY() { throw new UnsupportedOperationException(); }
@Override
public KEY_TYPE LAST_KEY() { return s.LAST_KEY(); }
@Override
public KEY_TYPE POLL_LAST_KEY() { throw new UnsupportedOperationException(); }
}
private static class UnmodifiableSortedSet KEY_GENERIC_TYPE extends UnmodifiableSet KEY_GENERIC_TYPE implements SORTED_SET KEY_GENERIC_TYPE
{
SORTED_SET KEY_GENERIC_TYPE s;
@@ -287,48 +361,26 @@ public class SETS
s = c;
}
@Override
public boolean addAndMoveToFirst(KEY_TYPE o) { throw new UnsupportedOperationException(); }
@Override
public boolean addAndMoveToLast(KEY_TYPE o) { throw new UnsupportedOperationException(); }
@Override
public boolean moveToFirst(KEY_TYPE o) { throw new UnsupportedOperationException(); }
@Override
public boolean moveToLast(KEY_TYPE o) { throw new UnsupportedOperationException(); }
@Override
public COMPARATOR KEY_GENERIC_TYPE comparator() { return s.comparator(); }
@Override
public BI_ITERATOR KEY_GENERIC_TYPE iterator() { return ITERATORS.unmodifiable(s.iterator()); }
@Override
public BI_ITERATOR KEY_GENERIC_TYPE iterator(KEY_TYPE fromElement) { return ITERATORS.unmodifiable(s.iterator(fromElement)); }
@Override
public SORTED_SET KEY_GENERIC_TYPE copy() { return s.copy(); }
@Override
public SORTED_SET KEY_GENERIC_TYPE subSet(KEY_TYPE fromElement, KEY_TYPE toElement) { return SETS.unmodifiable(s.subSet(fromElement, toElement)); }
@Override
public SORTED_SET KEY_GENERIC_TYPE headSet(KEY_TYPE toElement) { return SETS.unmodifiable(s.headSet(toElement)); }
@Override
public SORTED_SET KEY_GENERIC_TYPE tailSet(KEY_TYPE fromElement) { return SETS.unmodifiable(s.tailSet(fromElement)); }
@Override
public KEY_TYPE FIRST_KEY() { return s.FIRST_KEY(); }
@Override
public KEY_TYPE POLL_FIRST_KEY() { throw new UnsupportedOperationException(); }
@Override
public KEY_TYPE LAST_KEY() { return s.LAST_KEY(); }
@Override
public KEY_TYPE POLL_LAST_KEY() { throw new UnsupportedOperationException(); }
}
@@ -347,6 +399,11 @@ public class SETS
s = c;
}
#if TYPE_OBJECT
@Override
public KEY_TYPE addOrGet(KEY_TYPE o) { throw new UnsupportedOperationException(); }
#endif
@Override
public SET KEY_GENERIC_TYPE copy() { return s.copy(); }
@@ -489,48 +546,85 @@ public class SETS
s = c;
}
@Override
public boolean addAndMoveToFirst(KEY_TYPE o) { synchronized(mutex) { return s.addAndMoveToFirst(o); } }
@Override
public boolean addAndMoveToLast(KEY_TYPE o) { synchronized(mutex) { return s.addAndMoveToLast(o); } }
@Override
public boolean moveToFirst(KEY_TYPE o) { synchronized(mutex) { return s.moveToFirst(o); } }
@Override
public boolean moveToLast(KEY_TYPE o) { synchronized(mutex) { return s.moveToLast(o); } }
@Override
public COMPARATOR KEY_GENERIC_TYPE comparator(){ synchronized(mutex) { return s.comparator(); } }
@Override
public BI_ITERATOR KEY_GENERIC_TYPE iterator() { synchronized(mutex) { return s.iterator(); } }
@Override
public BI_ITERATOR KEY_GENERIC_TYPE iterator(KEY_TYPE fromElement) { synchronized(mutex) { return s.iterator(fromElement); } }
@Override
public SORTED_SET KEY_GENERIC_TYPE copy() { synchronized(mutex) { return s.copy(); } }
@Override
public SORTED_SET KEY_GENERIC_TYPE subSet(KEY_TYPE fromElement, KEY_TYPE toElement) { synchronized(mutex) { return SETS.synchronize(s.subSet(fromElement, toElement), mutex); } }
@Override
public SORTED_SET KEY_GENERIC_TYPE headSet(KEY_TYPE toElement) { synchronized(mutex) { return SETS.synchronize(s.headSet(toElement), mutex); } }
@Override
public SORTED_SET KEY_GENERIC_TYPE tailSet(KEY_TYPE fromElement) { synchronized(mutex) { return SETS.synchronize(s.tailSet(fromElement), mutex); } }
@Override
public KEY_TYPE FIRST_KEY() { synchronized(mutex) { return s.FIRST_KEY(); } }
@Override
public KEY_TYPE POLL_FIRST_KEY() { synchronized(mutex) { return s.POLL_FIRST_KEY(); } }
@Override
public KEY_TYPE LAST_KEY() { synchronized(mutex) { return s.LAST_KEY(); } }
@Override
public KEY_TYPE POLL_LAST_KEY() { synchronized(mutex) { return s.POLL_LAST_KEY(); } }
}
private static class SynchronizedOrderedTrimSet KEY_GENERIC_TYPE extends SynchronizedOrderedSet KEY_GENERIC_TYPE implements ITrimmable
{
ITrimmable trim;
SynchronizedOrderedTrimSet(ORDERED_SET KEY_GENERIC_TYPE c) {
super(c);
trim = (ITrimmable)c;
}
SynchronizedOrderedTrimSet(ORDERED_SET KEY_GENERIC_TYPE c, Object mutex) {
super(c, mutex);
trim = (ITrimmable)c;
}
@Override
public boolean trim(int size) { synchronized(mutex) { return trim.trim(size); } }
@Override
public void clearAndTrim(int size) { synchronized(mutex) { trim.clearAndTrim(size); } }
}
private static class SynchronizedOrderedSet KEY_GENERIC_TYPE extends SynchronizedSet KEY_GENERIC_TYPE implements ORDERED_SET KEY_GENERIC_TYPE
{
ORDERED_SET KEY_GENERIC_TYPE s;
SynchronizedOrderedSet(ORDERED_SET KEY_GENERIC_TYPE c) {
super(c);
s = c;
}
SynchronizedOrderedSet(ORDERED_SET KEY_GENERIC_TYPE c, Object mutex) {
super(c, mutex);
s = c;
}
@Override
public boolean addAndMoveToFirst(KEY_TYPE o) { synchronized(mutex) { return s.addAndMoveToFirst(o); } }
@Override
public boolean addAndMoveToLast(KEY_TYPE o) { synchronized(mutex) { return s.addAndMoveToLast(o); } }
@Override
public boolean moveToFirst(KEY_TYPE o) { synchronized(mutex) { return s.moveToFirst(o); } }
@Override
public boolean moveToLast(KEY_TYPE o) { synchronized(mutex) { return s.moveToLast(o); } }
@Override
public BI_ITERATOR KEY_GENERIC_TYPE iterator() { synchronized(mutex) { return s.iterator(); } }
@Override
public BI_ITERATOR KEY_GENERIC_TYPE iterator(KEY_TYPE fromElement) { synchronized(mutex) { return s.iterator(fromElement); } }
@Override
public ORDERED_SET KEY_GENERIC_TYPE copy() { synchronized(mutex) { return s.copy(); } }
@Override
public KEY_TYPE FIRST_KEY() { synchronized(mutex) { return s.FIRST_KEY(); } }
@Override
public KEY_TYPE POLL_FIRST_KEY() { synchronized(mutex) { return s.POLL_FIRST_KEY(); } }
@Override
public KEY_TYPE LAST_KEY() { synchronized(mutex) { return s.LAST_KEY(); } }
@Override
public KEY_TYPE POLL_LAST_KEY() { synchronized(mutex) { return s.POLL_LAST_KEY(); } }
}
@@ -570,6 +664,11 @@ public class SETS
s = c;
}
#if TYPE_OBJECT
@Override
public KEY_TYPE addOrGet(KEY_TYPE o) { synchronized(mutex) { return s.addOrGet(o); } }
#endif
@Override
public SET KEY_GENERIC_TYPE copy() { synchronized(mutex) { return s.copy(); } }
@@ -1,6 +1,7 @@
package speiger.src.collections.PACKAGE.utils;
import java.util.Comparator;
import java.util.NoSuchElementException;
import java.util.Spliterator;
#if PRIMITIVES
import java.util.Spliterator.JAVA_SPLIT_ITERATOR;
@@ -329,7 +330,11 @@ public class SPLIT_ITERATORS
}
@Override
public KEY_TYPE NEXT() { return array[index++]; }
public KEY_TYPE NEXT() {
if(!hasNext()) throw new NoSuchElementException();
return array[index++];
}
@Override
public boolean hasNext() { return index < fence; }
}
@@ -32,6 +32,7 @@ import speiger.src.collections.PACKAGE.maps.interfaces.MAP;
#if !TYPE_BOOLEAN
import speiger.src.collections.PACKAGE.maps.interfaces.NAVIGABLE_MAP;
import speiger.src.collections.PACKAGE.maps.interfaces.SORTED_MAP;
import speiger.src.collections.PACKAGE.maps.interfaces.ORDERED_MAP;
import speiger.src.collections.PACKAGE.sets.NAVIGABLE_SET;
#if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.sets.SET;
@@ -56,7 +57,21 @@ public class MAPS
/**
* Empty Map Variable
*/
public static final MAP NO_KV_GENERIC_TYPE EMPTY = new EmptyMapKV_BRACES();
private static final MAP NO_KV_GENERIC_TYPE EMPTY = new EmptyMapKV_BRACES();
/**
* Empty Map getter function that autocasts to the desired Key and Value
* @Type(T)
* @ValueType(V)
* @return empty map of desired type
*/
public static GENERIC_KEY_VALUE_BRACES MAP KEY_VALUE_GENERIC_TYPE empty() {
#if TYPE_OBJECT || VALUE_OBJECT
return (MAP KEY_VALUE_GENERIC_TYPE)EMPTY;
#else
return EMPTY;
#endif
}
#endif
/**
@@ -103,19 +118,6 @@ public class MAPS
}
#if !TYPE_BOOLEAN
/**
* Empty Map getter function that autocasts to the desired Key and Value
* @Type(T)
* @ValueType(V)
* @return empty map of desired type
*/
public static GENERIC_KEY_VALUE_BRACES MAP KEY_VALUE_GENERIC_TYPE empty() {
#if TYPE_OBJECT || VALUE_OBJECT
return (MAP KEY_VALUE_GENERIC_TYPE)EMPTY;
#else
return EMPTY;
#endif
}
/**
* Helper function that creates a Helper wrapper to synchronize access into the map.
@@ -161,6 +163,28 @@ public class MAPS
*/
public static GENERIC_KEY_VALUE_BRACES SORTED_MAP KEY_VALUE_GENERIC_TYPE synchronize(SORTED_MAP KEY_VALUE_GENERIC_TYPE map, Object mutex) { return map instanceof SynchronizedSortedMap ? map : new SynchronizedSortedMapKV_BRACES(map, mutex); }
/**
* Helper function that creates a Helper wrapper to synchronize access into the OrderedMap.
* @param map the OrderedMap that should be synchronized
* @Type(T)
* @ValueType(V)
* @return a synchronized OrderedMap
* @note if the inputted map is already synchronized then it will just return it instead
* @note iterators do not support synchronization
*/
public static GENERIC_KEY_VALUE_BRACES ORDERED_MAP KEY_VALUE_GENERIC_TYPE synchronize(ORDERED_MAP KEY_VALUE_GENERIC_TYPE map) { return map instanceof SynchronizedOrderedMap ? map : new SynchronizedOrderedMapKV_BRACES(map); }
/**
* Helper function that creates a Helper wrapper to synchronize access with custom access control into the OrderedMap.
* @param map the OrderedMap that should be synchronized
* @param mutex the object that controls access
* @Type(T)
* @ValueType(V)
* @return a synchronized OrderedMap
* @note if the inputted map is already synchronized then it will just return it instead
* @note iterators do not support synchronization
*/
public static GENERIC_KEY_VALUE_BRACES ORDERED_MAP KEY_VALUE_GENERIC_TYPE synchronize(ORDERED_MAP KEY_VALUE_GENERIC_TYPE map, Object mutex) { return map instanceof SynchronizedOrderedMap ? map : new SynchronizedOrderedMapKV_BRACES(map, mutex); }
/**
* Helper function that creates a Helper wrapper to synchronize access into the NavigableMap.
* @param map the NavigableMap that should be synchronized
@@ -192,6 +216,17 @@ public class MAPS
* @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 unmodifiable(MAP KEY_VALUE_GENERIC_TYPE map) { return map instanceof UnmodifyableMap ? map : new UnmodifyableMapKV_BRACES(map); }
/**
* A Helper function that creates a Helper wrapper to only allow Read Access into the OrderedMap
* @param map the OrderedMap that should be made Unmodifiable
* @Type(T)
* @ValueType(V)
* @return a unmodifiable OrderedMap
* @note if the inputted OrderedMap is already unmodifiable then it will just return it instead
*/
public static GENERIC_KEY_VALUE_BRACES ORDERED_MAP KEY_VALUE_GENERIC_TYPE unmodifiable(ORDERED_MAP KEY_VALUE_GENERIC_TYPE map) { return map instanceof UnmodifyableOrderedMap ? map : new UnmodifyableOrderedMapKV_BRACES(map); }
/**
* A Helper function that creates a Helper wrapper to only allow Read Access into the SortedMap
* @param map the SortedMap that should be made Unmodifiable
@@ -201,6 +236,7 @@ public class MAPS
* @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 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
* @param map the NavigableMap that should be made Unmodifiable
@@ -210,6 +246,7 @@ public class MAPS
* @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 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
* @param entry the Entry that should be made unmodifiable
@@ -262,6 +299,8 @@ public class MAPS
#if VALUE_PRIMITIVES
@Override
public VALUE_TYPE addTo(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); }
@Override
public VALUE_TYPE subFrom(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); }
#endif
@Override
public VALUE_TYPE REMOVE_VALUE(KEY_TYPE key) { throw new UnsupportedOperationException(); }
@@ -310,6 +349,8 @@ public class MAPS
#if VALUE_PRIMITIVES
@Override
public VALUE_TYPE addTo(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); }
@Override
public VALUE_TYPE subFrom(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); }
#endif
@Override
public VALUE_TYPE REMOVE_VALUE(KEY_TYPE key) { throw new UnsupportedOperationException(); }
@@ -424,14 +465,14 @@ public class MAPS
}
/**
* The Unmodifyable Sorted Map implementation that is sued for the unmodifyableMap function
* The Unmodifyable Ordered Map implementation that is sued for the unmodifyableMap function
* @Type(T)
* @ValueType(V)
*/
public static class UnmodifyableSortedMap KEY_VALUE_GENERIC_TYPE extends UnmodifyableMap KEY_VALUE_GENERIC_TYPE implements SORTED_MAP KEY_VALUE_GENERIC_TYPE {
SORTED_MAP KEY_VALUE_GENERIC_TYPE map;
public static class UnmodifyableOrderedMap KEY_VALUE_GENERIC_TYPE extends UnmodifyableMap KEY_VALUE_GENERIC_TYPE implements ORDERED_MAP KEY_VALUE_GENERIC_TYPE {
ORDERED_MAP KEY_VALUE_GENERIC_TYPE map;
UnmodifyableSortedMap(SORTED_MAP KEY_VALUE_GENERIC_TYPE map) {
UnmodifyableOrderedMap(ORDERED_MAP KEY_VALUE_GENERIC_TYPE map) {
super(map);
this.map = map;
}
@@ -448,6 +489,35 @@ public class MAPS
public VALUE_TYPE getAndMoveToFirst(KEY_TYPE key) { throw new UnsupportedOperationException(); }
@Override
public VALUE_TYPE getAndMoveToLast(KEY_TYPE key) { throw new UnsupportedOperationException(); }
@Override
public KEY_TYPE FIRST_ENTRY_KEY() { return map.FIRST_ENTRY_KEY(); }
@Override
public KEY_TYPE POLL_FIRST_ENTRY_KEY() { return map.POLL_FIRST_ENTRY_KEY(); }
@Override
public KEY_TYPE LAST_ENTRY_KEY() { return map.LAST_ENTRY_KEY(); }
@Override
public KEY_TYPE POLL_LAST_ENTRY_KEY() { return map.POLL_LAST_ENTRY_KEY(); }
@Override
public VALUE_TYPE FIRST_ENTRY_VALUE() { return map.FIRST_ENTRY_VALUE(); }
@Override
public VALUE_TYPE LAST_ENTRY_VALUE() { return map.LAST_ENTRY_VALUE(); }
@Override
public ORDERED_MAP KEY_VALUE_GENERIC_TYPE copy() { throw new UnsupportedOperationException(); }
}
/**
* The Unmodifyable Sorted Map implementation that is sued for the unmodifyableMap function
* @Type(T)
* @ValueType(V)
*/
public static class UnmodifyableSortedMap KEY_VALUE_GENERIC_TYPE extends UnmodifyableMap KEY_VALUE_GENERIC_TYPE implements SORTED_MAP KEY_VALUE_GENERIC_TYPE {
SORTED_MAP KEY_VALUE_GENERIC_TYPE map;
UnmodifyableSortedMap(SORTED_MAP KEY_VALUE_GENERIC_TYPE map) {
super(map);
this.map = map;
}
@Override
public COMPARATOR KEY_GENERIC_TYPE comparator() { return map.comparator(); }
@Override
@@ -494,6 +564,8 @@ public class MAPS
#if VALUE_PRIMITIVES
@Override
public VALUE_TYPE addTo(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); }
@Override
public VALUE_TYPE subFrom(KEY_TYPE key, VALUE_TYPE value) { throw new UnsupportedOperationException(); }
#endif
@Override
public VALUE_TYPE REMOVE_VALUE(KEY_TYPE key) { throw new UnsupportedOperationException(); }
@@ -680,6 +752,52 @@ public class MAPS
#endif
}
/**
* The Synchronized Ordered Map implementation used by the synchronizedMap helper function
* @Type(T)
* @ValueType(V)
*/
public static class SynchronizedOrderedMap KEY_VALUE_GENERIC_TYPE extends SynchronizedMap KEY_VALUE_GENERIC_TYPE implements ORDERED_MAP KEY_VALUE_GENERIC_TYPE {
ORDERED_MAP KEY_VALUE_GENERIC_TYPE map;
SynchronizedOrderedMap(ORDERED_MAP KEY_VALUE_GENERIC_TYPE map) {
super(map);
this.map = map;
}
SynchronizedOrderedMap(ORDERED_MAP KEY_VALUE_GENERIC_TYPE map, Object mutex) {
super(map, mutex);
this.map = map;
}
@Override
public VALUE_TYPE putAndMoveToFirst(KEY_TYPE key, VALUE_TYPE value) { synchronized(mutex) { return map.putAndMoveToFirst(key, value); } }
@Override
public VALUE_TYPE putAndMoveToLast(KEY_TYPE key, VALUE_TYPE value) { synchronized(mutex) { return map.putAndMoveToLast(key, value); } }
@Override
public boolean moveToFirst(KEY_TYPE key) { synchronized(mutex) { return map.moveToFirst(key); } }
@Override
public boolean moveToLast(KEY_TYPE key) { synchronized(mutex) { return map.moveToLast(key); } }
@Override
public VALUE_TYPE getAndMoveToFirst(KEY_TYPE key) { synchronized(mutex) { return map.getAndMoveToFirst(key); } }
@Override
public VALUE_TYPE getAndMoveToLast(KEY_TYPE key) { synchronized(mutex) { return map.getAndMoveToLast(key); } }
@Override
public KEY_TYPE FIRST_ENTRY_KEY() { synchronized(mutex) { return map.FIRST_ENTRY_KEY(); } }
@Override
public KEY_TYPE POLL_FIRST_ENTRY_KEY() { synchronized(mutex) { return map.POLL_FIRST_ENTRY_KEY(); } }
@Override
public KEY_TYPE LAST_ENTRY_KEY() { synchronized(mutex) { return map.LAST_ENTRY_KEY(); } }
@Override
public KEY_TYPE POLL_LAST_ENTRY_KEY() { synchronized(mutex) { return map.POLL_LAST_ENTRY_KEY(); } }
@Override
public VALUE_TYPE FIRST_ENTRY_VALUE() { synchronized(mutex) { return map.FIRST_ENTRY_VALUE(); } }
@Override
public VALUE_TYPE LAST_ENTRY_VALUE() { synchronized(mutex) { return map.LAST_ENTRY_VALUE(); } }
@Override
public ORDERED_MAP KEY_VALUE_GENERIC_TYPE copy() { throw new UnsupportedOperationException(); }
}
/**
* The Synchronized Sorted Map implementation used by the synchronizedMap helper function
* @Type(T)
@@ -698,18 +816,6 @@ public class MAPS
this.map = map;
}
@Override
public VALUE_TYPE putAndMoveToFirst(KEY_TYPE key, VALUE_TYPE value) { synchronized(mutex) { return map.putAndMoveToFirst(key, value); } }
@Override
public VALUE_TYPE putAndMoveToLast(KEY_TYPE key, VALUE_TYPE value) { synchronized(mutex) { return map.putAndMoveToLast(key, value); } }
@Override
public boolean moveToFirst(KEY_TYPE key) { synchronized(mutex) { return map.moveToFirst(key); } }
@Override
public boolean moveToLast(KEY_TYPE key) { synchronized(mutex) { return map.moveToLast(key); } }
@Override
public VALUE_TYPE getAndMoveToFirst(KEY_TYPE key) { synchronized(mutex) { return map.getAndMoveToFirst(key); } }
@Override
public VALUE_TYPE getAndMoveToLast(KEY_TYPE key) { synchronized(mutex) { return map.getAndMoveToLast(key); } }
@Override
public COMPARATOR KEY_GENERIC_TYPE comparator() { synchronized(mutex) { return map.comparator(); } }
@Override
@@ -791,6 +897,8 @@ public class MAPS
#if VALUE_PRIMITIVES
@Override
public VALUE_TYPE addTo(KEY_TYPE key, VALUE_TYPE value) { synchronized(mutex) { return map.addTo(key, value); } }
@Override
public VALUE_TYPE subFrom(KEY_TYPE key, VALUE_TYPE value) { synchronized(mutex) { return map.subFrom(key, value); } }
public void addToAll(MAP KEY_VALUE_GENERIC_TYPE m) { synchronized(mutex) { map.addToAll(m); } }
#endif
@Override
@@ -7,6 +7,8 @@ public class HashUtil
{
/** Minimum HashMap Capacity */
public static final int DEFAULT_MIN_CAPACITY = 16;
/** Minimum ConcurrentHashMap Concurrency */
public static final int DEFAULT_MIN_CONCURRENCY = 4;
/** Default HashMap Load Factor */
public static final float DEFAULT_LOAD_FACTOR = 0.75F;
/** HashMap Load Factor with reduced hash collisions but more memory usage */
@@ -104,6 +104,14 @@ public class SanityChecks
getPool().execute(task);
}
/**
* A Helper method to start a Async Task. This method will not await the finalization of said task
* @param task the Task to invoke
*/
public static void invokeAsyncTask(Runnable task) {
getPool().execute(task);
}
/**
* Helper method to control what ForkJoinPool is being used for any given task.
* @note this method is not thread-save. It is only there to provide control over how Library specific Threaded tasks are handled.
@@ -0,0 +1,75 @@
package speiger.src.collections.ints.base;
import java.util.EnumSet;
import org.junit.Assert;
import org.junit.Test;
import speiger.src.collections.ints.maps.interfaces.Int2IntOrderedMap;
import speiger.src.collections.tests.OrderedMapTests;
@SuppressWarnings("javadoc")
public abstract class BaseInt2IntOrderedMapTest extends BaseInt2IntMapTest
{
@Override
public abstract Int2IntOrderedMap createMap(int[] keys, int[] values);
@Override
public abstract Int2IntOrderedMap createEmptyMap();
public EnumSet<OrderedMapTests> getValidOrderedMapTests() { return EnumSet.allOf(OrderedMapTests.class); }
@Test
public void testPutMove()
{
if(!getValidOrderedMapTests().contains(OrderedMapTests.PUT_MOVE)) return;
Int2IntOrderedMap map = createMap(TEST_ARRAY, TEST_ARRAY);
Assert.assertEquals(0, map.putAndMoveToFirst(120, -1));
Assert.assertEquals(120, map.firstIntKey());
Assert.assertEquals(-1, map.firstIntValue());
Assert.assertEquals(0, map.putAndMoveToLast(121, -2));
Assert.assertEquals(121, map.lastIntKey());
Assert.assertEquals(-2, map.lastIntValue());
}
@Test
public void testMove()
{
if(!getValidOrderedMapTests().contains(OrderedMapTests.MOVE)) return;
Int2IntOrderedMap map = createMap(TEST_ARRAY, TEST_ARRAY);
Assert.assertTrue(map.moveToFirst(99));
Assert.assertFalse(map.moveToFirst(99));
Assert.assertEquals(99, map.firstIntKey());
Assert.assertTrue(map.moveToLast(0));
Assert.assertFalse(map.moveToLast(0));
Assert.assertEquals(0, map.lastIntKey());
}
@Test
public void testGetMove()
{
if(!getValidOrderedMapTests().contains(OrderedMapTests.GET_MOVE)) return;
Int2IntOrderedMap map = createMap(TEST_ARRAY, TEST_ARRAY);
Assert.assertNotEquals(99, map.firstIntValue());
Assert.assertEquals(99, map.getAndMoveToFirst(99));
Assert.assertEquals(99, map.firstIntValue());
Assert.assertNotEquals(0, map.lastIntValue());
Assert.assertEquals(0, map.getAndMoveToLast(0));
Assert.assertEquals(0, map.lastIntValue());
}
@Test
public void testFirst()
{
if(!getValidOrderedMapTests().contains(OrderedMapTests.FIRST)) return;
Int2IntOrderedMap map = createMap(TEST_ARRAY, TEST_ARRAY);
Assert.assertEquals(map.pollFirstIntKey(), 0);
}
@Test
public void testLast()
{
if(!getValidOrderedMapTests().contains(OrderedMapTests.LAST)) return;
Int2IntOrderedMap map = createMap(TEST_ARRAY, TEST_ARRAY);
Assert.assertEquals(map.pollLastIntKey(), 99);
}
}
@@ -18,45 +18,6 @@ public abstract class BaseInt2IntSortedMapTest extends BaseInt2IntMapTest
public EnumSet<SortedMapTests> getValidSortedMapTests() { return EnumSet.allOf(SortedMapTests.class); }
@Test
public void testPutMove()
{
if(!getValidSortedMapTests().contains(SortedMapTests.PUT_MOVE)) return;
Int2IntSortedMap map = createMap(TEST_ARRAY, TEST_ARRAY);
Assert.assertEquals(0, map.putAndMoveToFirst(120, -1));
Assert.assertEquals(120, map.firstIntKey());
Assert.assertEquals(-1, map.firstIntValue());
Assert.assertEquals(0, map.putAndMoveToLast(121, -2));
Assert.assertEquals(121, map.lastIntKey());
Assert.assertEquals(-2, map.lastIntValue());
}
@Test
public void testMove()
{
if(!getValidSortedMapTests().contains(SortedMapTests.MOVE)) return;
Int2IntSortedMap map = createMap(TEST_ARRAY, TEST_ARRAY);
Assert.assertTrue(map.moveToFirst(99));
Assert.assertFalse(map.moveToFirst(99));
Assert.assertEquals(99, map.firstIntKey());
Assert.assertTrue(map.moveToLast(0));
Assert.assertFalse(map.moveToLast(0));
Assert.assertEquals(0, map.lastIntKey());
}
@Test
public void testGetMove()
{
if(!getValidSortedMapTests().contains(SortedMapTests.GET_MOVE)) return;
Int2IntSortedMap map = createMap(TEST_ARRAY, TEST_ARRAY);
Assert.assertNotEquals(99, map.firstIntValue());
Assert.assertEquals(99, map.getAndMoveToFirst(99));
Assert.assertEquals(99, map.firstIntValue());
Assert.assertNotEquals(0, map.lastIntValue());
Assert.assertEquals(0, map.getAndMoveToLast(0));
Assert.assertEquals(0, map.lastIntValue());
}
@Test
public void testFirst()
{
@@ -123,8 +123,8 @@ public abstract class BaseIntIterableTest
@Test
public void testStreamMap() {
if(getValidIterableTests().contains(IterableTest.STREAM_MAP)) {
Integer[] expected = IntStream.of(TEST_ARRAY).mapToObj(Integer::new).toArray(Integer[]::new);
Integer[] actual = ObjectIterators.pour(create(TEST_ARRAY).map(Integer::new).iterator()).toArray(Integer[]::new);
Integer[] expected = IntStream.of(TEST_ARRAY).mapToObj(Integer::valueOf).toArray(Integer[]::new);
Integer[] actual = ObjectIterators.pour(create(TEST_ARRAY).map(Integer::valueOf).iterator()).toArray(Integer[]::new);
ObjectArrays.stableSort(actual);
Assert.assertArrayEquals(expected, actual);
}
@@ -0,0 +1,63 @@
package speiger.src.collections.ints.base;
import java.util.EnumSet;
import org.junit.Assert;
import org.junit.Test;
import speiger.src.collections.ints.sets.IntOrderedSet;
import speiger.src.collections.tests.OrderedSetTest;
@SuppressWarnings("javadoc")
public abstract class BaseIntOrderedSetTest extends BaseIntCollectionTest
{
@Override
protected abstract IntOrderedSet create(int[] data);
protected EnumSet<OrderedSetTest> getValidOrderedSetTests() { return EnumSet.allOf(OrderedSetTest.class); }
@Test
public void addMoveTest() {
if(getValidOrderedSetTests().contains(OrderedSetTest.ADD_MOVE)) {
IntOrderedSet set = create(TEST_ARRAY);
Assert.assertTrue(set.addAndMoveToFirst(1050));
Assert.assertFalse(set.addAndMoveToLast(5));
}
}
@Test
public void moveTest() {
if(getValidOrderedSetTests().contains(OrderedSetTest.MOVE)) {
IntOrderedSet set = create(TEST_ARRAY);
Assert.assertTrue(set.moveToFirst(5));
Assert.assertFalse(set.moveToFirst(5));
Assert.assertTrue(set.moveToLast(5));
Assert.assertFalse(set.moveToLast(5));
}
}
@Test
public void peekTest() {
if(getValidOrderedSetTests().contains(OrderedSetTest.PEEK)) {
IntOrderedSet set = create(TEST_ARRAY);
Assert.assertEquals(set.firstInt(), 0);
Assert.assertEquals(set.lastInt(), 99);
}
}
@Test
public void pollTest() {
if(getValidOrderedSetTests().contains(OrderedSetTest.POLL)) {
IntOrderedSet set = create(TEST_ARRAY);
for(int i = 0;i<100;i++)
{
Assert.assertEquals(i, set.pollFirstInt());
}
set = create(TEST_ARRAY);
for(int i = 99;i>=0;i--)
{
Assert.assertEquals(i, set.pollLastInt());
}
}
}
}
@@ -82,6 +82,24 @@ public abstract class BaseIntPriorityQueueTest extends BaseIntIterableTest
}
}
@Test
public void testUnorderedPeek() {
EnumSet<PriorityQueueTest> valid = getValidPriorityQueueTests();
if(valid.contains(PriorityQueueTest.IN_OUT) && valid.contains(PriorityQueueTest.PEEK) && !isUnsortedRead()) {
IntPriorityQueue queue = create(EMPTY_ARRAY);
for(int i = 0;i<100;i++) {
queue.enqueue(i);
}
for(int i = 0;i<25;i++) {
queue.dequeue();
queue.enqueue(i);
}
for(int i = 0;i<100;i++) {
Assert.assertEquals((i+25) % 100, queue.peek(i));
}
}
}
@Test
@SuppressWarnings("deprecation")
public void testToArray() {
@@ -16,26 +16,6 @@ public abstract class BaseIntSortedSetTest extends BaseIntCollectionTest
protected EnumSet<SortedSetTest> getValidSortedSetTests() { return EnumSet.allOf(SortedSetTest.class); }
@Test
public void addMoveTest() {
if(getValidSortedSetTests().contains(SortedSetTest.ADD_MOVE)) {
IntSortedSet set = create(TEST_ARRAY);
Assert.assertTrue(set.addAndMoveToFirst(1050));
Assert.assertFalse(set.addAndMoveToLast(5));
}
}
@Test
public void moveTest() {
if(getValidSortedSetTests().contains(SortedSetTest.MOVE)) {
IntSortedSet set = create(TEST_ARRAY);
Assert.assertTrue(set.moveToFirst(5));
Assert.assertFalse(set.moveToFirst(5));
Assert.assertTrue(set.moveToLast(5));
Assert.assertFalse(set.moveToLast(5));
}
}
@Test
public void peekTest() {
if(getValidSortedSetTests().contains(SortedSetTest.PEEK)) {
@@ -1,18 +1,12 @@
package speiger.src.collections.ints.maps;
import java.util.EnumSet;
import speiger.src.collections.ints.base.BaseInt2IntNavigableMapTest;
import speiger.src.collections.ints.maps.impl.tree.Int2IntAVLTreeMap;
import speiger.src.collections.ints.maps.interfaces.Int2IntNavigableMap;
import speiger.src.collections.tests.SortedMapTests;
@SuppressWarnings("javadoc")
public class Int2IntAVLTreeMapTest extends BaseInt2IntNavigableMapTest
{
@Override
public EnumSet<SortedMapTests> getValidSortedMapTests() { return EnumSet.complementOf(EnumSet.of(SortedMapTests.GET_MOVE, SortedMapTests.MOVE, SortedMapTests.PUT_MOVE)); }
@Override
public Int2IntNavigableMap createMap(int[] keys, int[] values)
{
@@ -1,20 +1,20 @@
package speiger.src.collections.ints.maps;
import speiger.src.collections.ints.base.BaseInt2IntSortedMapTest;
import speiger.src.collections.ints.base.BaseInt2IntOrderedMapTest;
import speiger.src.collections.ints.maps.impl.misc.Int2IntArrayMap;
import speiger.src.collections.ints.maps.interfaces.Int2IntSortedMap;
import speiger.src.collections.ints.maps.interfaces.Int2IntOrderedMap;
@SuppressWarnings("javadoc")
public class Int2IntArrayMapTest extends BaseInt2IntSortedMapTest
public class Int2IntArrayMapTest extends BaseInt2IntOrderedMapTest
{
@Override
public Int2IntSortedMap createMap(int[] keys, int[] values)
public Int2IntOrderedMap createMap(int[] keys, int[] values)
{
return new Int2IntArrayMap(keys, values);
}
@Override
public Int2IntSortedMap createEmptyMap()
public Int2IntOrderedMap createEmptyMap()
{
return new Int2IntArrayMap();
}
@@ -1,26 +1,20 @@
package speiger.src.collections.ints.maps;
import java.util.EnumSet;
import speiger.src.collections.ints.base.BaseInt2IntSortedMapTest;
import speiger.src.collections.ints.base.BaseInt2IntOrderedMapTest;
import speiger.src.collections.ints.maps.impl.customHash.Int2IntLinkedOpenCustomHashMap;
import speiger.src.collections.ints.maps.interfaces.Int2IntSortedMap;
import speiger.src.collections.tests.SortedMapTests;
import speiger.src.collections.ints.maps.interfaces.Int2IntOrderedMap;
@SuppressWarnings("javadoc")
public class Int2IntLinkedOpenCustomHashMapTest extends BaseInt2IntSortedMapTest
public class Int2IntLinkedOpenCustomHashMapTest extends BaseInt2IntOrderedMapTest
{
@Override
public EnumSet<SortedMapTests> getValidSortedMapTests() { return EnumSet.complementOf(EnumSet.of(SortedMapTests.SUB_MAP, SortedMapTests.TAIL_MAP, SortedMapTests.HEAD_MAP)); }
@Override
public Int2IntSortedMap createMap(int[] keys, int[] values)
public Int2IntOrderedMap createMap(int[] keys, int[] values)
{
return new Int2IntLinkedOpenCustomHashMap(keys, values, STRATEGY);
}
@Override
public Int2IntSortedMap createEmptyMap()
public Int2IntOrderedMap createEmptyMap()
{
return new Int2IntLinkedOpenCustomHashMap(STRATEGY);
}
@@ -1,26 +1,20 @@
package speiger.src.collections.ints.maps;
import java.util.EnumSet;
import speiger.src.collections.ints.base.BaseInt2IntSortedMapTest;
import speiger.src.collections.ints.base.BaseInt2IntOrderedMapTest;
import speiger.src.collections.ints.maps.impl.hash.Int2IntLinkedOpenHashMap;
import speiger.src.collections.ints.maps.interfaces.Int2IntSortedMap;
import speiger.src.collections.tests.SortedMapTests;
import speiger.src.collections.ints.maps.interfaces.Int2IntOrderedMap;
@SuppressWarnings("javadoc")
public class Int2IntLinkedOpenHashMapTest extends BaseInt2IntSortedMapTest
public class Int2IntLinkedOpenHashMapTest extends BaseInt2IntOrderedMapTest
{
@Override
public EnumSet<SortedMapTests> getValidSortedMapTests() { return EnumSet.complementOf(EnumSet.of(SortedMapTests.SUB_MAP, SortedMapTests.TAIL_MAP, SortedMapTests.HEAD_MAP)); }
@Override
public Int2IntSortedMap createMap(int[] keys, int[] values)
public Int2IntOrderedMap createMap(int[] keys, int[] values)
{
return new Int2IntLinkedOpenHashMap(keys, values);
}
@Override
public Int2IntSortedMap createEmptyMap()
public Int2IntOrderedMap createEmptyMap()
{
return new Int2IntLinkedOpenHashMap();
}
@@ -1,18 +1,12 @@
package speiger.src.collections.ints.maps;
import java.util.EnumSet;
import speiger.src.collections.ints.base.BaseInt2IntNavigableMapTest;
import speiger.src.collections.ints.maps.impl.tree.Int2IntRBTreeMap;
import speiger.src.collections.ints.maps.interfaces.Int2IntNavigableMap;
import speiger.src.collections.tests.SortedMapTests;
@SuppressWarnings("javadoc")
public class Int2IntRBTreeMapTest extends BaseInt2IntNavigableMapTest
{
@Override
public EnumSet<SortedMapTests> getValidSortedMapTests() { return EnumSet.complementOf(EnumSet.of(SortedMapTests.GET_MOVE, SortedMapTests.MOVE, SortedMapTests.PUT_MOVE)); }
@Override
public Int2IntNavigableMap createMap(int[] keys, int[] values)
{
@@ -1,9 +1,6 @@
package speiger.src.collections.ints.sets;
import java.util.EnumSet;
import speiger.src.collections.ints.base.BaseIntNavigableSetTest;
import speiger.src.collections.tests.SortedSetTest;
@SuppressWarnings("javadoc")
public class IntAVLTreeSetTests extends BaseIntNavigableSetTest
@@ -12,7 +9,4 @@ public class IntAVLTreeSetTests extends BaseIntNavigableSetTest
protected IntNavigableSet create(int[] data) {
return new IntAVLTreeSet(data);
}
@Override
protected EnumSet<SortedSetTest> getValidSortedSetTests() { return EnumSet.of(SortedSetTest.PEEK, SortedSetTest.POLL, SortedSetTest.HEAD_SET, SortedSetTest.SUB_SET, SortedSetTest.TAIL_SET);}
}
@@ -1,10 +1,10 @@
package speiger.src.collections.ints.sets;
import speiger.src.collections.ints.base.BaseIntSortedSetTest;
import speiger.src.collections.ints.base.BaseIntOrderedSetTest;
@SuppressWarnings("javadoc")
public class IntArraySetTests extends BaseIntSortedSetTest
public class IntArraySetTests extends BaseIntOrderedSetTest
{
@Override
protected IntSortedSet create(int[] data) { return new IntArraySet(data.clone()); }
protected IntOrderedSet create(int[] data) { return new IntArraySet(data.clone()); }
}
@@ -3,21 +3,14 @@ package speiger.src.collections.ints.sets;
import java.util.EnumSet;
import speiger.src.collections.ints.base.BaseIntCollectionTest;
import speiger.src.collections.ints.base.BaseIntSortedSetTest;
import speiger.src.collections.ints.base.BaseIntOrderedSetTest;
import speiger.src.collections.ints.collections.IntCollection;
import speiger.src.collections.ints.utils.IntStrategy;
import speiger.src.collections.tests.CollectionTest;
import speiger.src.collections.tests.SortedSetTest;
@SuppressWarnings("javadoc")
public class IntHashSetTests
{
public static abstract class BaseIntOpenHashSetTests extends BaseIntSortedSetTest
{
@Override
protected EnumSet<SortedSetTest> getValidSortedSetTests() { return EnumSet.of(SortedSetTest.ADD_MOVE, SortedSetTest.MOVE, SortedSetTest.PEEK, SortedSetTest.POLL); }
}
public static class IntOpenHashSetTests extends BaseIntCollectionTest
{
@Override
@@ -32,10 +25,10 @@ public class IntHashSetTests
}
}
public static class IntLinkedOpenHashSetTests extends BaseIntOpenHashSetTests
public static class IntLinkedOpenHashSetTests extends BaseIntOrderedSetTest
{
@Override
protected IntSortedSet create(int[] data) { return new IntLinkedOpenHashSet(data); }
protected IntOrderedSet create(int[] data) { return new IntLinkedOpenHashSet(data); }
}
public static class IntOpenCustomHashSetTests extends BaseIntCollectionTest
@@ -52,10 +45,10 @@ public class IntHashSetTests
}
}
public static class IntLinkedOpenCustomHashSetTests extends BaseIntOpenHashSetTests
public static class IntLinkedOpenCustomHashSetTests extends BaseIntOrderedSetTest
{
@Override
protected IntSortedSet create(int[] data) { return new IntLinkedOpenCustomHashSet(data, new DefaultStrategy()); }
protected IntOrderedSet create(int[] data) { return new IntLinkedOpenCustomHashSet(data, new DefaultStrategy()); }
}
public static class DefaultStrategy implements IntStrategy
@@ -1,9 +1,6 @@
package speiger.src.collections.ints.sets;
import java.util.EnumSet;
import speiger.src.collections.ints.base.BaseIntNavigableSetTest;
import speiger.src.collections.tests.SortedSetTest;
@SuppressWarnings("javadoc")
public class IntRBTreeSetTests extends BaseIntNavigableSetTest
@@ -13,7 +10,4 @@ public class IntRBTreeSetTests extends BaseIntNavigableSetTest
protected IntNavigableSet create(int[] data) {
return new IntRBTreeSet(data);
}
@Override
protected EnumSet<SortedSetTest> getValidSortedSetTests() { return EnumSet.of(SortedSetTest.PEEK, SortedSetTest.POLL, SortedSetTest.HEAD_SET, SortedSetTest.SUB_SET, SortedSetTest.TAIL_SET);}
}
@@ -1,5 +1,8 @@
package speiger.src.collections.objects.list;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.function.Function;
@@ -8,10 +11,18 @@ import com.google.common.collect.testing.TestStringListGenerator;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.ListFeature;
import com.google.common.collect.testing.testers.ListListIteratorTester;
import com.google.common.collect.testing.testers.ListSubListTester;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import speiger.src.collections.ints.lists.CopyOnWriteIntArrayList;
import speiger.src.collections.ints.lists.ImmutableIntList;
import speiger.src.collections.ints.lists.IntArrayList;
import speiger.src.collections.ints.lists.IntLinkedList;
import speiger.src.collections.ints.lists.IntList;
import speiger.src.collections.objects.lists.CopyOnWriteObjectArrayList;
import speiger.src.collections.objects.lists.ImmutableObjectList;
import speiger.src.collections.objects.lists.ObjectArrayList;
import speiger.src.collections.objects.lists.ObjectLinkedList;
@@ -24,23 +35,49 @@ public class ObjectListTests extends TestCase
TestSuite suite = new TestSuite("Lists");
suite.addTest(suite("ArrayList", T -> new ObjectArrayList<>(T)));
suite.addTest(suite("LinkedList", T -> new ObjectLinkedList<>(T)));
suite.addTest(copyOnWriteSuite("CopyOnWriteArrayList", T -> new CopyOnWriteObjectArrayList<>(T)));
suite.addTest(immutableSuite("ImmutableList", T -> new ImmutableObjectList<>(T)));
suite.addTest(intSuite("IntArrayList", IntArrayList::new));
suite.addTest(intSuite("IntLinkedList", IntLinkedList::new));
suite.addTest(intCopyOnWriteSuite("CopyOnWriteArrayList", CopyOnWriteIntArrayList::new));
suite.addTest(intImmutableSuite("IntImmutableList", ImmutableIntList::new));
return suite;
}
public static Test suite(String name, Function<String[], List<String>> factory)
{
public static Test intSuite(String name, Function<int[], IntList> factory) {
return ListTestSuiteBuilder.using(new TestIntListGenerator(factory)).named(name).withFeatures(ListFeature.GENERAL_PURPOSE, CollectionSize.ANY).createTestSuite();
}
public static Test intCopyOnWriteSuite(String name, Function<int[], IntList> factory) {
return ListTestSuiteBuilder.using(new TestIntListGenerator(factory)).named(name).suppressing(suppressForCopyOnWriteArrayList()).withFeatures(ListFeature.SUPPORTS_SET, ListFeature.SUPPORTS_ADD_WITH_INDEX, ListFeature.SUPPORTS_REMOVE_WITH_INDEX, CollectionFeature.SUPPORTS_ADD, CollectionFeature.SUPPORTS_REMOVE, CollectionSize.ANY).createTestSuite();
}
public static Test intImmutableSuite(String name, Function<int[], IntList> factory) {
return ListTestSuiteBuilder.using(new TestIntListGenerator(factory)).named(name).withFeatures(CollectionSize.ANY).createTestSuite();
}
public static Test suite(String name, Function<String[], List<String>> factory) {
return ListTestSuiteBuilder.using(new TestStringListGenerator() {
@Override
protected List<String> create(String[] elements) { return factory.apply(elements); }
}).named(name).withFeatures(ListFeature.GENERAL_PURPOSE, CollectionFeature.ALLOWS_NULL_VALUES, CollectionSize.ANY).createTestSuite();
}
public static Test immutableSuite(String name, Function<String[], List<String>> factory)
{
public static Test copyOnWriteSuite(String name, Function<String[], List<String>> factory) {
return ListTestSuiteBuilder.using(new TestStringListGenerator() {
@Override
protected List<String> create(String[] elements) { return factory.apply(elements); }
}).named(name).suppressing(suppressForCopyOnWriteArrayList()).withFeatures(ListFeature.SUPPORTS_SET, ListFeature.SUPPORTS_ADD_WITH_INDEX, ListFeature.SUPPORTS_REMOVE_WITH_INDEX, CollectionFeature.SUPPORTS_ADD, CollectionFeature.SUPPORTS_REMOVE, CollectionFeature.ALLOWS_NULL_VALUES, CollectionSize.ANY).createTestSuite();
}
public static Test immutableSuite(String name, Function<String[], List<String>> factory) {
return ListTestSuiteBuilder.using(new TestStringListGenerator() {
@Override
protected List<String> create(String[] elements) { return factory.apply(elements); }
}).named(name).withFeatures(CollectionFeature.ALLOWS_NULL_VALUES, CollectionSize.ANY).createTestSuite();
}
public static Collection<Method> suppressForCopyOnWriteArrayList() {
return Arrays.asList(ListSubListTester.getSubListSubListRemoveAffectsOriginalLargeListMethod(), ListListIteratorTester.getListIteratorFullyModifiableMethod());
}
}
@@ -0,0 +1,50 @@
package speiger.src.collections.objects.list;
import java.util.List;
import java.util.function.Function;
import com.google.common.collect.testing.SampleElements;
import com.google.common.collect.testing.SampleElements.Ints;
import com.google.common.collect.testing.TestListGenerator;
import speiger.src.collections.ints.lists.IntList;
@SuppressWarnings("javadoc")
public class TestIntListGenerator implements TestListGenerator<Integer>
{
Function<int[], IntList> function;
public TestIntListGenerator(Function<int[], IntList> function)
{
this.function = function;
}
@Override
public SampleElements<Integer> samples()
{
return new Ints();
}
@Override
public List<Integer> create(Object... elements)
{
int[] array = new int[elements.length];
int i = 0;
for(Object e : elements)
{
array[i++] = ((Integer)e).intValue();
}
return function.apply(array);
}
@Override
public Integer[] createArray(int length)
{
return new Integer[length];
}
@Override
public List<Integer> order(List<Integer> insertionOrder)
{
return insertionOrder;
}
}
@@ -2,14 +2,17 @@ package speiger.src.collections.objects.map;
import java.util.Comparator;
import java.util.Map;
import java.util.NavigableMap;
import java.util.Objects;
import java.util.function.BiFunction;
import java.util.function.Supplier;
import com.google.common.collect.testing.AnEnum;
import com.google.common.collect.testing.MapTestSuiteBuilder;
import com.google.common.collect.testing.NavigableMapTestSuiteBuilder;
import com.google.common.collect.testing.TestEnumMapGenerator;
import com.google.common.collect.testing.TestStringMapGenerator;
import com.google.common.collect.testing.TestStringSortedMapGenerator;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;
@@ -17,6 +20,7 @@ import com.google.common.collect.testing.features.MapFeature;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import speiger.src.collections.objects.maps.impl.concurrent.Object2ObjectConcurrentOpenHashMap;
import speiger.src.collections.objects.maps.impl.customHash.Object2ObjectLinkedOpenCustomHashMap;
import speiger.src.collections.objects.maps.impl.customHash.Object2ObjectOpenCustomHashMap;
import speiger.src.collections.objects.maps.impl.hash.Object2ObjectLinkedOpenHashMap;
@@ -39,10 +43,11 @@ public class ObjectMapTests extends TestCase
suite.addTest(suite("LinkedHashMap", Object2ObjectLinkedOpenHashMap::new, true));
suite.addTest(suite("CustomHashMap", () -> new Object2ObjectOpenCustomHashMap<>(Strategy.INSTANCE), true));
suite.addTest(suite("LinkedCustomHashMap", () -> new Object2ObjectLinkedOpenCustomHashMap<>(Strategy.INSTANCE), true));
suite.addTest(suite("RBTreeMap_NonNull", Object2ObjectRBTreeMap::new, false));
suite.addTest(suite("AVLTreeMap_NonNull", Object2ObjectAVLTreeMap::new, false));
suite.addTest(suite("RBTreeMap_Null", () -> new Object2ObjectRBTreeMap<String, String>(Comparator.nullsFirst(Comparator.naturalOrder())), true));
suite.addTest(suite("AVLTreeMap_Null", () -> new Object2ObjectAVLTreeMap<String, String>(Comparator.nullsFirst(Comparator.naturalOrder())), true));
suite.addTest(suite("ConcurrentHashMap", Object2ObjectConcurrentOpenHashMap::new, true));
suite.addTest(navigableSuite("RBTreeMap_NonNull", Object2ObjectRBTreeMap::new, false));
suite.addTest(navigableSuite("AVLTreeMap_NonNull", Object2ObjectAVLTreeMap::new, false));
suite.addTest(navigableSuite("RBTreeMap_Null", () -> new Object2ObjectRBTreeMap<>(new NullFriendlyComparator()), true));
suite.addTest(navigableSuite("AVLTreeMap_Null", () -> new Object2ObjectAVLTreeMap<>(new NullFriendlyComparator()), true));
suite.addTest(immutableSuit("ImmutableMap", ImmutableObject2ObjectOpenHashMap::new));
suite.addTest(suite("ArrayMap", Object2ObjectArrayMap::new, true));
suite.addTest(enumSuite("EnumMap", () -> new Enum2ObjectMap<>(AnEnum.class)));
@@ -66,6 +71,22 @@ public class ObjectMapTests extends TestCase
return builder.createTestSuite();
}
public static Test navigableSuite(String name, Supplier<NavigableMap<String, String>> factory, boolean allowNull)
{
MapTestSuiteBuilder<String, String> builder = NavigableMapTestSuiteBuilder.using(new TestStringSortedMapGenerator() {
@Override
protected NavigableMap<String, String> create(Map.Entry<String, String>[] entries) {
NavigableMap<String, String> map = factory.get();
for(Map.Entry<String, String> entry : entries) {
map.put(entry.getKey(), entry.getValue());
}
return map;
}
}).named(name).withFeatures(CollectionSize.ANY, MapFeature.GENERAL_PURPOSE, MapFeature.ALLOWS_NULL_VALUES, CollectionFeature.SUPPORTS_ITERATOR_REMOVE);
if(allowNull) builder.withFeatures(MapFeature.ALLOWS_NULL_KEYS, MapFeature.ALLOWS_ANY_NULL_QUERIES);
return builder.createTestSuite();
}
public static Test immutableSuit(String name, BiFunction<String[], String[], Map<String, String>> factory) {
MapTestSuiteBuilder<String, String> builder = MapTestSuiteBuilder.using(new TestStringMapGenerator() {
@Override
@@ -97,6 +118,14 @@ public class ObjectMapTests extends TestCase
return builder.createTestSuite();
}
private static final class NullFriendlyComparator implements Comparator<String>
{
@Override
public int compare(String left, String right) {
return String.valueOf(left).compareTo(String.valueOf(right));
}
}
private static class Strategy implements ObjectStrategy<String>
{
static final Strategy INSTANCE = new Strategy();
@@ -1,12 +1,19 @@
package speiger.src.collections.objects.set;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.NavigableSet;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Supplier;
import com.google.common.collect.testing.NavigableSetTestSuiteBuilder;
import com.google.common.collect.testing.SetTestSuiteBuilder;
import com.google.common.collect.testing.TestIntegerSetGenerator;
import com.google.common.collect.testing.TestStringSetGenerator;
import com.google.common.collect.testing.TestStringSortedSetGenerator;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.SetFeature;
@@ -14,6 +21,17 @@ import com.google.common.collect.testing.features.SetFeature;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import speiger.src.collections.ints.sets.ImmutableIntOpenHashSet;
import speiger.src.collections.ints.sets.IntAVLTreeSet;
import speiger.src.collections.ints.sets.IntArraySet;
import speiger.src.collections.ints.sets.IntLinkedOpenCustomHashSet;
import speiger.src.collections.ints.sets.IntLinkedOpenHashSet;
import speiger.src.collections.ints.sets.IntNavigableSet;
import speiger.src.collections.ints.sets.IntOpenCustomHashSet;
import speiger.src.collections.ints.sets.IntOpenHashSet;
import speiger.src.collections.ints.sets.IntRBTreeSet;
import speiger.src.collections.ints.sets.IntSet;
import speiger.src.collections.ints.utils.IntStrategy;
import speiger.src.collections.objects.sets.ImmutableObjectOpenHashSet;
import speiger.src.collections.objects.sets.ObjectAVLTreeSet;
import speiger.src.collections.objects.sets.ObjectArraySet;
@@ -27,24 +45,63 @@ import speiger.src.collections.objects.utils.ObjectStrategy;
@SuppressWarnings("javadoc")
public class ObjectSetTests extends TestCase
{
@SuppressWarnings("deprecation")
public static Test suite()
{
TestSuite suite = new TestSuite("Sets");
suite.addTest(intSuite("IntHashSet", IntOpenHashSet::new));
suite.addTest(intSuite("IntCustomHashSet", () -> new IntOpenCustomHashSet(IntegerStrategy.INSTANCE)));
suite.addTest(intSuite("IntLinkedHashSet", IntLinkedOpenHashSet::new));
suite.addTest(intSuite("IntLinkedCustomHashSet", () -> new IntLinkedOpenCustomHashSet(IntegerStrategy.INSTANCE)));
suite.addTest(intSuite("IntArraySet", IntArraySet::new));
suite.addTest(intImmutableSuite("ImmutableHashSet", ImmutableIntOpenHashSet::new));
suite.addTest(intNavigableSuite("IntRBTreeSet", IntRBTreeSet::new));
suite.addTest(intNavigableSuite("IntAVLTreeSet", IntAVLTreeSet::new));
suite.addTest(suite("HashSet", ObjectOpenHashSet::new, true));
suite.addTest(suite("LinkedHashSet", ObjectLinkedOpenHashSet::new, true));
suite.addTest(suite("CustomHashSet", T -> new ObjectOpenCustomHashSet<>(T, Strategy.INSTANCE), true));
suite.addTest(suite("LinkedCustomHashSet", T -> new ObjectLinkedOpenCustomHashSet<>(T, Strategy.INSTANCE), true));
suite.addTest(immutableSuite("ImmutableHashSet", ImmutableObjectOpenHashSet::new));
suite.addTest(suite("ArraySet", ObjectArraySet::new, true));
suite.addTest(suite("RBTreeSet_NonNull", ObjectRBTreeSet::new, false));
suite.addTest(suite("AVLTreeSet_NonNull", ObjectAVLTreeSet::new, false));
suite.addTest(suite("RBTreeSet_Null", T -> new ObjectRBTreeSet<>(T, Comparator.nullsFirst(Comparator.naturalOrder())), true));
suite.addTest(suite("AVLTreeSet_Null", T -> new ObjectAVLTreeSet<>(T, Comparator.nullsFirst(Comparator.naturalOrder())), true));
suite.addTest(navigableSuite("RBTreeSet_NonNull", ObjectRBTreeSet::new, false));
suite.addTest(navigableSuite("AVLTreeSet_NonNull", ObjectAVLTreeSet::new, false));
suite.addTest(navigableSuite("RBTreeSet_Null", T -> new ObjectRBTreeSet<>(T, Comparator.nullsFirst(Comparator.naturalOrder())), true));
suite.addTest(navigableSuite("AVLTreeSet_Null", T -> new ObjectAVLTreeSet<>(T, Comparator.nullsFirst(Comparator.naturalOrder())), true));
return suite;
}
public static Test suite(String name, Function<String[], Set<String>> factory, boolean allowNull)
{
public static Test intSuite(String name, Supplier<IntSet> factory) {
SetTestSuiteBuilder<Integer> generator = SetTestSuiteBuilder.using(new TestIntegerSetGenerator() {
@Override
protected Set<Integer> create(Integer[] elements) {
IntSet set = factory.get();
set.addAll(Arrays.asList(elements));
return set;
}
}).named(name).withFeatures(CollectionSize.ANY, SetFeature.GENERAL_PURPOSE);
return generator.createTestSuite();
}
public static Test intNavigableSuite(String name, Supplier<IntNavigableSet> factory) {
SetTestSuiteBuilder<Integer> generator = NavigableSetTestSuiteBuilder.using(new TestIntegerNavigableSetGenerator() {
@Override
protected NavigableSet<Integer> create(Integer[] elements) {
IntNavigableSet set = factory.get();
set.addAll(Arrays.asList(elements));
return set;
}
}).named(name).withFeatures(CollectionSize.ANY, SetFeature.GENERAL_PURPOSE, CollectionFeature.SUBSET_VIEW);
return generator.createTestSuite();
}
public static Test intImmutableSuite(String name, Function<List<Integer>, IntSet> factory) {
return SetTestSuiteBuilder.using(new TestIntegerSetGenerator() {
@Override
protected Set<Integer> create(Integer[] elements) { return factory.apply(Arrays.asList(elements)); }
}).named(name).withFeatures(CollectionSize.ANY, CollectionFeature.ALLOWS_NULL_QUERIES).createTestSuite();
}
public static Test suite(String name, Function<String[], Set<String>> factory, boolean allowNull) {
SetTestSuiteBuilder<String> generator = SetTestSuiteBuilder.using(new TestStringSetGenerator() {
@Override
protected Set<String> create(String[] elements) { return factory.apply(elements); }
@@ -53,17 +110,23 @@ public class ObjectSetTests extends TestCase
return generator.createTestSuite();
}
public static Test navigableSuite(String name, Function<String[], NavigableSet<String>> factory, boolean allowNull) {
SetTestSuiteBuilder<String> generator = NavigableSetTestSuiteBuilder.using(new TestStringSortedSetGenerator() {
@Override
protected NavigableSet<String> create(String[] elements) { return factory.apply(elements); }
}).named(name).withFeatures(CollectionSize.ANY, SetFeature.GENERAL_PURPOSE);
if(allowNull) generator.withFeatures(CollectionFeature.ALLOWS_NULL_VALUES);
return generator.createTestSuite();
}
public static Test immutableSuite(String name, Function<String[], Set<String>> factory)
{
public static Test immutableSuite(String name, Function<String[], Set<String>> factory) {
return SetTestSuiteBuilder.using(new TestStringSetGenerator() {
@Override
protected Set<String> create(String[] elements) { return factory.apply(elements); }
}).named(name).withFeatures(CollectionSize.ANY, CollectionFeature.ALLOWS_NULL_VALUES).createTestSuite();
}
private static class Strategy implements ObjectStrategy<String>
{
private static class Strategy implements ObjectStrategy<String> {
static final Strategy INSTANCE = new Strategy();
@Override
@@ -75,6 +138,20 @@ public class ObjectSetTests extends TestCase
public boolean equals(String key, String value) {
return Objects.equals(key, value);
}
}
private static class IntegerStrategy implements IntStrategy {
static final IntegerStrategy INSTANCE = new IntegerStrategy();
@Override
public int hashCode(int o) {
return Integer.hashCode(o);
}
@Override
public boolean equals(int key, int value) {
return key == value;
}
}
}
@@ -0,0 +1,32 @@
package speiger.src.collections.objects.set;
import java.util.SortedSet;
import com.google.common.collect.testing.TestIntegerSortedSetGenerator;
import com.google.common.collect.testing.TestSortedSetGenerator;
@SuppressWarnings("javadoc")
public abstract class TestIntegerNavigableSetGenerator extends TestIntegerSortedSetGenerator implements TestSortedSetGenerator<Integer>
{
@Override
protected abstract SortedSet<Integer> create(Integer[] elements);
@Override
public SortedSet<Integer> create(Object... elements) {
Integer[] array = new Integer[elements.length];
int i = 0;
for (Object e : elements) {
array[i++] = (Integer) e;
}
return create(array);
}
@Override
public Integer belowSamplesLesser() { return -2; }
@Override
public Integer belowSamplesGreater() { return -1; }
@Override
public Integer aboveSamplesLesser() { return 5; }
@Override
public Integer aboveSamplesGreater() { return 6; }
}
@@ -0,0 +1,11 @@
package speiger.src.collections.tests;
@SuppressWarnings("javadoc")
public enum OrderedMapTests
{
PUT_MOVE,
MOVE,
GET_MOVE,
FIRST,
LAST;
}
@@ -0,0 +1,10 @@
package speiger.src.collections.tests;
@SuppressWarnings("javadoc")
public enum OrderedSetTest
{
ADD_MOVE,
MOVE,
PEEK,
POLL;
}
@@ -3,9 +3,6 @@ package speiger.src.collections.tests;
@SuppressWarnings("javadoc")
public enum SortedMapTests
{
PUT_MOVE,
MOVE,
GET_MOVE,
FIRST,
LAST,
SUB_MAP,
@@ -3,8 +3,6 @@ package speiger.src.collections.tests;
@SuppressWarnings("javadoc")
public enum SortedSetTest
{
ADD_MOVE,
MOVE,
PEEK,
POLL,
SUB_SET,