29 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
28 changed files with 893 additions and 212 deletions
-2
View File
@@ -32,7 +32,5 @@ jobs:
uses: gradle/wrapper-validation-action@e6e38bacfdf1a337459f332974bb2327a31aaf4b uses: gradle/wrapper-validation-action@e6e38bacfdf1a337459f332974bb2327a31aaf4b
- name: Make gradlew executable - name: Make gradlew executable
run: chmod +x ./gradlew run: chmod +x ./gradlew
- name: Generate SourceCode with Gradle
run: ./gradlew generateGithubSource
- name: Build with Gradle - name: Build with Gradle
run: ./gradlew build run: ./gradlew build
+26
View File
@@ -1,5 +1,31 @@
# Changelog of versions # 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 ### Version 0.6.0
- Added: addOrGet for sets. - Added: addOrGet for sets.
- Added: Async API which allows to easily execute Iterables/Collections offthread without the complexity. - Added: Async API which allows to easily execute Iterables/Collections offthread without the complexity.
+35 -74
View File
@@ -1,10 +1,17 @@
![build](https://github.com/Speiger/Primitive-Collections/actions/workflows/build_validator.yml/badge.svg) ![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 # 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. ## Benchmarks
It is based on Java's Collection Library and FastUtil. 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)
But its focus is a different one.
## 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: ## Main Features:
- ArrayLists / LinkedLists / CopyOnWriteLists - ArrayLists / LinkedLists / CopyOnWriteLists
@@ -15,80 +22,30 @@ But its focus is a different one.
- ConcurrentHashMaps - ConcurrentHashMaps
- Priority Queues - Priority Queues
- Streams & Functional Queries - Streams & Functional Queries
- SplitIterators - Split/Iterators
- Iterators
- Pairs - Pairs
- Unary/Functions - Unary/Functions
- Suppliers - Suppliers
- Bi/Consumers - Bi/Consumers
- AsyncBuilders - AsyncBuilders
## Current Level of Stability
Since this is a relatively new Library, stability was not perfect and some areas are not perfect yet.
Thanks to [ben-manes](https://github.com/ben-manes) we now have Roughly 160k unit test covering Maps/Sets/Lists.
These tests cover Javas Collection API completely and ensuring a Stable implementation.
These freshly added tests allowed me to squash thousands of issues according to Googles Test Library (Guava-Tests).
These will be expanded on as time goes on.
### Benchmarks
Benchmarks can be found here: [Click Me](https://github.com/Speiger/Primitive-Collections-Benchmarks/tree/master)
## Specialized Functions
New Specialized functions that were added to increase performance or reduce allocations or Quality Of life.
To highlight things that may be wanted.
- Iterable:
- map/flatMap/arrayFlatMap: A Light weight version of Stream.map().
- findFirst: Allows to find the first element of a Predicated Iterable.
- filter: Allows to filter unwanted elements for wrapped Iterable
- matchAny/matchNone/matchAll: Allows to find elements in a collection.
- count: counts all valid elements in a collection.
- forEach: Allows to input a second element into a forEach move allowing for more flexibility for Method References
- reduce/limit/peek/distinct: Light Versions of the Stream variant, to reduce Stream usage.
- pour: a function that allows to collect all elements within the Collection
- Collection:
- addAll: addAll array version
- containsAny: Allows to test if another collection contains an of the elements of the tested collection.
- primitiveStream: Provides access to the closest Java Stream Type.
- copy: shallowCopies the collection, used instead of clone because this is better to use.
(subCollections not supported for obvious reasons)
- toArray: the ToArray function from Java9 and newer that uses a Functional interface and can use a method reference
- List:
- add/get/removeElements (From FastUtil): Allows to add/get/remove an Array into/from a list. Just with less overhead
- extractElements: Allows to remove a Range of elements from the List and get what was removed.
- Unstable Sort(From FastUtil): Uses a faster but not stable sort (Quick-Sort as example) to sort the list.
- addIfAbsent/Present: adds a element only if absent/present in the list
- swapRemove: deletes a desired element and inserts the last element in its place instead of leftshifting elements.
- SortedSet:
- addAndMoveToFirst/Last (From FastUtil but moved to Interface): Allows to add a element to the first/last position of a sorted set.
- moveToFirst/Last: Moves the desired element at the first/last position of the SortedSet.
- pollFirst/Last: Allows to poll the first/last element of the set.
- Map:
- putAll: putAll but in Array form.
- putAllIfAbsent: Puts only the elements that are absent.
- addTo (Only Primitives Values) (From FastUtil but moved to Interface): allows to add to the value of a given key. If not present it will be added. (Accumulator)
- subFrom (Only Primitive Values): allows to subtract from the value of a given key. If value reached getDefaultReturnValue() element will be removed.
- addToAll: Same as addTo but bulkVersion.
- removeOrDefault: removes a Element and if not present returns the default value instead of the present value.
- mergeAll: BulkVersion of Merge function.
- supplyIfAbsent: A Supplier based computeIfAbsent
- Sorted Map:
- addAndMoveToFirst/Last (From FastUtil but moved to Interface): Allows to add a element to the first/last position of a sorted Map.
- moveToFirst/Last: Moves the desired element at the first/last position of the Map.
- getAndMoveToFirst/Last: gets the element and moves it to the first/last position. Replicating a Optional LinkedHashMap feature.
- pollFirst/LastKey: Allows to poll the first/last element.
- first/LastValue: Allows to get the first/last value from the Map.
# Notes about Versions # Notes about Versions
Any 0.x.0 version (Minor) can be reason for massive changes including API. 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. 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 # 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 ```gradle
repositories { repositories {
maven { maven {
@@ -96,13 +53,18 @@ repositories {
} }
} }
dependencies { dependencies {
compile 'de.speiger:Primitive-Collections:0.6.0' implementation 'de.speiger:Primitive-Collections:0.6.2'
} }
``` ```
Direct:
<details>
<summary>Direct: </summary>
<p>
| Version | Jar | Sources | Java Doc | | 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.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.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.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) |
@@ -116,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.4.0 | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.4.0/Primitive-Collections-0.4.0.jar) | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.4.0/Primitive-Collections-0.4.0-sources.jar) | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.4.0/Primitive-Collections-0.4.0-javadoc.jar) |
| 0.3.6 | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.3.6/Primitive-Collections-0.3.6.jar) | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.3.6/Primitive-Collections-0.3.6-sources.jar) | [Download](https://maven.speiger.com/repository/main/de/speiger/Primitive-Collections/0.3.6/Primitive-Collections-0.3.6-javadoc.jar) | | 0.3.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 # Contributing
If you want to contribute. If you want to contribute.
This project is created using gradle and java and my Template Library only. Nothing extra. This project is created using gradle and java and my Template Library only. Nothing extra.
@@ -134,9 +99,5 @@ Please if you want to contribute follow the [Rule-Sheet](RuleSheet.md). It keeps
The SourceCode can be generated via: The SourceCode can be generated via:
/gradlew.bat generateSource /gradlew.bat generateSource
to build the jar: to generate SourceCode and build the jar:
/gradlew.bat build /gradlew.bat build
do not combine the commands because they can not be executed at the same time.
## Current Down Sides (Random order)
- Documentation is only present at the lowest level for most cases and needs a typo fixing.
+4 -1
View File
@@ -18,7 +18,7 @@ repositories {
} }
archivesBaseName = 'Primitive Collections' archivesBaseName = 'Primitive Collections'
version = '0.6.0'; version = '0.6.2';
sourceCompatibility = targetCompatibility = compileJava.sourceCompatibility = compileJava.targetCompatibility = JavaVersion.current(); sourceCompatibility = targetCompatibility = compileJava.sourceCompatibility = compileJava.targetCompatibility = JavaVersion.current();
@@ -47,6 +47,7 @@ dependencies {
builderImplementation 'de.speiger:Simple-Code-Generator:1.0.7' builderImplementation 'de.speiger:Simple-Code-Generator:1.0.7'
testImplementation 'junit:junit:4.12' testImplementation 'junit:junit:4.12'
testImplementation 'com.google.guava:guava-testlib:31.0.1-jre' testImplementation 'com.google.guava:guava-testlib:31.0.1-jre'
} }
task generateSource(type: JavaExec) { task generateSource(type: JavaExec) {
@@ -82,6 +83,8 @@ task srcJar(type: Jar) {
classifier = 'sources' classifier = 'sources'
} }
compileJava.dependsOn generateGithubSource
javadoc.failOnError = false javadoc.failOnError = false
javadoc.options.memberLevel = JavadocMemberLevel.PUBLIC javadoc.options.memberLevel = JavadocMemberLevel.PUBLIC
javadoc.options.quiet() javadoc.options.quiet()
+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
@@ -2,6 +2,5 @@ jdk:
- openjdk9 - openjdk9
install: install:
- chmod +x ./gradlew - chmod +x ./gradlew
- ./gradlew generateGithubSource
- ./gradlew build publishToMavenLocal - ./gradlew build publishToMavenLocal
@@ -230,6 +230,7 @@ public abstract class ABSTRACT_COLLECTION KEY_GENERIC_TYPE extends AbstractColle
for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) { for(ITERATOR KEY_GENERIC_TYPE iter = iterator();iter.hasNext();) {
KEY_TYPE e = iter.NEXT(); KEY_TYPE e = iter.NEXT();
if(!c.contains(e)) { if(!c.contains(e)) {
r.accept(e);
iter.remove(); iter.remove();
modified = true; modified = true;
} }
@@ -256,6 +257,7 @@ public abstract class ABSTRACT_COLLECTION KEY_GENERIC_TYPE extends AbstractColle
public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] a) { public KEY_TYPE[] TO_ARRAY(KEY_TYPE[] a) {
if(a == null || a.length < size()) a = new KEY_TYPE[size()]; if(a == null || a.length < size()) a = new KEY_TYPE[size()];
ITERATORS.unwrap(a, iterator()); ITERATORS.unwrap(a, iterator());
if (a.length > size()) a[size()] = EMPTY_KEY_VALUE;
return a; return a;
} }
#endif #endif
@@ -5,9 +5,11 @@ import java.util.function.Consumer;
#if !TYPE_OBJECT #if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.functions.CONSUMER; import speiger.src.collections.PACKAGE.functions.CONSUMER;
import speiger.src.collections.PACKAGE.functions.COMPARATOR;
import speiger.src.collections.objects.collections.ObjectIterable; import speiger.src.collections.objects.collections.ObjectIterable;
#else #else
import java.util.function.BiFunction; import java.util.function.BiFunction;
import java.util.Comparator;
#endif #endif
import speiger.src.collections.PACKAGE.functions.function.TO_OBJECT_FUNCTION; import speiger.src.collections.PACKAGE.functions.function.TO_OBJECT_FUNCTION;
@@ -156,6 +158,15 @@ public interface ITERABLE KEY_GENERIC_TYPE extends Iterable<CLASS_TYPE>
return ITERABLES.limit(this, limit); 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 * 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 * @param action the action that should be applied
@@ -315,7 +315,7 @@ public abstract class ABSTRACT_LIST KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION
public void removeElements(int from, int to) { public void removeElements(int from, int to) {
if(to-from <= 0) return; if(to-from <= 0) return;
checkSubRange(from); checkSubRange(from);
checkSubRange(to); checkAddSubRange(to);
list.removeElements(from+parentOffset, to+parentOffset); list.removeElements(from+parentOffset, to+parentOffset);
size -= to - from; size -= to - from;
} }
@@ -324,9 +324,9 @@ public abstract class ABSTRACT_LIST KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION
@Override @Override
public <K> K[] extractElements(int from, int to, Class<K> type) { public <K> K[] extractElements(int from, int to, Class<K> type) {
checkSubRange(from); checkSubRange(from);
checkSubRange(to); checkAddSubRange(to);
K[] result = list.extractElements(from+parentOffset, to+parentOffset, type); K[] result = list.extractElements(from+parentOffset, to+parentOffset, type);
size -= to - from; size -= result.length;
return result; return result;
} }
@@ -334,9 +334,9 @@ public abstract class ABSTRACT_LIST KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION
@Override @Override
public KEY_TYPE[] extractElements(int from, int to) { public KEY_TYPE[] extractElements(int from, int to) {
checkSubRange(from); checkSubRange(from);
checkSubRange(to); checkAddSubRange(to);
KEY_TYPE[] result = list.extractElements(from+parentOffset, to+parentOffset); KEY_TYPE[] result = list.extractElements(from+parentOffset, to+parentOffset);
size -= to - from; size -= result.length;
return result; return result;
} }
@@ -324,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) { public void addElements(int from, KEY_TYPE[] a, int offset, int length) {
if(length <= 0) return; if(length <= 0) return;
checkAddRange(from); checkAddRange(from);
SanityChecks.checkArrayCapacity(a.length, offset, length);
grow(size + 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; size+=length;
System.arraycopy(a, offset, data, from, length); System.arraycopy(a, offset, data, from, length);
} }
@@ -361,11 +362,11 @@ public class ARRAY_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
int length = to - from; int length = to - from;
if(length <= 0) return; if(length <= 0) return;
if(to != size) System.arraycopy(data, to, data, from, size - to); if(to != size) System.arraycopy(data, to, data, from, size - to);
size -= length;
#if TYPE_OBJECT #if TYPE_OBJECT
for(int i = 0;i<length;i++) for(int i = 0;i<length;i++)
data[i+to] = null; data[i+size] = null;
#endif #endif
size -= length;
} }
#if TYPE_OBJECT #if TYPE_OBJECT
@@ -381,13 +382,13 @@ public class ARRAY_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
checkRange(from); checkRange(from);
checkAddRange(to); checkAddRange(to);
int length = to - from; int length = to - from;
if(length <= 0) return ARRAYS.newArray(type, 0);
K[] a = ARRAYS.newArray(type, length); K[] a = ARRAYS.newArray(type, length);
if(length <= 0) return a;
System.arraycopy(data, from, a, 0, length); System.arraycopy(data, from, a, 0, length);
if(to != size) System.arraycopy(data, to, data, from, size - to); if(to != size) System.arraycopy(data, to, data, from, size - to);
for(int i = 0;i<length;i++)
data[i+to] = null;
size -= length; size -= length;
for(int i = 0;i<length;i++)
data[i+size] = null;
return a; return a;
} }
@@ -365,6 +365,7 @@ public class COPY_ON_WRITE_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENER
KEY_TYPE[] data = this.data; KEY_TYPE[] data = this.data;
int size = data.length; int size = data.length;
if(from < 0 || from > size) throw new IndexOutOfBoundsException("Index: " + from + ", Size: " + size); if(from < 0 || from > size) throw new IndexOutOfBoundsException("Index: " + from + ", Size: " + size);
SanityChecks.checkArrayCapacity(a.length, offset, length);
KEY_TYPE[] newElements; KEY_TYPE[] newElements;
if(from == size) { if(from == size) {
newElements = Arrays.copyOf(data, size+length); newElements = Arrays.copyOf(data, size+length);
@@ -1580,7 +1581,7 @@ public class COPY_ON_WRITE_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENER
lock.lock(); lock.lock();
try { try {
checkSubRange(from); checkSubRange(from);
checkSubRange(to); checkAddSubRange(to);
list.removeElements(from+parentOffset, to+parentOffset); list.removeElements(from+parentOffset, to+parentOffset);
size -= to - from; size -= to - from;
} }
@@ -1596,9 +1597,9 @@ public class COPY_ON_WRITE_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENER
lock.lock(); lock.lock();
try { try {
checkSubRange(from); checkSubRange(from);
checkSubRange(to); checkAddSubRange(to);
K[] result = list.extractElements(from+parentOffset, to+parentOffset, type); K[] result = list.extractElements(from+parentOffset, to+parentOffset, type);
size -= to - from; size -= result.length;
return result; return result;
} }
finally { finally {
@@ -1613,9 +1614,9 @@ public class COPY_ON_WRITE_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENER
lock.lock(); lock.lock();
try { try {
checkSubRange(from); checkSubRange(from);
checkSubRange(to); checkAddSubRange(to);
KEY_TYPE[] result = list.extractElements(from+parentOffset, to+parentOffset); KEY_TYPE[] result = list.extractElements(from+parentOffset, to+parentOffset);
size -= to - from; size -= result.length;
return result; return result;
} }
finally { finally {
@@ -152,10 +152,16 @@ public class LINKED_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
int length = c.size(); int length = c.size();
if(length == 0) return false; if(length == 0) return false;
checkAddRange(index); checkAddRange(index);
Entry KEY_GENERIC_TYPE next = null; Entry KEY_GENERIC_TYPE next;
Entry KEY_GENERIC_TYPE prev = null; Entry KEY_GENERIC_TYPE prev;
if(index == size) prev = last; if(index == size) {
else if(index == 0) next = first; prev = last;
next = null;
}
else if(index == 0) {
next = first;
prev = null;
}
else { else {
next = getNode(index); next = getNode(index);
prev = next.prev; prev = next.prev;
@@ -180,10 +186,16 @@ public class LINKED_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
int length = c.size(); int length = c.size();
if(length == 0) return false; if(length == 0) return false;
checkAddRange(index); checkAddRange(index);
Entry KEY_GENERIC_TYPE next = null; Entry KEY_GENERIC_TYPE next;
Entry KEY_GENERIC_TYPE prev = null; Entry KEY_GENERIC_TYPE prev;
if(index == size) prev = last; if(index == size) {
else if(index == 0) next = first; prev = last;
next = null;
}
else if(index == 0) {
next = first;
prev = null;
}
else { else {
next = getNode(index); next = getNode(index);
prev = next.prev; prev = next.prev;
@@ -210,10 +222,16 @@ public class LINKED_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
int length = c.size(); int length = c.size();
if(length == 0) return false; if(length == 0) return false;
checkAddRange(index); checkAddRange(index);
Entry KEY_GENERIC_TYPE next = null; Entry KEY_GENERIC_TYPE next;
Entry KEY_GENERIC_TYPE prev = null; Entry KEY_GENERIC_TYPE prev;
if(index == size) prev = last; if(index == size) {
else if(index == 0) next = first; prev = last;
next = null;
}
else if(index == 0) {
next = first;
prev = null;
}
else { else {
next = getNode(index); next = getNode(index);
prev = next.prev; prev = next.prev;
@@ -258,12 +276,19 @@ public class LINKED_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
@Override @Override
public void addElements(int from, KEY_TYPE[] a, int offset, int length) { public void addElements(int from, KEY_TYPE[] a, int offset, int length) {
if(length <= 0) return;
SanityChecks.checkArrayCapacity(a.length, offset, length); SanityChecks.checkArrayCapacity(a.length, offset, length);
checkAddRange(from); checkAddRange(from);
Entry KEY_GENERIC_TYPE next = null; Entry KEY_GENERIC_TYPE next;
Entry KEY_GENERIC_TYPE prev = null; Entry KEY_GENERIC_TYPE prev;
if(from == size) prev = last; if(from == size) {
else if(from == 0) next = first; prev = last;
next = null;
}
else if(from == 0) {
next = first;
prev = null;
}
else { else {
next = getNode(from); next = getNode(from);
prev = next.prev; prev = next.prev;
@@ -593,12 +618,14 @@ public class LINKED_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
first = temp; first = temp;
return result; return result;
} }
else if(before.next != last) {
Entry KEY_GENERIC_TYPE temp = last; Entry KEY_GENERIC_TYPE temp = last;
last = temp.prev; last = temp.prev;
last.next = null; last.next = null;
temp.next = before.next; temp.next = before.next;
temp.prev = before; temp.prev = before;
before.next = temp; before.next = temp;
}
return result; return result;
} }
@@ -623,12 +650,14 @@ public class LINKED_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
first = temp; first = temp;
return true; return true;
} }
else if(before.next != last) {
Entry KEY_GENERIC_TYPE temp = last; Entry KEY_GENERIC_TYPE temp = last;
last = temp.prev; last = temp.prev;
last.next = null; last.next = null;
temp.next = before.next; temp.next = before.next;
temp.prev = before; temp.prev = before;
before.next = temp; before.next = temp;
}
return true; return true;
} }
} }
@@ -671,16 +700,18 @@ public class LINKED_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
if(from < size - to) { if(from < size - to) {
Entry KEY_GENERIC_TYPE entry = getNode(from); Entry KEY_GENERIC_TYPE entry = getNode(from);
while(length > 0) { while(length > 0) {
entry = entry.next; Entry KEY_GENERIC_TYPE next = entry.next;
unlink(entry.prev); unlink(entry);
entry = next;
length--; length--;
} }
return; return;
} }
Entry KEY_GENERIC_TYPE entry = getNode(to); Entry KEY_GENERIC_TYPE entry = getNode(to);
while(length > 0) { while(length > 0) {
entry = entry.prev; Entry KEY_GENERIC_TYPE prev = entry.prev;
unlink(entry.next); unlink(entry);
entry = prev;
length--; length--;
} }
} }
@@ -691,20 +722,22 @@ public class LINKED_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
checkRange(from); checkRange(from);
checkAddRange(to); checkAddRange(to);
int length = to - from; int length = to - from;
if(length <= 0) return ARRAYS.newArray(type, 0);
K[] a = ARRAYS.newArray(type, length); K[] a = ARRAYS.newArray(type, length);
if(length <= 0) return a;
if(from < size - to) { if(from < size - to) {
Entry KEY_GENERIC_TYPE entry = getNode(from); Entry KEY_GENERIC_TYPE entry = getNode(from);
for(int i = 0;length > 0;i++, length--) { for(int i = 0;length > 0;i++, length--) {
entry = entry.next; Entry KEY_GENERIC_TYPE next = entry.next;
a[i] = (K)unlink(entry.prev); a[i] = (K)unlink(entry);
entry = next;
} }
return a; return a;
} }
Entry KEY_GENERIC_TYPE entry = getNode(to); Entry KEY_GENERIC_TYPE entry = getNode(to);
for(int i = length-1;length > 0;i--) { for(int i = length-1;length > 0;i--, length--) {
entry = entry.prev; Entry KEY_GENERIC_TYPE prev = entry.prev;
a[i] = (K)unlink(entry.next); a[i] = (K)unlink(entry);
entry = prev;
} }
return a; return a;
} }
@@ -720,15 +753,17 @@ public class LINKED_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
if(from < size - to) { if(from < size - to) {
Entry KEY_GENERIC_TYPE entry = getNode(from); Entry KEY_GENERIC_TYPE entry = getNode(from);
for(int i = 0;length > 0;i++, length--) { for(int i = 0;length > 0;i++, length--) {
entry = entry.next; Entry KEY_GENERIC_TYPE next = entry.next;
d[i] = unlink(entry.prev); d[i] = unlink(entry);
entry = next;
} }
return d; return d;
} }
Entry KEY_GENERIC_TYPE entry = getNode(to); Entry KEY_GENERIC_TYPE entry = getNode(to);
for(int i = length-1;length > 0;i--) { for(int i = length-1;length > 0;i--, length--) {
entry = entry.prev; Entry KEY_GENERIC_TYPE prev = entry.prev;
d[i] = unlink(entry.next); d[i] = unlink(entry);
entry = prev;
} }
return d; return d;
} }
@@ -1239,7 +1274,7 @@ public class LINKED_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
@Override @Override
public long estimateSize() { public long estimateSize() {
return list.size - index; return (long)list.size - (long)index;
} }
@Override @Override
@@ -1305,7 +1340,7 @@ public class LINKED_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
@Override @Override
public long estimateSize() { public long estimateSize() {
return list.size - index; return (long)list.size - (long)index;
} }
@Override @Override
@@ -408,7 +408,7 @@ public class AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_
@Override @Override
public KEY_TYPE POLL_FIRST_ENTRY_KEY() { public KEY_TYPE POLL_FIRST_ENTRY_KEY() {
if(tree == null) return EMPTY_KEY_VALUE; if(tree == null) return getDefaultMinValue();
KEY_TYPE result = first.key; KEY_TYPE result = first.key;
removeNode(first); removeNode(first);
return result; return result;
@@ -422,7 +422,7 @@ public class AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_
@Override @Override
public KEY_TYPE POLL_LAST_ENTRY_KEY() { public KEY_TYPE POLL_LAST_ENTRY_KEY() {
if(tree == null) return EMPTY_KEY_VALUE; if(tree == null) return getDefaultMaxValue();
KEY_TYPE result = last.key; KEY_TYPE result = last.key;
removeNode(last); removeNode(last);
return result; return result;
@@ -1022,6 +1022,33 @@ public class AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_
public KEY_TYPE ceiling(KEY_TYPE e) { return map.ceilingKey(e); } public KEY_TYPE ceiling(KEY_TYPE e) { return map.ceilingKey(e); }
@Override @Override
public KEY_TYPE higher(KEY_TYPE e) { return map.higherKey(e); } public KEY_TYPE higher(KEY_TYPE e) { return map.higherKey(e); }
#if !TYPE_OBJECT
@Override
public CLASS_TYPE lower(CLASS_TYPE e) {
MAP.Entry KEY_VALUE_GENERIC_TYPE node = map.lowerEntry(OBJ_TO_KEY(e));
return node != null ? node.getKey() : null;
}
@Override
public CLASS_TYPE floor(CLASS_TYPE e) {
MAP.Entry KEY_VALUE_GENERIC_TYPE node = map.floorEntry(OBJ_TO_KEY(e));
return node != null ? node.getKey() : null;
}
@Override
public CLASS_TYPE higher(CLASS_TYPE e) {
MAP.Entry KEY_VALUE_GENERIC_TYPE node = map.higherEntry(OBJ_TO_KEY(e));
return node != null ? node.getKey() : null;
}
@Override
public CLASS_TYPE ceiling(CLASS_TYPE e) {
MAP.Entry KEY_VALUE_GENERIC_TYPE node = map.ceilingEntry(OBJ_TO_KEY(e));
return node != null ? node.getKey() : null;
}
#endif
@Override @Override
public KEY_TYPE POLL_FIRST_KEY() { return map.POLL_FIRST_ENTRY_KEY(); } public KEY_TYPE POLL_FIRST_KEY() { return map.POLL_FIRST_ENTRY_KEY(); }
@Override @Override
@@ -1461,8 +1488,8 @@ public class AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_
protected abstract BI_ITERATOR KEY_GENERIC_TYPE keyIterator(KEY_TYPE element); protected abstract BI_ITERATOR KEY_GENERIC_TYPE keyIterator(KEY_TYPE element);
protected abstract VALUE_BI_ITERATOR VALUE_GENERIC_TYPE valueIterator(); protected abstract VALUE_BI_ITERATOR VALUE_GENERIC_TYPE valueIterator();
protected abstract BI_ITERATOR KEY_GENERIC_TYPE descendingKeyIterator(); protected abstract BI_ITERATOR KEY_GENERIC_TYPE descendingKeyIterator();
protected KEY_TYPE lowKeyOrNull(Node KEY_VALUE_GENERIC_TYPE entry) { return entry == null ? EMPTY_KEY_VALUE : entry.key; } protected KEY_TYPE lowKeyOrNull(Node KEY_VALUE_GENERIC_TYPE entry) { return entry == null ? getDefaultMinValue() : entry.key; }
protected KEY_TYPE highKeyOrNull(Node KEY_VALUE_GENERIC_TYPE entry) { return entry == null ? EMPTY_KEY_VALUE : entry.key; } protected KEY_TYPE highKeyOrNull(Node KEY_VALUE_GENERIC_TYPE entry) { return entry == null ? getDefaultMaxValue() : entry.key; }
protected Node KEY_VALUE_GENERIC_TYPE next(Node KEY_VALUE_GENERIC_TYPE entry) { return entry.next(); } protected Node KEY_VALUE_GENERIC_TYPE next(Node KEY_VALUE_GENERIC_TYPE entry) { return entry.next(); }
protected Node KEY_VALUE_GENERIC_TYPE previous(Node KEY_VALUE_GENERIC_TYPE entry) { return entry.previous(); } protected Node KEY_VALUE_GENERIC_TYPE previous(Node KEY_VALUE_GENERIC_TYPE entry) { return entry.previous(); }
@@ -1533,7 +1560,7 @@ public class AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_
map.removeNode(entry); map.removeNode(entry);
return result; return result;
} }
return EMPTY_KEY_VALUE; return getDefaultMinValue();
} }
@Override @Override
@@ -1544,7 +1571,7 @@ public class AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_
map.removeNode(entry); map.removeNode(entry);
return result; return result;
} }
return EMPTY_KEY_VALUE; return getDefaultMaxValue();
} }
@Override @Override
@@ -1632,7 +1659,7 @@ public class AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_
@Override @Override
public VALUE_TYPE REMOVE_VALUEOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { public VALUE_TYPE REMOVE_VALUEOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) {
return inRange(key) ? map.REMOVE_VALUE(key) : defaultValue; return inRange(key) ? map.REMOVE_VALUEOrDefault(key, defaultValue) : defaultValue;
} }
#if TYPE_OBJECT && VALUE_OBJECT #if TYPE_OBJECT && VALUE_OBJECT
@@ -1778,7 +1805,7 @@ public class AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_
KEY_TYPE key = entry.ENTRY_KEY(); KEY_TYPE key = entry.ENTRY_KEY();
if (!inRange(key)) return false; if (!inRange(key)) return false;
Node KEY_VALUE_GENERIC_TYPE node = map.findNode(key); Node KEY_VALUE_GENERIC_TYPE node = map.findNode(key);
if (node != null && VALUE_EQUALS(node.getValue(), entry.getValue())) { if (node != null && VALUE_EQUALS(node.ENTRY_VALUE(), entry.ENTRY_VALUE())) {
map.removeNode(node); map.removeNode(node);
return true; return true;
} }
@@ -2147,8 +2174,8 @@ public class AVL_TREE_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_
public SubMapEntryIterator(Node KEY_VALUE_GENERIC_TYPE first, Node KEY_VALUE_GENERIC_TYPE forwardFence, Node KEY_VALUE_GENERIC_TYPE backwardFence) public SubMapEntryIterator(Node KEY_VALUE_GENERIC_TYPE first, Node KEY_VALUE_GENERIC_TYPE forwardFence, Node KEY_VALUE_GENERIC_TYPE backwardFence)
{ {
next = first; next = first;
this.forwardFence = forwardFence == null ? null : forwardFence.key; this.forwardFence = forwardFence == null ? EMPTY_KEY_VALUE : forwardFence.key;
this.backwardFence = backwardFence == null ? null : backwardFence.key; this.backwardFence = backwardFence == null ? EMPTY_KEY_VALUE : backwardFence.key;
unboundForwardFence = forwardFence == null; unboundForwardFence = forwardFence == null;
unboundBackwardFence = backwardFence == null; unboundBackwardFence = backwardFence == null;
} }
@@ -411,7 +411,7 @@ public class RB_TREE_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_G
@Override @Override
public KEY_TYPE POLL_FIRST_ENTRY_KEY() { public KEY_TYPE POLL_FIRST_ENTRY_KEY() {
if(tree == null) return EMPTY_KEY_VALUE; if(tree == null) return getDefaultMinValue();
KEY_TYPE result = first.key; KEY_TYPE result = first.key;
removeNode(first); removeNode(first);
return result; return result;
@@ -425,7 +425,7 @@ public class RB_TREE_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_G
@Override @Override
public KEY_TYPE POLL_LAST_ENTRY_KEY() { public KEY_TYPE POLL_LAST_ENTRY_KEY() {
if(tree == null) return EMPTY_KEY_VALUE; if(tree == null) return getDefaultMaxValue();
KEY_TYPE result = last.key; KEY_TYPE result = last.key;
removeNode(last); removeNode(last);
return result; return result;
@@ -1080,6 +1080,33 @@ public class RB_TREE_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_G
public KEY_TYPE ceiling(KEY_TYPE e) { return map.ceilingKey(e); } public KEY_TYPE ceiling(KEY_TYPE e) { return map.ceilingKey(e); }
@Override @Override
public KEY_TYPE higher(KEY_TYPE e) { return map.higherKey(e); } public KEY_TYPE higher(KEY_TYPE e) { return map.higherKey(e); }
#if !TYPE_OBJECT
@Override
public CLASS_TYPE lower(CLASS_TYPE e) {
MAP.Entry KEY_VALUE_GENERIC_TYPE node = map.lowerEntry(OBJ_TO_KEY(e));
return node != null ? node.getKey() : null;
}
@Override
public CLASS_TYPE floor(CLASS_TYPE e) {
MAP.Entry KEY_VALUE_GENERIC_TYPE node = map.floorEntry(OBJ_TO_KEY(e));
return node != null ? node.getKey() : null;
}
@Override
public CLASS_TYPE higher(CLASS_TYPE e) {
MAP.Entry KEY_VALUE_GENERIC_TYPE node = map.higherEntry(OBJ_TO_KEY(e));
return node != null ? node.getKey() : null;
}
@Override
public CLASS_TYPE ceiling(CLASS_TYPE e) {
MAP.Entry KEY_VALUE_GENERIC_TYPE node = map.ceilingEntry(OBJ_TO_KEY(e));
return node != null ? node.getKey() : null;
}
#endif
@Override @Override
public KEY_TYPE POLL_FIRST_KEY() { return map.POLL_FIRST_ENTRY_KEY(); } public KEY_TYPE POLL_FIRST_KEY() { return map.POLL_FIRST_ENTRY_KEY(); }
@Override @Override
@@ -1518,8 +1545,8 @@ public class RB_TREE_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_G
protected abstract BI_ITERATOR KEY_GENERIC_TYPE keyIterator(KEY_TYPE element); protected abstract BI_ITERATOR KEY_GENERIC_TYPE keyIterator(KEY_TYPE element);
protected abstract VALUE_BI_ITERATOR VALUE_GENERIC_TYPE valueIterator(); protected abstract VALUE_BI_ITERATOR VALUE_GENERIC_TYPE valueIterator();
protected abstract BI_ITERATOR KEY_GENERIC_TYPE descendingKeyIterator(); protected abstract BI_ITERATOR KEY_GENERIC_TYPE descendingKeyIterator();
protected KEY_TYPE lowKeyOrNull(Node KEY_VALUE_GENERIC_TYPE entry) { return entry == null ? EMPTY_KEY_VALUE : entry.key; } protected KEY_TYPE lowKeyOrNull(Node KEY_VALUE_GENERIC_TYPE entry) { return entry == null ? getDefaultMinValue() : entry.key; }
protected KEY_TYPE highKeyOrNull(Node KEY_VALUE_GENERIC_TYPE entry) { return entry == null ? EMPTY_KEY_VALUE : entry.key; } protected KEY_TYPE highKeyOrNull(Node KEY_VALUE_GENERIC_TYPE entry) { return entry == null ? getDefaultMaxValue() : entry.key; }
protected Node KEY_VALUE_GENERIC_TYPE next(Node KEY_VALUE_GENERIC_TYPE entry) { return entry.next(); } protected Node KEY_VALUE_GENERIC_TYPE next(Node KEY_VALUE_GENERIC_TYPE entry) { return entry.next(); }
protected Node KEY_VALUE_GENERIC_TYPE previous(Node KEY_VALUE_GENERIC_TYPE entry) { return entry.previous(); } protected Node KEY_VALUE_GENERIC_TYPE previous(Node KEY_VALUE_GENERIC_TYPE entry) { return entry.previous(); }
@@ -1590,7 +1617,7 @@ public class RB_TREE_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_G
map.removeNode(entry); map.removeNode(entry);
return result; return result;
} }
return EMPTY_KEY_VALUE; return getDefaultMinValue();
} }
@Override @Override
@@ -1601,7 +1628,7 @@ public class RB_TREE_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_G
map.removeNode(entry); map.removeNode(entry);
return result; return result;
} }
return EMPTY_KEY_VALUE; return getDefaultMaxValue();
} }
@Override @Override
@@ -1689,7 +1716,7 @@ public class RB_TREE_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_G
@Override @Override
public VALUE_TYPE REMOVE_VALUEOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) { public VALUE_TYPE REMOVE_VALUEOrDefault(KEY_TYPE key, VALUE_TYPE defaultValue) {
return inRange(key) ? map.REMOVE_VALUE(key) : defaultValue; return inRange(key) ? map.REMOVE_VALUEOrDefault(key, defaultValue) : defaultValue;
} }
#if TYPE_OBJECT && VALUE_OBJECT #if TYPE_OBJECT && VALUE_OBJECT
@@ -1835,7 +1862,7 @@ public class RB_TREE_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_G
KEY_TYPE key = entry.ENTRY_KEY(); KEY_TYPE key = entry.ENTRY_KEY();
if (!inRange(key)) return false; if (!inRange(key)) return false;
Node KEY_VALUE_GENERIC_TYPE node = map.findNode(key); Node KEY_VALUE_GENERIC_TYPE node = map.findNode(key);
if (node != null && VALUE_EQUALS(node.getValue(), entry.getValue())) { if (node != null && VALUE_EQUALS(node.ENTRY_VALUE(), entry.ENTRY_VALUE())) {
map.removeNode(node); map.removeNode(node);
return true; return true;
} }
@@ -2204,8 +2231,8 @@ public class RB_TREE_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_G
public SubMapEntryIterator(Node KEY_VALUE_GENERIC_TYPE first, Node KEY_VALUE_GENERIC_TYPE forwardFence, Node KEY_VALUE_GENERIC_TYPE backwardFence) public SubMapEntryIterator(Node KEY_VALUE_GENERIC_TYPE first, Node KEY_VALUE_GENERIC_TYPE forwardFence, Node KEY_VALUE_GENERIC_TYPE backwardFence)
{ {
next = first; next = first;
this.forwardFence = forwardFence == null ? null : forwardFence.key; this.forwardFence = forwardFence == null ? EMPTY_KEY_VALUE : forwardFence.key;
this.backwardFence = backwardFence == null ? null : backwardFence.key; this.backwardFence = backwardFence == null ? EMPTY_KEY_VALUE : backwardFence.key;
unboundForwardFence = forwardFence == null; unboundForwardFence = forwardFence == null;
unboundBackwardFence = backwardFence == null; unboundBackwardFence = backwardFence == null;
} }
@@ -155,11 +155,11 @@ public interface SORTED_MAP KEY_VALUE_GENERIC_TYPE extends SortedMap<CLASS_TYPE,
public VALUE_TYPE LAST_ENTRY_VALUE(); public VALUE_TYPE LAST_ENTRY_VALUE();
@Override @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 @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 @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 #endif
/** /**
@@ -106,11 +106,16 @@ public class ARRAY_FIFO_QUEUE KEY_GENERIC_TYPE extends ABSTRACT_PRIORITY_QUEUE K
@Override @Override
public void clear() { public void clear() {
if(first != last) {
#if TYPE_OBJECT #if TYPE_OBJECT
Arrays.fill(array, null); Arrays.fill(array, null);
#endif #endif
first = last = 0; first = last = 0;
} }
else if(first != 0) {
first = last = 0;
}
}
@Override @Override
public void enqueue(KEY_TYPE e) { public void enqueue(KEY_TYPE e) {
@@ -152,9 +157,9 @@ public class ARRAY_FIFO_QUEUE KEY_GENERIC_TYPE extends ABSTRACT_PRIORITY_QUEUE K
@Override @Override
public KEY_TYPE peek(int index) { public KEY_TYPE peek(int index) {
if(first == last || index < 0 || index > size()) throw new NoSuchElementException(); if(first == last || index < 0 || index >= size()) throw new NoSuchElementException();
index += first; index += first;
return index > array.length ? array[index-array.length] : array[index]; return index >= array.length ? array[index-array.length] : array[index];
} }
@Override @Override
@@ -429,6 +434,7 @@ public class ARRAY_FIFO_QUEUE KEY_GENERIC_TYPE extends ABSTRACT_PRIORITY_QUEUE K
@Override @Override
public KEY_TYPE NEXT() { public KEY_TYPE NEXT() {
if(!hasNext()) throw new NoSuchElementException();
KEY_TYPE value = array[index]; KEY_TYPE value = array[index];
removeIndex(index); removeIndex(index);
index = ++index % array.length; index = ++index % array.length;
@@ -187,7 +187,7 @@ public class ARRAY_PRIORITY_QUEUE KEY_GENERIC_TYPE extends ABSTRACT_PRIORITY_QUE
@Override @Override
public void enqueue(KEY_TYPE e) { public void enqueue(KEY_TYPE e) {
if(size == array.length) array = Arrays.copyOf(array, (int)Math.max(Math.min((long)array.length + (array.length >> 1), SanityChecks.MAX_ARRAY_SIZE), size+1)); if(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){ if(firstIndex != -1){
int compare = comparator == null ? COMPAREABLE_TO_KEY(e, array[firstIndex]) : comparator.compare(e, array[firstIndex]); int compare = comparator == null ? COMPAREABLE_TO_KEY(e, array[firstIndex]) : comparator.compare(e, array[firstIndex]);
if(compare < 0) firstIndex = size; if(compare < 0) firstIndex = size;
@@ -414,6 +414,7 @@ public class ARRAY_PRIORITY_QUEUE KEY_GENERIC_TYPE extends ABSTRACT_PRIORITY_QUE
@Override @Override
public KEY_TYPE NEXT() { public KEY_TYPE NEXT() {
if(!hasNext()) throw new NoSuchElementException();
return dequeue(); return dequeue();
} }
} }
@@ -207,7 +207,7 @@ public class HEAP_PRIORITY_QUEUE KEY_GENERIC_TYPE extends ABSTRACT_PRIORITY_QUEU
@Override @Override
public void enqueue(KEY_TYPE e) { public void enqueue(KEY_TYPE e) {
if(size == array.length) array = Arrays.copyOf(array, (int)Math.max(Math.min((long)array.length + (array.length >> 1), SanityChecks.MAX_ARRAY_SIZE), size+1)); if(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; array[size++] = e;
ARRAYS.shiftUp(array, size-1, comparator); ARRAYS.shiftUp(array, size-1, comparator);
} }
@@ -389,6 +389,7 @@ public class HEAP_PRIORITY_QUEUE KEY_GENERIC_TYPE extends ABSTRACT_PRIORITY_QUEU
@Override @Override
public KEY_TYPE NEXT() { public KEY_TYPE NEXT() {
if(!hasNext()) throw new NoSuchElementException();
return dequeue(); return dequeue();
} }
} }
@@ -237,6 +237,7 @@ public class LINKED_CUSTOM_HASH_SET KEY_GENERIC_TYPE extends CUSTOM_HASH_SET KEY
} }
containsNull = true; containsNull = true;
onNodeAdded(nullIndex); onNodeAdded(nullIndex);
moveToFirstIndex(nullIndex);
} }
else { else {
int pos = HashUtil.mix(strategy.hashCode(o)) & mask; int pos = HashUtil.mix(strategy.hashCode(o)) & mask;
@@ -249,6 +250,7 @@ public class LINKED_CUSTOM_HASH_SET KEY_GENERIC_TYPE extends CUSTOM_HASH_SET KEY
} }
keys[pos] = o; keys[pos] = o;
onNodeAdded(pos); onNodeAdded(pos);
moveToFirstIndex(pos);
} }
if(size++ >= maxFill) rehash(HashUtil.arraySize(size+1, loadFactor)); if(size++ >= maxFill) rehash(HashUtil.arraySize(size+1, loadFactor));
return true; return true;
@@ -208,6 +208,7 @@ public class LINKED_HASH_SET KEY_GENERIC_TYPE extends HASH_SET KEY_GENERIC_TYPE
} }
containsNull = true; containsNull = true;
onNodeAdded(nullIndex); onNodeAdded(nullIndex);
moveToFirstIndex(nullIndex);
} }
else { else {
int pos = HashUtil.mix(KEY_TO_HASH(o)) & mask; int pos = HashUtil.mix(KEY_TO_HASH(o)) & mask;
@@ -220,6 +221,7 @@ public class LINKED_HASH_SET KEY_GENERIC_TYPE extends HASH_SET KEY_GENERIC_TYPE
} }
keys[pos] = o; keys[pos] = o;
onNodeAdded(pos); onNodeAdded(pos);
moveToFirstIndex(pos);
} }
if(size++ >= maxFill) rehash(HashUtil.arraySize(size+1, loadFactor)); if(size++ >= maxFill) rehash(HashUtil.arraySize(size+1, loadFactor));
return true; return true;
@@ -348,9 +348,11 @@ public class ARRAYS
* @param array the array that needs to be sorted * @param array the array that needs to be sorted
* @ArrayType(T) * @ArrayType(T)
* @param comp the Comparator that decides the sorting order * @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); stableSort(array, 0, array.length, comp);
return array;
} }
/** /**
@@ -386,9 +388,11 @@ public class ARRAYS
* Stable sort referres to Mergesort or Insertionsort * Stable sort referres to Mergesort or Insertionsort
* @param array the array that needs to be sorted * @param array the array that needs to be sorted
* @ArrayType(T) * @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); stableSort(array, 0, array.length);
return array;
} }
/** /**
@@ -423,9 +427,11 @@ public class ARRAYS
* @param array the array that needs to be sorted * @param array the array that needs to be sorted
* @param comp the Comparator that decides the sorting order * @param comp the Comparator that decides the sorting order
* @ArrayType(T) * @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); unstableSort(array, 0, array.length, comp);
return array;
} }
/** /**
@@ -461,9 +467,11 @@ public class ARRAYS
* Unstable sort referres to QuickSort or SelectionSort * Unstable sort referres to QuickSort or SelectionSort
* @param array the array that needs to be sorted * @param array the array that needs to be sorted
* @ArrayType(T) * @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); unstableSort(array, 0, array.length);
return array;
} }
/** /**
@@ -496,9 +504,11 @@ public class ARRAYS
* @param array the array that needs to be sorted * @param array the array that needs to be sorted
* @param comp the Comparator that decides the sorting order * @param comp the Comparator that decides the sorting order
* @ArrayType(T) * @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); 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, * Sorts an array according to the natural ascending order using InsertionSort,
* @param array the array that needs to be sorted * @param array the array that needs to be sorted
* @ArrayType(T) * @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); insertionSort(array, 0, array.length);
return array;
} }
/** /**
@@ -573,9 +585,11 @@ public class ARRAYS
* @param array the array that needs to be sorted * @param array the array that needs to be sorted
* @param comp the Comparator that decides the sorting order * @param comp the Comparator that decides the sorting order
* @ArrayType(T) * @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); 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, * Sorts an array according to the natural ascending order using Selection Sort,
* @param array the array that needs to be sorted * @param array the array that needs to be sorted
* @ArrayType(T) * @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); selectionSort(array, 0, array.length);
return array;
} }
/** /**
@@ -661,9 +677,11 @@ public class ARRAYS
* @param array the array that needs to be sorted * @param array the array that needs to be sorted
* @param comp the Comparator that decides the sorting order * @param comp the Comparator that decides the sorting order
* @ArrayType(T) * @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); 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 * 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 * @param array the array that needs to be sorted
* @ArrayType(T) * @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); mergeSort(array, null, 0, array.length);
return array;
} }
/** /**
@@ -922,9 +942,11 @@ public class ARRAYS
* @author Speiger * @author Speiger
* @param array the array that needs to be sorted * @param array the array that needs to be sorted
* @ArrayType(T) * @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); memFreeMergeSort(array, 0, array.length);
return array;
} }
/** /**
@@ -1099,9 +1121,11 @@ public class ARRAYS
* @param array the array that needs to be sorted * @param array the array that needs to be sorted
* @param comp the Comparator that decides the sorting order * @param comp the Comparator that decides the sorting order
* @ArrayType(T) * @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); 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. * 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 * @param array the array that needs to be sorted
* @ArrayType(T) * @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); quickSort(array, 0, array.length);
return array;
} }
/** /**
@@ -7,12 +7,13 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException; import java.util.concurrent.TimeoutException;
import java.util.concurrent.locks.LockSupport; import java.util.concurrent.locks.LockSupport;
import java.util.function.Consumer; import java.util.function.Consumer;
#if !TYPE_OBJECT #if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.functions.CONSUMER; import speiger.src.collections.PACKAGE.functions.CONSUMER;
import speiger.src.collections.PACKAGE.functions.COMPARATOR;
#else #else
import java.util.function.BiFunction; import java.util.function.BiFunction;
import java.util.Comparator;
#endif #endif
import speiger.src.collections.PACKAGE.collections.ITERABLE; import speiger.src.collections.PACKAGE.collections.ITERABLE;
@@ -112,6 +113,16 @@ public class ASYNC_BUILDER KEY_GENERIC_TYPE
return new ASYNC_BUILDERBRACES(ITERABLES.wrap(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 * Maps the elements to something else
* @param mapper the mapping function * @param mapper the mapping function
@@ -172,6 +183,17 @@ public class ASYNC_BUILDER KEY_GENERIC_TYPE
return this; 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 * Allows to preview elements before they are processed
* @param action the action that should be applied * @param action the action that should be applied
@@ -3,6 +3,8 @@ package speiger.src.collections.PACKAGE.utils;
import java.util.Objects; import java.util.Objects;
#if TYPE_BOOLEAN #if TYPE_BOOLEAN
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
#else if TYPE_OBJECT
import java.util.Comparator;
#endif #endif
import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Consumer; 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.ObjectIterable;
import speiger.src.collections.objects.collections.ObjectIterator; import speiger.src.collections.objects.collections.ObjectIterator;
import speiger.src.collections.PACKAGE.functions.CONSUMER; import speiger.src.collections.PACKAGE.functions.CONSUMER;
import speiger.src.collections.PACKAGE.functions.COMPARATOR;
#endif #endif
import speiger.src.collections.PACKAGE.collections.ITERATOR; 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.TO_OBJECT_FUNCTION;
import speiger.src.collections.PACKAGE.functions.function.PREDICATE; import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
#if !TYPE_BOOLEAN #if !TYPE_BOOLEAN
@@ -164,6 +169,30 @@ public class ITERABLES
return new LimitedIterableBRACES(wrap(iterable), limit); 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. * A Helper function that allows to preview the result of a Iterable.
* @param iterable that should be peeked at * @param iterable that should be peeked at
@@ -359,6 +388,42 @@ public class ITERABLES
#endif #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 private static class DistinctIterable KEY_GENERIC_TYPE implements ITERABLE KEY_GENERIC_TYPE
{ {
ITERABLE KEY_GENERIC_TYPE iterable; ITERABLE KEY_GENERIC_TYPE iterable;
@@ -3,6 +3,7 @@ package speiger.src.collections.PACKAGE.utils;
import java.util.Iterator; import java.util.Iterator;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
#if TYPE_OBJECT #if TYPE_OBJECT
import java.util.Comparator;
import java.util.function.CONSUMER; import java.util.function.CONSUMER;
#endif #endif
@@ -11,6 +12,7 @@ import speiger.src.collections.PACKAGE.collections.ITERATOR;
import speiger.src.collections.objects.collections.ObjectIterator; import speiger.src.collections.objects.collections.ObjectIterator;
import speiger.src.collections.objects.utils.ObjectIterators; import speiger.src.collections.objects.utils.ObjectIterators;
import speiger.src.collections.PACKAGE.functions.CONSUMER; import speiger.src.collections.PACKAGE.functions.CONSUMER;
import speiger.src.collections.PACKAGE.functions.COMPARATOR;
#endif #endif
import speiger.src.collections.PACKAGE.functions.function.TO_OBJECT_FUNCTION; import speiger.src.collections.PACKAGE.functions.function.TO_OBJECT_FUNCTION;
import speiger.src.collections.PACKAGE.functions.function.PREDICATE; import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
@@ -32,7 +34,7 @@ public class ITERATORS
/** /**
* Empty Iterator Reference * 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. * Returns a Immutable EmptyIterator instance that is automatically casted.
@@ -235,6 +237,30 @@ public class ITERATORS
return new LimitedIteratorBRACES(wrap(iterator), limit); 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. * A Helper function that allows to preview the result of a Iterator.
* @param iterator that should be peeked at * @param iterator that should be peeked at
@@ -709,7 +735,7 @@ public class ITERATORS
@Override @Override
public KEY_TYPE NEXT() { public KEY_TYPE NEXT() {
return EMPTY_KEY_VALUE; throw new NoSuchElementException();
} }
@Override @Override
@@ -719,7 +745,7 @@ public class ITERATORS
@Override @Override
public KEY_TYPE PREVIOUS() { public KEY_TYPE PREVIOUS() {
return EMPTY_KEY_VALUE; throw new NoSuchElementException();
} }
@Override @Override
@@ -761,6 +787,7 @@ public class ITERATORS
@Override @Override
public KEY_TYPE NEXT() { public KEY_TYPE NEXT() {
if(!hasNext()) throw new NoSuchElementException();
return a[from++]; return a[from++];
} }
@@ -828,7 +855,7 @@ public class ITERATORS
@Override @Override
public T next() { public T next() {
if(!hasNext()) throw new IllegalStateException("End of Iterator"); if(!hasNext()) throw new NoSuchElementException();
T result = last.next(); T result = last.next();
foundNext = false; foundNext = false;
return result; return result;
@@ -864,13 +891,42 @@ public class ITERATORS
@Override @Override
public T next() { public T next() {
if(!hasNext()) throw new IllegalStateException("End of Iterator"); if(!hasNext()) throw new NoSuchElementException();
T result = last.next(); T result = last.next();
foundNext = false; foundNext = false;
return result; 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 private static class DistinctIterator KEY_GENERIC_TYPE implements ITERATOR KEY_GENERIC_TYPE
{ {
ITERATOR KEY_GENERIC_TYPE iterator; ITERATOR KEY_GENERIC_TYPE iterator;
@@ -916,7 +972,7 @@ public class ITERATORS
@Override @Override
public KEY_TYPE NEXT() { public KEY_TYPE NEXT() {
if(!hasNext()) throw new IllegalStateException("End of Iterator"); if(!hasNext()) throw new NoSuchElementException();
foundNext = false; foundNext = false;
return lastFound; return lastFound;
} }
@@ -953,7 +1009,7 @@ public class ITERATORS
@Override @Override
public KEY_TYPE NEXT() { public KEY_TYPE NEXT() {
if(!hasNext()) throw new IllegalStateException("End of Iterator"); if(!hasNext()) throw new NoSuchElementException();
foundNext = false; foundNext = false;
return lastFound; return lastFound;
} }
@@ -976,7 +1032,7 @@ public class ITERATORS
@Override @Override
public KEY_TYPE NEXT() { public KEY_TYPE NEXT() {
if(!hasNext()) throw new IllegalStateException("End of Iterator"); if(!hasNext()) throw new NoSuchElementException();
limit--; limit--;
return iterator.NEXT(); return iterator.NEXT();
} }
@@ -999,7 +1055,7 @@ public class ITERATORS
@Override @Override
public KEY_TYPE NEXT() { public KEY_TYPE NEXT() {
if(!hasNext()) throw new IllegalStateException("End of Iterator"); if(!hasNext()) throw new NoSuchElementException();
KEY_TYPE result = iterator.NEXT(); KEY_TYPE result = iterator.NEXT();
action.accept(result); action.accept(result);
return result; return result;
@@ -27,7 +27,7 @@ public class LISTS
/** /**
* Empty List reference * 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. * Returns a Immutable EmptyList instance that is automatically casted.
@@ -1,5 +1,6 @@
package speiger.src.collections.PACKAGE.utils; package speiger.src.collections.PACKAGE.utils;
import java.util.NoSuchElementException;
#if TYPE_BOOLEAN #if TYPE_BOOLEAN
import speiger.src.collections.booleans.collections.BooleanIterator; import speiger.src.collections.booleans.collections.BooleanIterator;
import speiger.src.collections.booleans.sets.AbstractBooleanSet; import speiger.src.collections.booleans.sets.AbstractBooleanSet;
@@ -34,7 +35,7 @@ public class SETS
/** /**
* Empty Set Variable * 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 * EmptySet getter
@@ -216,10 +217,10 @@ public class SETS
return new ITERATOR KEY_GENERIC_TYPE() { return new ITERATOR KEY_GENERIC_TYPE() {
boolean next = true; boolean next = true;
@Override @Override
public boolean hasNext() { return next = false; } public boolean hasNext() { return next; }
@Override @Override
public KEY_TYPE NEXT() { public KEY_TYPE NEXT() {
if(!next) throw new IllegalStateException(); if(!hasNext()) throw new NoSuchElementException();
next = false; next = false;
return element; return element;
} }
@@ -1,6 +1,7 @@
package speiger.src.collections.PACKAGE.utils; package speiger.src.collections.PACKAGE.utils;
import java.util.Comparator; import java.util.Comparator;
import java.util.NoSuchElementException;
import java.util.Spliterator; import java.util.Spliterator;
#if PRIMITIVES #if PRIMITIVES
import java.util.Spliterator.JAVA_SPLIT_ITERATOR; import java.util.Spliterator.JAVA_SPLIT_ITERATOR;
@@ -329,7 +330,11 @@ public class SPLIT_ITERATORS
} }
@Override @Override
public KEY_TYPE NEXT() { return array[index++]; } public KEY_TYPE NEXT() {
if(!hasNext()) throw new NoSuchElementException();
return array[index++];
}
@Override @Override
public boolean hasNext() { return index < fence; } public boolean hasNext() { return index < fence; }
} }
@@ -57,7 +57,21 @@ public class MAPS
/** /**
* Empty Map Variable * 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 #endif
/** /**
@@ -104,19 +118,6 @@ public class MAPS
} }
#if !TYPE_BOOLEAN #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. * Helper function that creates a Helper wrapper to synchronize access into the map.