11 Commits
Author SHA1 Message Date
Speiger 8ff1d4f0b5 Last Sync for now 2026-05-14 21:33:31 +02:00
Speiger e56e136459 Sync with latest changes 2026-05-14 19:24:20 +02:00
Speiger 4db9c69a54 Source Sync 2026-05-14 02:54:57 +02:00
Speiger 91aabe2096 Sync Source Changes :) 2026-05-12 13:40:48 +02:00
Speiger 4c565f2cf3 Sync Latest Update 2026-05-11 18:02:31 +02:00
Speiger 720fa44eed Whoops forgot the special cases 2026-05-11 00:25:20 +02:00
Speiger c46baa10b4 Updated Workflow 2026-05-11 00:21:34 +02:00
Speiger 29ddc55947 Synced first part of the next update 2026-05-11 00:20:50 +02:00
Speiger 2a2d9e8d95 Updated to 0.9.0 src 2023-06-29 22:59:18 +02:00
Speiger 49ce7fbfbe Merge branch 'master' into debug 2023-06-29 22:56:43 +02:00
Speiger 867b3b4d9a Fixing Debug Branch by bringing it up to date! 2023-06-15 19:05:47 +02:00
2190 changed files with 1751392 additions and 301 deletions
+4 -4
View File
@@ -11,20 +11,20 @@ jobs:
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
jdk: [8, 11, 17, 20, 21] jdk: [8, 11, 16, 17, 18, 19, 20]
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v6 - uses: actions/checkout@v3
- name: Set up JDK ${{ matrix.jdk }} - name: Set up JDK ${{ matrix.jdk }}
uses: actions/setup-java@v5 uses: actions/setup-java@v3
with: with:
distribution: 'temurin' distribution: 'temurin'
java-version: ${{ matrix.jdk }} java-version: ${{ matrix.jdk }}
- name: Validate Gradle wrapper - name: Validate Gradle wrapper
uses: gradle/actions/wrapper-validation@v6 uses: gradle/wrapper-validation-action@v1
- name: Make gradlew executable - name: Make gradlew executable
run: chmod +x ./gradlew run: chmod +x ./gradlew
+3 -3
View File
@@ -9,12 +9,12 @@ jobs:
name: Unit Tests name: Unit Tests
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v6 - uses: actions/checkout@v3
with: with:
fetch-depth: 0 fetch-depth: 0
- name: Set up JDK 11 - name: Set up JDK 11
uses: actions/setup-java@v5 uses: actions/setup-java@v3
with: with:
distribution: temurin distribution: temurin
java-version: 11 java-version: 11
@@ -54,7 +54,7 @@ jobs:
esac esac
- name: Create Test Badge - name: Create Test Badge
uses: emibcn/badge-action@v2 uses: emibcn/badge-action@v1.2.4
with: with:
label: Tests label: Tests
status: '${{ fromJSON( steps.test-results.outputs.json ).conclusion }}, Passed: ${{ fromJSON( steps.test-results.outputs.json ).formatted.stats.tests_succ }}, Skipped: ${{ fromJSON( steps.test-results.outputs.json ).formatted.stats.tests_skip }}, Failed: ${{ fromJSON( steps.test-results.outputs.json ).formatted.stats.tests_fail }}' status: '${{ fromJSON( steps.test-results.outputs.json ).conclusion }}, Passed: ${{ fromJSON( steps.test-results.outputs.json ).formatted.stats.tests_succ }}, Skipped: ${{ fromJSON( steps.test-results.outputs.json ).formatted.stats.tests_skip }}, Failed: ${{ fromJSON( steps.test-results.outputs.json ).formatted.stats.tests_fail }}'
@@ -9,12 +9,12 @@ jobs:
name: Unit Tests name: Unit Tests
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v6 - uses: actions/checkout@v2
with: with:
fetch-depth: 0 fetch-depth: 0
- name: Set up JDK 11 - name: Set up JDK 11
uses: actions/setup-java@v5 uses: actions/setup-java@v3
with: with:
distribution: temurin distribution: temurin
java-version: 11 java-version: 11
+1 -9
View File
@@ -20,15 +20,7 @@ gradle-app.setting
/bin/ /bin/
/storage/ /storage/
#Generated Code #Generated Code
/src/main/java/speiger/src/collections/booleans/*
/src/main/java/speiger/src/collections/bytes/*
/src/main/java/speiger/src/collections/shorts/*
/src/main/java/speiger/src/collections/chars/*
/src/main/java/speiger/src/collections/ints/*
/src/main/java/speiger/src/collections/longs/*
/src/main/java/speiger/src/collections/floats/*
/src/main/java/speiger/src/collections/doubles/*
/src/main/java/speiger/src/collections/objects/*
#Generated Tests #Generated Tests
/src/test/java/speiger/src/testers/booleans/* /src/test/java/speiger/src/testers/booleans/*
+13 -14
View File
@@ -2,22 +2,21 @@
<projectDescription> <projectDescription>
<name>Primitive-Collections</name> <name>Primitive-Collections</name>
<comment></comment> <comment></comment>
<projects> <projects/>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.buildship.core.gradleprojectbuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures> <natures>
<nature>org.eclipse.jdt.core.javanature</nature> <nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.buildship.core.gradleprojectnature</nature> <nature>org.eclipse.buildship.core.gradleprojectnature</nature>
</natures> </natures>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments/>
</buildCommand>
<buildCommand>
<name>org.eclipse.buildship.core.gradleprojectbuilder</name>
<arguments/>
</buildCommand>
</buildSpec>
<linkedResources/>
<filteredResources/>
</projectDescription> </projectDescription>
-16
View File
@@ -1,21 +1,5 @@
# Changelog of versions # Changelog of versions
### Version 0.9.0
- Added: getFirst/getLast/removeFirst/removeLast to List.class.
- Added: Dedicated Set toArray implementations.
- Added: ToArray/pushTop functions to Stack.class.
- Added: ComputeNonDefault functions which will contain the current behavior of the Compute function, while the Compute will be changed to be more java compliant!
- Added: List.reversed, which returns a SubList that has all elements in reversed order and also inserts reversed.
- Added: Iterators.infinite as an option that will create a Infinite Iterator based on the inputed one.
- Added: List.indexedIterator which allows you to create a iterator with a customized iteration indecies. Useful if you want to transform lists output.
- Added: PriorityQueue.contains is now a function
- Added: Iterators/Async Builders now support MapToPrimitiveType function on the object variant. So more processing can be done. (Will be expanded upon later versions)
- Fixed: SetValue wasn't working on forEach implementations.
- Fixed: Compute functions now perform with primitives more java compliant. Meaning that getDefaultReturnValue function no longer is seen as null.
- Fixed: Supplier was using the wrong dataType in their function name.
- Updated: SimpleCodeGenerator 1.3.0 is now being used which allows for iterative code support.
- Breaking Change: Map.compute/IfAbsent/Present and Map.supplyIfAbsent if the value is a primitive it will no longer accept the defaultReturnValue() as "null" if that functionality is desired then use: computeNonDefault which contains the functionality!
### Version 0.8.1 ### Version 0.8.1
- Added: getFirst/getLast/removeFirst/removeLast to List.class. - Added: getFirst/getLast/removeFirst/removeLast to List.class.
- Added: Dedicated Set toArray implementations. - Added: Dedicated Set toArray implementations.
+1 -4
View File
@@ -30,13 +30,10 @@ There is 3 layers of control inside of the ModuleSettings.
Allowing for greater control without having to edit hundreds of lines of code. Allowing for greater control without having to edit hundreds of lines of code.
On top of that: On top of that:
Any Setting that isn't "Present" can be defined as "Enabled" or "Disabled" using the "Default" argument. Any Setting that isn't "Present" is counted as "Enabled".
If "Default" is missing, then it will just default to "Enabled".
So if you want to disable just 1 thing you can keep that 1 thing and delete the rest of the Setting. So if you want to disable just 1 thing you can keep that 1 thing and delete the rest of the Setting.
It will still work as the same. It will still work as the same.
The default settings just come with everything so you can see what is controllable. The default settings just come with everything so you can see what is controllable.
Note: If a global Module setting is disabled but a dependency needs said Module, it will enable only the required classes.
If a Module type (Float-Collection as example) is specifically disabled, the Dependency Resolver will throw errors telling you whats wrong.
How to compile the Code with the ModuleSettings enabled: How to compile the Code with the ModuleSettings enabled:
``` ```
-1
View File
@@ -1,5 +1,4 @@
{ {
"Default": true,
"Async": true, "Async": true,
"Base": true, "Base": true,
"Collection": true, "Collection": true,
+4 -12
View File
@@ -1,12 +1,11 @@
![build](https://github.com/Speiger/Primitive-Collections/actions/workflows/build_action.yml/badge.svg) ![build](https://github.com/Speiger/Primitive-Collections/actions/workflows/build_action.yml/badge.svg)
[![Latest Release](https://jitpack.io/v/Speiger/Primitive-Collections.svg)](https://jitpack.io/#Speiger/Primitive-Collections) [![Latest Release](https://jitpack.io/v/Speiger/Primitive-Collections.svg)](https://jitpack.io/#Speiger/Primitive-Collections)
![Maven Central Version](https://img.shields.io/maven-central/v/io.github.speiger/Primitive-Collections)
[![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) [![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/y/Speiger/Primitive-Collections) ![GitHub commit activity](https://img.shields.io/github/commit-activity/m/Speiger/Primitive-Collections)
![Unit Tests](https://github.com/Speiger/Primitive-Collections/actions/workflows/build_tests_action.yml/badge.svg) ![Unit Tests](https://github.com/Speiger/Primitive-Collections/actions/workflows/build_tests_action.yml/badge.svg)
![Coverage](https://gist.githubusercontent.com/Speiger/280257cd19cbe1dda3789bebd4ff65cf/raw/jacoco.svg) ![Coverage](https://gist.githubusercontent.com/Speiger/280257cd19cbe1dda3789bebd4ff65cf/raw/405abd1d2f6c19ac70f20b8b1772176f42d5c5d3/jacoco.svg)
[![codecov](https://codecov.io/gh/Speiger/Primitive-Collections/branch/debug/graph/badge.svg?token=WSTSNJM0EN)](https://codecov.io/gh/Speiger/Primitive-Collections) [![codecov](https://codecov.io/gh/Speiger/Primitive-Collections/branch/debug/graph/badge.svg?token=WSTSNJM0EN)](https://codecov.io/gh/Speiger/Primitive-Collections)
![Tests Done](https://gist.githubusercontent.com/Speiger/280257cd19cbe1dda3789bebd4ff65cf/raw/tests.svg) ![Tests Done](https://gist.githubusercontent.com/Speiger/280257cd19cbe1dda3789bebd4ff65cf/raw/405abd1d2f6c19ac70f20b8b1772176f42d5c5d3/tests.svg)
# Primitive-Collections # Primitive-Collections
This is a Simple Primitive Collections Library aimed to outperform Java's Collection Library and FastUtil. This is a Simple Primitive Collections Library aimed to outperform Java's Collection Library and FastUtil.
Both in Performance and Quality of Life Features. Both in Performance and Quality of Life Features.
@@ -44,7 +43,7 @@ To ensure that problems can be dealt with even if it is breaking the current API
# How to install # How to install
Using Jitpack Gradle Using Jitpack Gradle
```groovy ```gradle
repositories { repositories {
maven { maven {
url = "https://jitpack.io" url = "https://jitpack.io"
@@ -55,13 +54,6 @@ dependencies {
} }
``` ```
Using Maven Central
```groovy
dependencies {
implementation 'io.github.speiger:Primitive-Collections:0.9.0'
}
```
# SourceCode # SourceCode
The generated Sourcecode can be automatically build, The generated Sourcecode can be automatically build,
but if you want to just browse around in it. but if you want to just browse around in it.
-15
View File
@@ -1,15 +0,0 @@
# Security Policy
## Supported Versions
Due to how the releases work, only the latest versions will be supported.
## Reporting a Vulnerability
If you have discovered a security vulnerability in this project, please report it privately.
**Please refrain from posting in public issues.**
This gives me time to process issues that are being found, and reduces the possiblity of abuse while patches are being created.
Please disclose it [here](https://github.com/Speiger/Primitive-Collections/security/advisories/new).
Please consider that this project is developed by a single person.
So please provide a reasonable timeframe when reporting.
+25 -86
View File
@@ -10,7 +10,6 @@ tasks.withType(JavaCompile) {
apply plugin: 'java' apply plugin: 'java'
apply plugin: 'eclipse' apply plugin: 'eclipse'
apply plugin: 'maven-publish' apply plugin: 'maven-publish'
apply plugin: 'signing'
repositories { repositories {
mavenCentral() mavenCentral()
@@ -20,22 +19,16 @@ repositories {
} }
archivesBaseName = 'Primitive Collections' archivesBaseName = 'Primitive Collections'
version = RELEASE_VERSION; version = '0.9.0';
sourceCompatibility = targetCompatibility = compileJava.sourceCompatibility = compileJava.targetCompatibility = JavaVersion.current(); sourceCompatibility = targetCompatibility = compileJava.sourceCompatibility = compileJava.targetCompatibility = JavaVersion.current();
System.out.println("Java Version: "+compileJava.sourceCompatibility) System.out.println("Java Version: "+compileJava.sourceCompatibility)
java {
withJavadocJar()
withSourcesJar()
}
javadoc { javadoc {
options.tags = [ "implSpec", "note" ] options.tags = [ "implSpec", "note" ]
} }
eclipse { eclipse {
classpath { classpath {
downloadJavadoc = true downloadJavadoc = true
@@ -47,7 +40,6 @@ sourceSets {
builder builder
} }
configurations { configurations {
builderCompile.extendsFrom compile builderCompile.extendsFrom compile
} }
@@ -56,7 +48,7 @@ dependencies {
builderImplementation 'com.google.code.gson:gson:2.10' builderImplementation 'com.google.code.gson:gson:2.10'
builderImplementation 'de.speiger:Simple-Code-Generator:1.3.0' builderImplementation 'de.speiger:Simple-Code-Generator:1.3.0'
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:33.6.0-jre'
} }
@@ -107,12 +99,26 @@ task generateLimitSource(type: JavaExec) {
args = ['silent', 'load'] args = ['silent', 'load']
} }
task javadocJar(type: Jar) {
from javadoc
archiveClassifier = 'javadoc'
}
task srcJar(type: Jar) {
from sourceSets.main.allSource
archiveClassifier = 'sources'
}
compileJava.dependsOn generateGithubSource 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()
artifacts {
archives javadocJar
archives srcJar
}
task testBooleans(type: Test) { task testBooleans(type: Test) {
group 'tests' group 'tests'
@@ -262,10 +268,13 @@ jacocoTestReport {
} }
} }
publishing { publishing {
Properties props = new Properties()
if(file("$buildDir/credentials.properties").exists()) {
props.load(new FileInputStream("$buildDir/credentials.properties"))
}
publications { publications {
personal(MavenPublication) { mavenJava(MavenPublication) {
pom { pom {
name = 'Primitive Collections' name = 'Primitive Collections'
description = 'A Primitive Collection library that reduces memory usage and improves performance' description = 'A Primitive Collection library that reduces memory usage and improves performance'
@@ -274,6 +283,8 @@ publishing {
artifactId = project.archivesBaseName.replace(" ", "-") artifactId = project.archivesBaseName.replace(" ", "-")
groupId = 'de.speiger' groupId = 'de.speiger'
from components.java from components.java
artifact tasks.srcJar
artifact tasks.javadocJar
licenses { licenses {
license { license {
name = 'The Apache License, Version 2.0' name = 'The Apache License, Version 2.0'
@@ -298,83 +309,11 @@ publishing {
} }
repositories { repositories {
maven { maven {
name = "Speiger_Maven"
def auth = System.getenv("Speiger_Maven_Auth")?.split(';');
url version.endsWith('SNAPSHOT') ? "https://maven.speiger.com/repository/debug" : "https://maven.speiger.com/repository/main" url version.endsWith('SNAPSHOT') ? "https://maven.speiger.com/repository/debug" : "https://maven.speiger.com/repository/main"
credentials(PasswordCredentials) { credentials(PasswordCredentials) {
username auth?[0] username props.mavenUser
password auth?[1] password props.mavenPassword
} }
} }
} }
} }
tasks.withType(PublishToMavenRepository) {
def predicate = provider {
(repository == publishing.repositories.mavenCentral && publication == publishing.publications.maven) ||
(repository != publishing.repositories.mavenCentral && publication != publishing.publications.maven)
}
onlyIf("publishing binary to the external repository, or binary and sources to the internal one") {
predicate.get()
}
}
tasks.withType(PublishToMavenLocal) {
def predicate = provider {
publication == publishing.publications.personal
}
onlyIf("publishing binary and sources") {
predicate.get()
}
}
//Maven central Start
//Disabling due to java8 incompat, only needed to manually publishing anyways
//signing.useGpgCmd()
//
//import com.vanniktech.maven.publish.SonatypeHost
//import com.vanniktech.maven.publish.JavaLibrary
//import com.vanniktech.maven.publish.JavadocJar
//
//mavenPublishing {
// configure(new JavaLibrary(new JavadocJar.None(), true))
//}
//
//mavenPublishing {
// publishToMavenCentral(SonatypeHost.CENTRAL_PORTAL)
//
// signAllPublications()
// pom {
// name = 'Primitive Collections'
// description = 'A Primitive Collection library that reduces memory usage and improves performance'
// url = 'https://github.com/Speiger/Primitive-Collections'
// version = project.version
// group = 'io.github.speiger'
// licenses {
// license {
// name = 'The Apache License, Version 2.0'
// url = 'http://www.apache.org/licenses/LICENSE-2.0.txt'
// }
// }
//
// developers {
// developer {
// id = 'speiger'
// name = 'Speiger'
// }
// }
//
// scm {
// connection = 'scm:git:git://github.com/Speiger/Primitive-Collections.git'
// developerConnection = 'scm:git:ssh://github.com:Speiger/Primitive-Collections.git'
// url = 'https://github.com/Speiger/Primitive-Collections'
// }
//
// issueManagement {
// system = 'github'
// url = 'https://github.com/Speiger/Primitive-Collections/issues'
// }
// }
//}
//
-2
View File
@@ -2,5 +2,3 @@ org.gradle.jvmargs=-Xmx3G
maxMemory = 2048m maxMemory = 2048m
testThreads = 4 testThreads = 4
RELEASE_VERSION = 0.9.0
+1 -1
View File
@@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.10-bin.zip distributionUrl=https\://services.gradle.org/distributions/gradle-8.1-bin.zip
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists zipStorePath=wrapper/dists
@@ -36,6 +36,10 @@ public class MapModule extends BaseModule
public static final FunctionDependency ENUM_MAP = MODULE.createDependency("EnumMap").addEntryDependency(IMPLEMENTATION); public static final FunctionDependency ENUM_MAP = MODULE.createDependency("EnumMap").addEntryDependency(IMPLEMENTATION);
public static final FunctionDependency LINKED_ENUM_MAP = MODULE.createDependency("LinkedEnumMap").addEntryDependency(ENUM_MAP).addEntryDependency(ORDERED_MAP); public static final FunctionDependency LINKED_ENUM_MAP = MODULE.createDependency("LinkedEnumMap").addEntryDependency(ENUM_MAP).addEntryDependency(ORDERED_MAP);
public static final FunctionDependency REF_MAP = MODULE.createDependency("ReferenceHashMap").addEntryDependency(IMPLEMENTATION);
public static final FunctionDependency LINKED_REF_MAP = MODULE.createDependency("LinkedReferenceMap").addEntryDependency(REF_MAP).addEntryDependency(ORDERED_MAP);
public static final FunctionDependency CONCURRENT_MAP = MODULE.createDependency("ConcurrentMap").addEntryDependency(IMPLEMENTATION); public static final FunctionDependency CONCURRENT_MAP = MODULE.createDependency("ConcurrentMap").addEntryDependency(IMPLEMENTATION);
public static final FunctionDependency AVL_TREE_MAP = MODULE.createDependency("AVLTreeMap").addEntryDependency(SORTED_MAP).addEntryDependency(IMPLEMENTATION); public static final FunctionDependency AVL_TREE_MAP = MODULE.createDependency("AVLTreeMap").addEntryDependency(SORTED_MAP).addEntryDependency(IMPLEMENTATION);
public static final FunctionDependency RB_TREE_MAP = MODULE.createDependency("RBTreeMap").addEntryDependency(SORTED_MAP).addEntryDependency(IMPLEMENTATION); public static final FunctionDependency RB_TREE_MAP = MODULE.createDependency("RBTreeMap").addEntryDependency(SORTED_MAP).addEntryDependency(IMPLEMENTATION);
@@ -51,7 +55,7 @@ public class MapModule extends BaseModule
@Override @Override
public List<IDependency> getDependencies(ClassType keyType, ClassType valueType) { public List<IDependency> getDependencies(ClassType keyType, ClassType valueType) {
List<IDependency> dependencies = new ArrayList<>(Arrays.asList(MODULE, ORDERED_MAP, SORTED_MAP, IMPLEMENTATION, WRAPPERS, ARRAY_MAP, IMMUTABLE_MAP, HASH_MAP, LINKED_MAP, CUSTOM_MAP, LINKED_CUSTOM_MAP, CONCURRENT_MAP, AVL_TREE_MAP, RB_TREE_MAP)); List<IDependency> dependencies = new ArrayList<>(Arrays.asList(MODULE, ORDERED_MAP, SORTED_MAP, IMPLEMENTATION, WRAPPERS, ARRAY_MAP, IMMUTABLE_MAP, HASH_MAP, LINKED_MAP, CUSTOM_MAP, LINKED_CUSTOM_MAP, CONCURRENT_MAP, AVL_TREE_MAP, RB_TREE_MAP));
if(keyType == ClassType.OBJECT) dependencies.addAll(Arrays.asList(ENUM_MAP, LINKED_ENUM_MAP)); if(keyType == ClassType.OBJECT) dependencies.addAll(Arrays.asList(ENUM_MAP, LINKED_ENUM_MAP, REF_MAP, LINKED_REF_MAP));
return dependencies; return dependencies;
} }
@@ -70,6 +74,10 @@ public class MapModule extends BaseModule
if(AVL_TREE_MAP.isEnabled()) addFlag("AVL_TREE_MAP_FEATURE"); if(AVL_TREE_MAP.isEnabled()) addFlag("AVL_TREE_MAP_FEATURE");
if(RB_TREE_MAP.isEnabled()) addFlag("RB_TREE_MAP_FEATURE"); if(RB_TREE_MAP.isEnabled()) addFlag("RB_TREE_MAP_FEATURE");
if(REF_MAP.isEnabled()) addFlag("REF_MAP_FEATURE");
if(LINKED_REF_MAP.isEnabled()) addFlag("LINKED_REF_MAP_FEATURE");
if(CONCURRENT_MAP.isEnabled()) addFlag("CONCURRENT_MAP_FEATURE"); if(CONCURRENT_MAP.isEnabled()) addFlag("CONCURRENT_MAP_FEATURE");
if(IMMUTABLE_MAP.isEnabled()) addFlag("IMMUTABLE_MAP_FEATURE"); if(IMMUTABLE_MAP.isEnabled()) addFlag("IMMUTABLE_MAP_FEATURE");
if(HASH_MAP.isEnabled()) addFlag("MAP_FEATURE"); if(HASH_MAP.isEnabled()) addFlag("MAP_FEATURE");
@@ -85,6 +93,8 @@ public class MapModule extends BaseModule
if(!IMMUTABLE_MAP.isEnabled()) addBlockedFiles("ImmutableOpenHashMap"); if(!IMMUTABLE_MAP.isEnabled()) addBlockedFiles("ImmutableOpenHashMap");
if(!CONCURRENT_MAP.isEnabled()) addBlockedFiles("ConcurrentMap", "ConcurrentOpenHashMap"); if(!CONCURRENT_MAP.isEnabled()) addBlockedFiles("ConcurrentMap", "ConcurrentOpenHashMap");
if(!ORDERED_MAP.isEnabled()) addBlockedFiles("OrderedMap"); if(!ORDERED_MAP.isEnabled()) addBlockedFiles("OrderedMap");
if(!REF_MAP.isEnabled()) addBlockedFiles("ReferenceHashMap");
if(!LINKED_REF_MAP.isEnabled()) addBlockedFiles("LinkedReferenceHashMap");
if(!HASH_MAP.isEnabled()) addBlockedFiles("OpenHashMap"); if(!HASH_MAP.isEnabled()) addBlockedFiles("OpenHashMap");
if(!LINKED_MAP.isEnabled()) addBlockedFiles("LinkedOpenHashMap"); if(!LINKED_MAP.isEnabled()) addBlockedFiles("LinkedOpenHashMap");
if(!CUSTOM_MAP.isEnabled()) addBlockedFiles("OpenCustomHashMap"); if(!CUSTOM_MAP.isEnabled()) addBlockedFiles("OpenCustomHashMap");
@@ -127,6 +137,8 @@ public class MapModule extends BaseModule
addBiRequirement("AbstractMap"); addBiRequirement("AbstractMap");
addEnumRequirement("EnumMap"); addEnumRequirement("EnumMap");
addEnumRequirement("LinkedEnumMap"); addEnumRequirement("LinkedEnumMap");
addEnumRequirement("ReferenceHashMap");
addEnumRequirement("LinkedReferenceHashMap");
addBiRequirement("ConcurrentOpenHashMap"); addBiRequirement("ConcurrentOpenHashMap");
addBiRequirement("ImmutableOpenHashMap"); addBiRequirement("ImmutableOpenHashMap");
addBiRequirement("OpenHashMap"); addBiRequirement("OpenHashMap");
@@ -141,6 +153,8 @@ public class MapModule extends BaseModule
addRemapper("AbstractMap", "Abstract%sMap"); addRemapper("AbstractMap", "Abstract%sMap");
addRemapper("EnumMap", "Enum2%sMap"); addRemapper("EnumMap", "Enum2%sMap");
addRemapper("LinkedEnumMap", "LinkedEnum2%sMap"); addRemapper("LinkedEnumMap", "LinkedEnum2%sMap");
addRemapper("ReferenceHashMap", "Reference2%sHashMap");
addRemapper("LinkedReferenceHashMap", "Reference2%sLinkedHashMap");
addRemapper("ImmutableOpenHashMap", "Immutable%sOpenHashMap"); addRemapper("ImmutableOpenHashMap", "Immutable%sOpenHashMap");
//Test Classes //Test Classes
@@ -198,6 +212,7 @@ public class MapModule extends BaseModule
addBiRequirement("SortedMapNavigationTester"); addBiRequirement("SortedMapNavigationTester");
addBiRequirement("OrderedMapNavigationTester"); addBiRequirement("OrderedMapNavigationTester");
addBiRequirement("OrderedMapMoveTester"); addBiRequirement("OrderedMapMoveTester");
addBiRequirement("OrderedMapPutTester");
addBiRequirement("MapConstructorTester"); addBiRequirement("MapConstructorTester");
addRemapper("TestMapGenerator", "Test%sMapGenerator"); addRemapper("TestMapGenerator", "Test%sMapGenerator");
@@ -248,6 +263,8 @@ public class MapModule extends BaseModule
addBiClassMapper("RB_TREE_MAP", "RBTreeMap", "2"); addBiClassMapper("RB_TREE_MAP", "RBTreeMap", "2");
addFunctionValueMappers("LINKED_ENUM_MAP", valueType.isObject() ? "LinkedEnum2ObjectMap" : "LinkedEnum2%sMap"); addFunctionValueMappers("LINKED_ENUM_MAP", valueType.isObject() ? "LinkedEnum2ObjectMap" : "LinkedEnum2%sMap");
addFunctionValueMappers("ENUM_MAP", valueType.isObject() ? "Enum2ObjectMap" : "Enum2%sMap"); addFunctionValueMappers("ENUM_MAP", valueType.isObject() ? "Enum2ObjectMap" : "Enum2%sMap");
addFunctionValueMappers("REF_MAP", valueType.isObject() ? "Reference2ObjectHashMap" : "Reference2%sHashMap");
addFunctionValueMappers("LINKED_REF_MAP", valueType.isObject() ? "Reference2ObjectLinkedHashMap" : "Reference2%sLinkedHashMap");
addBiClassMapper("HASH_MAP", "OpenHashMap", "2"); addBiClassMapper("HASH_MAP", "OpenHashMap", "2");
addBiClassMapper("ARRAY_MAP", "ArrayMap", "2"); addBiClassMapper("ARRAY_MAP", "ArrayMap", "2");
@@ -9,6 +9,13 @@ import java.util.Iterator;
import java.util.Objects; import java.util.Objects;
#if JDK_TYPE #if JDK_TYPE
import java.util.OPTIONAL; import java.util.OPTIONAL;
#if SPLIT_ITERATOR_FEATURE && STREAM_FEATURE
#if TYPE_OBJECT
import java.util.stream.Stream;
import java.util.stream.Collector;
#endif
#endif
#endif #endif
#if TYPE_OBJECT #if TYPE_OBJECT
#if IARRAY_FEATURE || TYPE_OBJECT #if IARRAY_FEATURE || TYPE_OBJECT
@@ -225,6 +232,42 @@ public class ARRAY_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
return list; return list;
} }
#endif
#if JDK_TYPE && SPLIT_ITERATOR_FEATURE && STREAM_FEATURE
#if TYPE_OBJECT
/**
* Creates a Collector for a ArrayList
* @Type(T)
* @return a collector
*/
public static <T> Collector<T, ObjectArrayList<T>, ObjectArrayList<T>> toList() {
return Collector.of(ObjectArrayList::new, ObjectArrayList::add, ObjectArrayList::merge);
}
/**
* Collects a Stream to a ArrayList
* @Type(T)
* @return a list with the contents of the Stream
*/
public static <T> ARRAY_LIST KEY_GENERIC_TYPE toList(Stream<T> stream) {
return stream.collect(ObjectArrayList::new, ObjectArrayList::add, ObjectArrayList::merge);
}
private ObjectArrayList<T> merge(ObjectArrayList<T> a) {
addAll(a);
return this;
}
#else
/**
* Collects a Stream to a ArrayList
* @return a list with the contents of the Stream
*/
public static ARRAY_LIST toList(JAVA_STREAM stream) {
return stream.collect(ARRAY_LIST::new, ARRAY_LIST::add, ARRAY_LIST::addAll);
}
#endif
#endif #endif
/** /**
* Appends the specified element to the end of this list. * Appends the specified element to the end of this list.
@@ -10,6 +10,12 @@ import java.util.NoSuchElementException;
import java.util.Objects; import java.util.Objects;
#if JDK_TYPE #if JDK_TYPE
import java.util.OPTIONAL; import java.util.OPTIONAL;
#if SPLIT_ITERATOR_FEATURE && STREAM_FEATURE
#if TYPE_OBJECT
import java.util.stream.Stream;
import java.util.stream.Collector;
#endif
#endif
#endif #endif
import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer; import java.util.function.Consumer;
@@ -172,7 +178,42 @@ public class COPY_ON_WRITE_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENER
} }
#endif #endif
#if JDK_TYPE && SPLIT_ITERATOR_FEATURE && STREAM_FEATURE
#if TYPE_OBJECT
/**
* Creates a Collector for a CopyOnWriteArrayList
* @Type(T)
* @return a collector
*/
public static <T> Collector<T, CopyOnWriteObjectArrayList<T>, CopyOnWriteObjectArrayList<T>> toList() {
return Collector.of(CopyOnWriteObjectArrayList::new, CopyOnWriteObjectArrayList::add, CopyOnWriteObjectArrayList::merge);
}
/**
* Collects a Stream to a CopyOnWriteArrayList
* @Type(T)
* @return a list with the contents of the Stream
*/
public static <T> CopyOnWriteObjectArrayList KEY_GENERIC_TYPE toList(Stream<T> stream) {
return stream.collect(CopyOnWriteObjectArrayList::new, CopyOnWriteObjectArrayList::add, CopyOnWriteObjectArrayList::merge);
}
private CopyOnWriteObjectArrayList<T> merge(CopyOnWriteObjectArrayList<T> a) {
addAll(a);
return this;
}
#else
/**
* Collects a Stream to a CopyOnWriteArrayList
* @return a list with the contents of the Stream
*/
public static COPY_ON_WRITE_LIST toList(JAVA_STREAM stream) {
return stream.collect(COPY_ON_WRITE_LIST::new, COPY_ON_WRITE_LIST::add, COPY_ON_WRITE_LIST::addAll);
}
#endif
#endif
private void setArray(KEY_TYPE[] data) { private void setArray(KEY_TYPE[] data) {
this.data = data; this.data = data;
} }
@@ -3,12 +3,25 @@ package speiger.src.collections.PACKAGE.lists;
import java.util.Arrays; import java.util.Arrays;
#if TYPE_OBJECT #if TYPE_OBJECT
import java.util.Comparator; import java.util.Comparator;
#else if !TYPE_BOOLEAN
import java.util.stream.JAVA_STREAM;
import java.util.stream.StreamSupport;
#endif #endif
import java.util.Collection; import java.util.Collection;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import java.util.Objects; import java.util.Objects;
#if JDK_TYPE #if JDK_TYPE
import java.util.OPTIONAL; import java.util.OPTIONAL;
#if SPLIT_ITERATOR_FEATURE && STREAM_FEATURE
#if PRIMITIVES
import java.util.function.Supplier;
#else
import java.util.stream.Stream;
import java.util.stream.Collector;
#endif
import speiger.src.collections.PACKAGE.utils.COLLECTIONS;
#endif
#endif #endif
#if TYPE_OBJECT #if TYPE_OBJECT
import java.util.function.BiFunction; import java.util.function.BiFunction;
@@ -23,6 +36,7 @@ import java.util.function.PREDICATE;
#if !JDK_FUNCTION #if !JDK_FUNCTION
import java.util.function.JAVA_PREDICATE; import java.util.function.JAVA_PREDICATE;
#endif #endif
import java.util.function.JAVA_UNARY_OPERATOR; import java.util.function.JAVA_UNARY_OPERATOR;
#endif #endif
@@ -42,10 +56,6 @@ import speiger.src.collections.PACKAGE.functions.function.PREDICATE;
import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR; import speiger.src.collections.PACKAGE.functions.function.UNARY_OPERATOR;
import speiger.src.collections.objects.utils.ObjectArrays; import speiger.src.collections.objects.utils.ObjectArrays;
import speiger.src.collections.PACKAGE.utils.ITERATORS; import speiger.src.collections.PACKAGE.utils.ITERATORS;
#if PRIMITIVES && SPLIT_ITERATOR_FEATURE && STREAM_FEATURE
import java.util.stream.JAVA_STREAM;
import java.util.stream.StreamSupport;
#endif
#if SPLIT_ITERATOR_FEATURE #if SPLIT_ITERATOR_FEATURE
import speiger.src.collections.PACKAGE.collections.SPLIT_ITERATOR; import speiger.src.collections.PACKAGE.collections.SPLIT_ITERATOR;
import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS; import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS;
@@ -126,6 +136,42 @@ public class IMMUTABLE_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_T
data = Arrays.copyOfRange(a, offset, offset+length); data = Arrays.copyOfRange(a, offset, offset+length);
} }
#if JDK_TYPE && SPLIT_ITERATOR_FEATURE && STREAM_FEATURE
#if TYPE_OBJECT
/**
* Creates a Collector for a ImmutableList
* @Type(T)
* @return a collector
*/
public static <T> Collector<T, COLLECTION<T>, ImmutableObjectList<T>> toList() {
return Collector.of(COLLECTIONS::wrapper, COLLECTION::add, ImmutableObjectList::merge, E -> new IMMUTABLE_LIST<>(E.toArray((T[])new Object[E.size()])));
}
/**
* Collects a Stream to a ImmutableList
* @Type(T)
* @return a list with the contents of the Stream
*/
public static <T> ImmutableObjectList KEY_GENERIC_TYPE toList(Stream<T> stream) {
return stream.collect(toList());
}
private static <T> COLLECTION<T> merge(COLLECTION<T> a, COLLECTION<T> b) {
a.addAll(b);
return a;
}
#else
/**
* Collects a Stream to a ImmutableList
* @return a list with the contents of the Stream
*/
public static IMMUTABLE_LIST toList(JAVA_STREAM stream) {
return new IMMUTABLE_LIST(stream.collect((Supplier<COLLECTION>)COLLECTIONS::wrapper, COLLECTION::add, COLLECTION::addAll).TO_ARRAY());
}
#endif
#endif
@Override @Override
public boolean add(KEY_TYPE e) { throw new UnsupportedOperationException(); } public boolean add(KEY_TYPE e) { throw new UnsupportedOperationException(); }
@Override @Override
@@ -13,6 +13,12 @@ import java.util.Iterator;
import java.util.Objects; import java.util.Objects;
#if JDK_TYPE #if JDK_TYPE
import java.util.OPTIONAL; import java.util.OPTIONAL;
#if SPLIT_ITERATOR_FEATURE && STREAM_FEATURE
#if TYPE_OBJECT
import java.util.stream.Stream;
import java.util.stream.Collector;
#endif
#endif
#endif #endif
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
#if SPLIT_ITERATOR_FEATURE #if SPLIT_ITERATOR_FEATURE
@@ -160,6 +166,42 @@ public class LINKED_LIST KEY_GENERIC_TYPE extends ABSTRACT_LIST KEY_GENERIC_TYPE
for(int i = offset,m=offset+length;i<m;add(a[i++])); for(int i = offset,m=offset+length;i<m;add(a[i++]));
} }
#if JDK_TYPE && SPLIT_ITERATOR_FEATURE && STREAM_FEATURE
#if TYPE_OBJECT
/**
* Creates a Collector for a LinkedList
* @Type(T)
* @return a collector
*/
public static <T> Collector<T, ObjectLinkedList<T>, ObjectLinkedList<T>> toList() {
return Collector.of(ObjectLinkedList::new, ObjectLinkedList::add, ObjectLinkedList::merge);
}
/**
* Collects a Stream to a LinkedList
* @Type(T)
* @return a list with the contents of the Stream
*/
public static <T> ObjectLinkedList KEY_GENERIC_TYPE toList(Stream<T> stream) {
return stream.collect(ObjectLinkedList::new, ObjectLinkedList::add, ObjectLinkedList::merge);
}
private ObjectLinkedList<T> merge(ObjectLinkedList<T> a) {
addAll(a);
return this;
}
#else
/**
* Collects a Stream to a LinkedList
* @return a list with the contents of the Stream
*/
public static LINKED_LIST toList(JAVA_STREAM stream) {
return stream.collect(LINKED_LIST::new, LINKED_LIST::add, LINKED_LIST::addAll);
}
#endif
#endif
@Override @Override
public boolean add(KEY_TYPE e) { public boolean add(KEY_TYPE e) {
add(size(), e); add(size(), e);
@@ -238,13 +238,13 @@ public class LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends CUSTOM_HASH_M
if(containsNull) { if(containsNull) {
VALUE_TYPE lastValue = values[nullIndex]; VALUE_TYPE lastValue = values[nullIndex];
values[nullIndex] = value; values[nullIndex] = value;
moveToFirstIndex(nullIndex); moveToFirstIndex(nullIndex, false);
return lastValue; return lastValue;
} }
values[nullIndex] = value; values[nullIndex] = value;
containsNull = true; containsNull = true;
onNodeAdded(nullIndex); onNodeAdded(nullIndex);
moveToFirstIndex(nullIndex); moveToFirstIndex(nullIndex, true);
} }
else { else {
int pos = HashUtil.mix(strategy.hashCode(key)) & mask; int pos = HashUtil.mix(strategy.hashCode(key)) & mask;
@@ -252,7 +252,7 @@ public class LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends CUSTOM_HASH_M
if(strategy.equals(keys[pos], key)) { if(strategy.equals(keys[pos], key)) {
VALUE_TYPE lastValue = values[pos]; VALUE_TYPE lastValue = values[pos];
values[pos] = value; values[pos] = value;
moveToFirstIndex(pos); moveToFirstIndex(pos, false);
return lastValue; return lastValue;
} }
pos = ++pos & mask; pos = ++pos & mask;
@@ -260,7 +260,7 @@ public class LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends CUSTOM_HASH_M
keys[pos] = key; keys[pos] = key;
values[pos] = value; values[pos] = value;
onNodeAdded(pos); onNodeAdded(pos);
moveToFirstIndex(pos); moveToFirstIndex(pos, true);
} }
if(size++ >= maxFill) rehash(HashUtil.arraySize(size+1, loadFactor)); if(size++ >= maxFill) rehash(HashUtil.arraySize(size+1, loadFactor));
return getDefaultReturnValue(); return getDefaultReturnValue();
@@ -272,13 +272,13 @@ public class LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends CUSTOM_HASH_M
if(containsNull) { if(containsNull) {
VALUE_TYPE lastValue = values[nullIndex]; VALUE_TYPE lastValue = values[nullIndex];
values[nullIndex] = value; values[nullIndex] = value;
moveToLastIndex(nullIndex); moveToLastIndex(nullIndex, false);
return lastValue; return lastValue;
} }
values[nullIndex] = value; values[nullIndex] = value;
containsNull = true; containsNull = true;
onNodeAdded(nullIndex); onNodeAdded(nullIndex);
moveToLastIndex(nullIndex); moveToLastIndex(nullIndex, true);
} }
else { else {
int pos = HashUtil.mix(strategy.hashCode(key)) & mask; int pos = HashUtil.mix(strategy.hashCode(key)) & mask;
@@ -286,7 +286,7 @@ public class LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends CUSTOM_HASH_M
if(strategy.equals(keys[pos], key)) { if(strategy.equals(keys[pos], key)) {
VALUE_TYPE lastValue = values[pos]; VALUE_TYPE lastValue = values[pos];
values[pos] = value; values[pos] = value;
moveToLastIndex(pos); moveToLastIndex(pos, false);
return lastValue; return lastValue;
} }
pos = ++pos & mask; pos = ++pos & mask;
@@ -294,7 +294,7 @@ public class LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends CUSTOM_HASH_M
keys[pos] = key; keys[pos] = key;
values[pos] = value; values[pos] = value;
onNodeAdded(pos); onNodeAdded(pos);
moveToLastIndex(pos); moveToLastIndex(pos, true);
} }
if(size++ >= maxFill) rehash(HashUtil.arraySize(size+1, loadFactor)); if(size++ >= maxFill) rehash(HashUtil.arraySize(size+1, loadFactor));
return getDefaultReturnValue(); return getDefaultReturnValue();
@@ -307,7 +307,7 @@ public class LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends CUSTOM_HASH_M
values[nullIndex] = value; values[nullIndex] = value;
containsNull = true; containsNull = true;
onNodeAdded(nullIndex); onNodeAdded(nullIndex);
moveToFirstIndex(nullIndex); moveToFirstIndex(nullIndex, true);
} }
else { else {
int pos = HashUtil.mix(strategy.hashCode(key)) & mask; int pos = HashUtil.mix(strategy.hashCode(key)) & mask;
@@ -318,7 +318,7 @@ public class LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends CUSTOM_HASH_M
keys[pos] = key; keys[pos] = key;
values[pos] = value; values[pos] = value;
onNodeAdded(pos); onNodeAdded(pos);
moveToFirstIndex(pos); moveToFirstIndex(pos, true);
} }
if(size++ >= maxFill) rehash(HashUtil.arraySize(size+1, loadFactor)); if(size++ >= maxFill) rehash(HashUtil.arraySize(size+1, loadFactor));
return getDefaultReturnValue(); return getDefaultReturnValue();
@@ -331,7 +331,7 @@ public class LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends CUSTOM_HASH_M
values[nullIndex] = value; values[nullIndex] = value;
containsNull = true; containsNull = true;
onNodeAdded(nullIndex); onNodeAdded(nullIndex);
moveToLastIndex(nullIndex); moveToLastIndex(nullIndex, true);
} }
else { else {
int pos = HashUtil.mix(strategy.hashCode(key)) & mask; int pos = HashUtil.mix(strategy.hashCode(key)) & mask;
@@ -342,7 +342,7 @@ public class LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends CUSTOM_HASH_M
keys[pos] = key; keys[pos] = key;
values[pos] = value; values[pos] = value;
onNodeAdded(pos); onNodeAdded(pos);
moveToLastIndex(pos); moveToLastIndex(pos, true);
} }
if(size++ >= maxFill) rehash(HashUtil.arraySize(size+1, loadFactor)); if(size++ >= maxFill) rehash(HashUtil.arraySize(size+1, loadFactor));
return getDefaultReturnValue(); return getDefaultReturnValue();
@@ -353,7 +353,7 @@ public class LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends CUSTOM_HASH_M
if(isEmpty() || strategy.equals(FIRST_ENTRY_KEY(), key)) return false; if(isEmpty() || strategy.equals(FIRST_ENTRY_KEY(), key)) return false;
if(strategy.equals(key, EMPTY_KEY_VALUE)) { if(strategy.equals(key, EMPTY_KEY_VALUE)) {
if(containsNull) { if(containsNull) {
moveToFirstIndex(nullIndex); moveToFirstIndex(nullIndex, false);
return true; return true;
} }
} }
@@ -361,7 +361,7 @@ public class LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends CUSTOM_HASH_M
int pos = HashUtil.mix(strategy.hashCode(key)) & mask; int pos = HashUtil.mix(strategy.hashCode(key)) & mask;
while(!strategy.equals(keys[pos], EMPTY_KEY_VALUE)) { while(!strategy.equals(keys[pos], EMPTY_KEY_VALUE)) {
if(strategy.equals(keys[pos], key)) { if(strategy.equals(keys[pos], key)) {
moveToFirstIndex(pos); moveToFirstIndex(pos, false);
return true; return true;
} }
pos = ++pos & mask; pos = ++pos & mask;
@@ -375,7 +375,7 @@ public class LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends CUSTOM_HASH_M
if(isEmpty() || strategy.equals(LAST_ENTRY_KEY(), key)) return false; if(isEmpty() || strategy.equals(LAST_ENTRY_KEY(), key)) return false;
if(strategy.equals(key, EMPTY_KEY_VALUE)) { if(strategy.equals(key, EMPTY_KEY_VALUE)) {
if(containsNull) { if(containsNull) {
moveToLastIndex(nullIndex); moveToLastIndex(nullIndex, false);
return true; return true;
} }
} }
@@ -383,7 +383,7 @@ public class LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends CUSTOM_HASH_M
int pos = HashUtil.mix(strategy.hashCode(key)) & mask; int pos = HashUtil.mix(strategy.hashCode(key)) & mask;
while(!strategy.equals(keys[pos], EMPTY_KEY_VALUE)) { while(!strategy.equals(keys[pos], EMPTY_KEY_VALUE)) {
if(strategy.equals(keys[pos], key)) { if(strategy.equals(keys[pos], key)) {
moveToLastIndex(pos); moveToLastIndex(pos, false);
return true; return true;
} }
pos = ++pos & mask; pos = ++pos & mask;
@@ -396,7 +396,7 @@ public class LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends CUSTOM_HASH_M
public VALUE_TYPE getAndMoveToFirst(KEY_TYPE key) { public VALUE_TYPE getAndMoveToFirst(KEY_TYPE key) {
int index = findIndex(key); int index = findIndex(key);
if(index < 0) return getDefaultReturnValue(); if(index < 0) return getDefaultReturnValue();
moveToFirstIndex(index); moveToFirstIndex(index, false);
return values[index]; return values[index];
} }
@@ -404,7 +404,7 @@ public class LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends CUSTOM_HASH_M
public VALUE_TYPE getAndMoveToLast(KEY_TYPE key) { public VALUE_TYPE getAndMoveToLast(KEY_TYPE key) {
int index = findIndex(key); int index = findIndex(key);
if(index < 0) return getDefaultReturnValue(); if(index < 0) return getDefaultReturnValue();
moveToLastIndex(index); moveToLastIndex(index, false);
return values[index]; return values[index];
} }
@@ -580,8 +580,8 @@ public class LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends CUSTOM_HASH_M
containsNull = false; containsNull = false;
} }
protected void moveToFirstIndex(int startPos) { protected void moveToFirstIndex(int startPos, boolean adding) {
if(size == 1 || firstIndex == startPos) return; if(size == (adding ? 0 : 1) || firstIndex == startPos) return;
if(lastIndex == startPos) { if(lastIndex == startPos) {
lastIndex = (int)(links[startPos] >>> 32); lastIndex = (int)(links[startPos] >>> 32);
links[lastIndex] |= 0xFFFFFFFFL; links[lastIndex] |= 0xFFFFFFFFL;
@@ -598,8 +598,8 @@ public class LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends CUSTOM_HASH_M
firstIndex = startPos; firstIndex = startPos;
} }
protected void moveToLastIndex(int startPos) { protected void moveToLastIndex(int startPos, boolean adding) {
if(size == 1 || lastIndex == startPos) return; if(size == (adding ? 0 : 1) || lastIndex == startPos) return;
if(firstIndex == startPos) { if(firstIndex == startPos) {
firstIndex = (int)links[startPos]; firstIndex = (int)links[startPos];
links[lastIndex] |= 0xFFFFFFFF00000000L; links[lastIndex] |= 0xFFFFFFFF00000000L;
@@ -713,6 +713,10 @@ public class LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends CUSTOM_HASH_M
} }
private class MapEntrySet extends AbstractObjectSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> implements ORDERED_MAP.FastOrderedSet KEY_VALUE_GENERIC_TYPE { private class MapEntrySet extends AbstractObjectSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> implements ORDERED_MAP.FastOrderedSet KEY_VALUE_GENERIC_TYPE {
@Override
public void addFirst(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); }
@Override
public void addLast(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); }
@Override @Override
public boolean addAndMoveToFirst(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); } public boolean addAndMoveToFirst(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); }
@Override @Override
@@ -1005,9 +1009,12 @@ public class LINKED_CUSTOM_HASH_MAP KEY_VALUE_GENERIC_TYPE extends CUSTOM_HASH_M
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
@Override
public void addFirst(KEY_TYPE o) { throw new UnsupportedOperationException(); }
@Override
public void addLast(KEY_TYPE o) { throw new UnsupportedOperationException(); }
@Override @Override
public boolean addAndMoveToFirst(KEY_TYPE o) { throw new UnsupportedOperationException(); } public boolean addAndMoveToFirst(KEY_TYPE o) { throw new UnsupportedOperationException(); }
@Override @Override
public boolean addAndMoveToLast(KEY_TYPE o) { throw new UnsupportedOperationException(); } public boolean addAndMoveToLast(KEY_TYPE o) { throw new UnsupportedOperationException(); }
@@ -215,13 +215,13 @@ public class LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE extends HASH_MAP KEY_VALUE_G
if(containsNull) { if(containsNull) {
VALUE_TYPE lastValue = values[nullIndex]; VALUE_TYPE lastValue = values[nullIndex];
values[nullIndex] = value; values[nullIndex] = value;
moveToFirstIndex(nullIndex); moveToFirstIndex(nullIndex, false);
return lastValue; return lastValue;
} }
values[nullIndex] = value; values[nullIndex] = value;
containsNull = true; containsNull = true;
onNodeAdded(nullIndex); onNodeAdded(nullIndex);
moveToFirstIndex(nullIndex); moveToFirstIndex(nullIndex, true);
} }
else { else {
int pos = HashUtil.mix(KEY_TO_HASH(key)) & mask; int pos = HashUtil.mix(KEY_TO_HASH(key)) & mask;
@@ -229,7 +229,7 @@ public class LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE extends HASH_MAP KEY_VALUE_G
if(KEY_EQUALS(keys[pos], key)) { if(KEY_EQUALS(keys[pos], key)) {
VALUE_TYPE lastValue = values[pos]; VALUE_TYPE lastValue = values[pos];
values[pos] = value; values[pos] = value;
moveToFirstIndex(pos); moveToFirstIndex(pos, false);
return lastValue; return lastValue;
} }
pos = ++pos & mask; pos = ++pos & mask;
@@ -237,7 +237,7 @@ public class LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE extends HASH_MAP KEY_VALUE_G
keys[pos] = key; keys[pos] = key;
values[pos] = value; values[pos] = value;
onNodeAdded(pos); onNodeAdded(pos);
moveToFirstIndex(pos); moveToFirstIndex(pos, true);
} }
if(size++ >= maxFill) rehash(HashUtil.arraySize(size+1, loadFactor)); if(size++ >= maxFill) rehash(HashUtil.arraySize(size+1, loadFactor));
return getDefaultReturnValue(); return getDefaultReturnValue();
@@ -249,13 +249,13 @@ public class LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE extends HASH_MAP KEY_VALUE_G
if(containsNull) { if(containsNull) {
VALUE_TYPE lastValue = values[nullIndex]; VALUE_TYPE lastValue = values[nullIndex];
values[nullIndex] = value; values[nullIndex] = value;
moveToLastIndex(nullIndex); moveToLastIndex(nullIndex, false);
return lastValue; return lastValue;
} }
values[nullIndex] = value; values[nullIndex] = value;
containsNull = true; containsNull = true;
onNodeAdded(nullIndex); onNodeAdded(nullIndex);
moveToLastIndex(nullIndex); moveToLastIndex(nullIndex, true);
} }
else { else {
int pos = HashUtil.mix(KEY_TO_HASH(key)) & mask; int pos = HashUtil.mix(KEY_TO_HASH(key)) & mask;
@@ -263,7 +263,7 @@ public class LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE extends HASH_MAP KEY_VALUE_G
if(KEY_EQUALS(keys[pos], key)) { if(KEY_EQUALS(keys[pos], key)) {
VALUE_TYPE lastValue = values[pos]; VALUE_TYPE lastValue = values[pos];
values[pos] = value; values[pos] = value;
moveToLastIndex(pos); moveToLastIndex(pos, false);
return lastValue; return lastValue;
} }
pos = ++pos & mask; pos = ++pos & mask;
@@ -271,7 +271,7 @@ public class LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE extends HASH_MAP KEY_VALUE_G
keys[pos] = key; keys[pos] = key;
values[pos] = value; values[pos] = value;
onNodeAdded(pos); onNodeAdded(pos);
moveToLastIndex(pos); moveToLastIndex(pos, true);
} }
if(size++ >= maxFill) rehash(HashUtil.arraySize(size+1, loadFactor)); if(size++ >= maxFill) rehash(HashUtil.arraySize(size+1, loadFactor));
return getDefaultReturnValue(); return getDefaultReturnValue();
@@ -284,18 +284,18 @@ public class LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE extends HASH_MAP KEY_VALUE_G
values[nullIndex] = value; values[nullIndex] = value;
containsNull = true; containsNull = true;
onNodeAdded(nullIndex); onNodeAdded(nullIndex);
moveToFirstIndex(nullIndex); moveToFirstIndex(nullIndex, true);
} }
else { else {
int pos = HashUtil.mix(KEY_TO_HASH(key)) & mask; int pos = HashUtil.mix(KEY_TO_HASH(key)) & mask;
while(KEY_EQUALS_NULL(key)) { while(KEY_EQUALS_NOT_NULL(keys[pos])) {
if(KEY_EQUALS(keys[pos], key)) return values[pos]; if(KEY_EQUALS(keys[pos], key)) return values[pos];
pos = ++pos & mask; pos = ++pos & mask;
} }
keys[pos] = key; keys[pos] = key;
values[pos] = value; values[pos] = value;
onNodeAdded(pos); onNodeAdded(pos);
moveToFirstIndex(pos); moveToFirstIndex(pos, true);
} }
if(size++ >= maxFill) rehash(HashUtil.arraySize(size+1, loadFactor)); if(size++ >= maxFill) rehash(HashUtil.arraySize(size+1, loadFactor));
return getDefaultReturnValue(); return getDefaultReturnValue();
@@ -308,18 +308,18 @@ public class LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE extends HASH_MAP KEY_VALUE_G
values[nullIndex] = value; values[nullIndex] = value;
containsNull = true; containsNull = true;
onNodeAdded(nullIndex); onNodeAdded(nullIndex);
moveToLastIndex(nullIndex); moveToLastIndex(nullIndex, true);
} }
else { else {
int pos = HashUtil.mix(KEY_TO_HASH(key)) & mask; int pos = HashUtil.mix(KEY_TO_HASH(key)) & mask;
while(KEY_EQUALS_NULL(key)) { while(KEY_EQUALS_NOT_NULL(keys[pos])) {
if(KEY_EQUALS(keys[pos], key)) return values[pos]; if(KEY_EQUALS(keys[pos], key)) return values[pos];
pos = ++pos & mask; pos = ++pos & mask;
} }
keys[pos] = key; keys[pos] = key;
values[pos] = value; values[pos] = value;
onNodeAdded(pos); onNodeAdded(pos);
moveToLastIndex(pos); moveToLastIndex(pos, true);
} }
if(size++ >= maxFill) rehash(HashUtil.arraySize(size+1, loadFactor)); if(size++ >= maxFill) rehash(HashUtil.arraySize(size+1, loadFactor));
return getDefaultReturnValue(); return getDefaultReturnValue();
@@ -330,7 +330,7 @@ public class LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE extends HASH_MAP KEY_VALUE_G
if(isEmpty() || KEY_EQUALS(FIRST_ENTRY_KEY(), key)) return false; if(isEmpty() || KEY_EQUALS(FIRST_ENTRY_KEY(), key)) return false;
if(KEY_EQUALS_NULL(key)) { if(KEY_EQUALS_NULL(key)) {
if(containsNull) { if(containsNull) {
moveToFirstIndex(nullIndex); moveToFirstIndex(nullIndex, false);
return true; return true;
} }
} }
@@ -338,7 +338,7 @@ public class LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE extends HASH_MAP KEY_VALUE_G
int pos = HashUtil.mix(KEY_TO_HASH(key)) & mask; int pos = HashUtil.mix(KEY_TO_HASH(key)) & mask;
while(KEY_EQUALS_NOT_NULL(keys[pos])) { while(KEY_EQUALS_NOT_NULL(keys[pos])) {
if(KEY_EQUALS(keys[pos], key)) { if(KEY_EQUALS(keys[pos], key)) {
moveToFirstIndex(pos); moveToFirstIndex(pos, false);
return true; return true;
} }
pos = ++pos & mask; pos = ++pos & mask;
@@ -352,7 +352,7 @@ public class LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE extends HASH_MAP KEY_VALUE_G
if(isEmpty() || KEY_EQUALS(LAST_ENTRY_KEY(), key)) return false; if(isEmpty() || KEY_EQUALS(LAST_ENTRY_KEY(), key)) return false;
if(KEY_EQUALS_NULL(key)) { if(KEY_EQUALS_NULL(key)) {
if(containsNull) { if(containsNull) {
moveToLastIndex(nullIndex); moveToLastIndex(nullIndex, false);
return true; return true;
} }
} }
@@ -360,7 +360,7 @@ public class LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE extends HASH_MAP KEY_VALUE_G
int pos = HashUtil.mix(KEY_TO_HASH(key)) & mask; int pos = HashUtil.mix(KEY_TO_HASH(key)) & mask;
while(KEY_EQUALS_NOT_NULL(keys[pos])) { while(KEY_EQUALS_NOT_NULL(keys[pos])) {
if(KEY_EQUALS(keys[pos], key)) { if(KEY_EQUALS(keys[pos], key)) {
moveToLastIndex(pos); moveToLastIndex(pos, false);
return true; return true;
} }
pos = ++pos & mask; pos = ++pos & mask;
@@ -373,7 +373,7 @@ public class LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE extends HASH_MAP KEY_VALUE_G
public VALUE_TYPE getAndMoveToFirst(KEY_TYPE key) { public VALUE_TYPE getAndMoveToFirst(KEY_TYPE key) {
int index = findIndex(key); int index = findIndex(key);
if(index < 0) return getDefaultReturnValue(); if(index < 0) return getDefaultReturnValue();
moveToFirstIndex(index); moveToFirstIndex(index, false);
return values[index]; return values[index];
} }
@@ -381,7 +381,7 @@ public class LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE extends HASH_MAP KEY_VALUE_G
public VALUE_TYPE getAndMoveToLast(KEY_TYPE key) { public VALUE_TYPE getAndMoveToLast(KEY_TYPE key) {
int index = findIndex(key); int index = findIndex(key);
if(index < 0) return getDefaultReturnValue(); if(index < 0) return getDefaultReturnValue();
moveToLastIndex(index); moveToLastIndex(index, false);
return values[index]; return values[index];
} }
@@ -584,8 +584,8 @@ public class LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE extends HASH_MAP KEY_VALUE_G
containsNull = false; containsNull = false;
} }
protected void moveToFirstIndex(int startPos) { protected void moveToFirstIndex(int startPos, boolean adding) {
if(size == 1 || firstIndex == startPos) return; if(size == (adding ? 0 : 1) || firstIndex == startPos) return;
if(lastIndex == startPos) { if(lastIndex == startPos) {
lastIndex = (int)(links[startPos] >>> 32); lastIndex = (int)(links[startPos] >>> 32);
links[lastIndex] |= 0xFFFFFFFFL; links[lastIndex] |= 0xFFFFFFFFL;
@@ -602,8 +602,8 @@ public class LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE extends HASH_MAP KEY_VALUE_G
firstIndex = startPos; firstIndex = startPos;
} }
protected void moveToLastIndex(int startPos) { protected void moveToLastIndex(int startPos, boolean adding) {
if(size == 1 || lastIndex == startPos) return; if(size == (adding ? 0 : 1) || lastIndex == startPos) return;
if(firstIndex == startPos) { if(firstIndex == startPos) {
firstIndex = (int)links[startPos]; firstIndex = (int)links[startPos];
links[lastIndex] |= 0xFFFFFFFF00000000L; links[lastIndex] |= 0xFFFFFFFF00000000L;
@@ -717,6 +717,10 @@ public class LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE extends HASH_MAP KEY_VALUE_G
} }
private class MapEntrySet extends AbstractObjectSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> implements ORDERED_MAP.FastOrderedSet KEY_VALUE_GENERIC_TYPE { private class MapEntrySet extends AbstractObjectSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> implements ORDERED_MAP.FastOrderedSet KEY_VALUE_GENERIC_TYPE {
@Override
public void addFirst(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); }
@Override
public void addLast(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); }
@Override @Override
public boolean addAndMoveToFirst(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); } public boolean addAndMoveToFirst(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); }
@Override @Override
@@ -1004,6 +1008,12 @@ public class LINKED_HASH_MAP KEY_VALUE_GENERIC_TYPE extends HASH_MAP KEY_VALUE_G
@Override @Override
public boolean add(KEY_TYPE o) { throw new UnsupportedOperationException(); } public boolean add(KEY_TYPE o) { throw new UnsupportedOperationException(); }
@Override
public void addFirst(KEY_TYPE o) { throw new UnsupportedOperationException(); }
@Override
public void addLast(KEY_TYPE o) { throw new UnsupportedOperationException(); }
@Override @Override
public boolean addAndMoveToFirst(KEY_TYPE o) { throw new UnsupportedOperationException(); } public boolean addAndMoveToFirst(KEY_TYPE o) { throw new UnsupportedOperationException(); }
@@ -637,6 +637,10 @@ public class IMMUTABLE_HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_
} }
private class MapEntrySet extends AbstractObjectSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> implements ORDERED_MAP.FastOrderedSet KEY_VALUE_GENERIC_TYPE { private class MapEntrySet extends AbstractObjectSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> implements ORDERED_MAP.FastOrderedSet KEY_VALUE_GENERIC_TYPE {
@Override
public void addFirst(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); }
@Override
public void addLast(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); }
@Override @Override
public boolean addAndMoveToFirst(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); } public boolean addAndMoveToFirst(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); }
@Override @Override
@@ -894,6 +898,12 @@ public class IMMUTABLE_HASH_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
@Override
public void addFirst(KEY_TYPE o) { throw new UnsupportedOperationException(); }
@Override
public void addLast(KEY_TYPE o) { throw new UnsupportedOperationException(); }
@Override @Override
public boolean addAndMoveToFirst(KEY_TYPE o) { throw new UnsupportedOperationException(); } public boolean addAndMoveToFirst(KEY_TYPE o) { throw new UnsupportedOperationException(); }
@@ -868,6 +868,10 @@ public class ARRAY_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GEN
} }
private class MapEntrySet extends AbstractObjectSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> implements ORDERED_MAP.FastOrderedSet KEY_VALUE_GENERIC_TYPE { private class MapEntrySet extends AbstractObjectSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> implements ORDERED_MAP.FastOrderedSet KEY_VALUE_GENERIC_TYPE {
@Override
public void addFirst(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); }
@Override
public void addLast(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); }
@Override @Override
public boolean addAndMoveToFirst(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); } public boolean addAndMoveToFirst(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); }
@Override @Override
@@ -1126,6 +1130,10 @@ public class ARRAY_MAP KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP KEY_VALUE_GEN
@Override @Override
public boolean add(KEY_TYPE o) { throw new UnsupportedOperationException(); } public boolean add(KEY_TYPE o) { throw new UnsupportedOperationException(); }
@Override @Override
public void addFirst(KEY_TYPE o) { throw new UnsupportedOperationException(); }
@Override
public void addLast(KEY_TYPE o) { throw new UnsupportedOperationException(); }
@Override
public boolean addAndMoveToFirst(KEY_TYPE o) { throw new UnsupportedOperationException(); } public boolean addAndMoveToFirst(KEY_TYPE o) { throw new UnsupportedOperationException(); }
@Override @Override
public boolean addAndMoveToLast(KEY_TYPE o) { throw new UnsupportedOperationException(); } public boolean addAndMoveToLast(KEY_TYPE o) { throw new UnsupportedOperationException(); }
@@ -473,6 +473,10 @@ public class LINKED_ENUM_MAP KEY_ENUM_VALUE_GENERIC_TYPE extends ENUM_MAP KEY_VA
} }
private class MapEntrySet extends AbstractObjectSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> implements ORDERED_MAP.FastOrderedSet KEY_VALUE_GENERIC_TYPE { private class MapEntrySet extends AbstractObjectSet<MAP.Entry KEY_VALUE_GENERIC_TYPE> implements ORDERED_MAP.FastOrderedSet KEY_VALUE_GENERIC_TYPE {
@Override
public void addFirst(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); }
@Override
public void addLast(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); }
@Override @Override
public boolean addAndMoveToFirst(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); } public boolean addAndMoveToFirst(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); }
@Override @Override
@@ -637,7 +641,10 @@ public class LINKED_ENUM_MAP KEY_ENUM_VALUE_GENERIC_TYPE extends ENUM_MAP KEY_VA
public boolean add(T o) { public boolean add(T o) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
@Override
public void addFirst(T o) { throw new UnsupportedOperationException(); }
@Override
public void addLast(T o) { throw new UnsupportedOperationException(); }
@Override @Override
public boolean addAndMoveToFirst(T o) { throw new UnsupportedOperationException(); } public boolean addAndMoveToFirst(T o) { throw new UnsupportedOperationException(); }
@@ -9,6 +9,14 @@ import java.util.function.BiFunction;
import java.util.Objects; import java.util.Objects;
#if JDK_TYPE #if JDK_TYPE
import java.util.OPTIONAL; import java.util.OPTIONAL;
#if SPLIT_ITERATOR_FEATURE && STREAM_FEATURE
#if !TYPE_OBJECT
import java.util.stream.JAVA_STREAM;
#else
import java.util.stream.Stream;
import java.util.stream.Collector;
#endif
#endif
#endif #endif
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
#if JDK_FUNCTION #if JDK_FUNCTION
@@ -105,6 +113,47 @@ public class ARRAY_FIFO_QUEUE KEY_GENERIC_TYPE extends ABSTRACT_PRIORITY_QUEUE K
this(MIN_CAPACITY); this(MIN_CAPACITY);
} }
#if JDK_TYPE && SPLIT_ITERATOR_FEATURE && STREAM_FEATURE
#if TYPE_OBJECT
/**
* Creates a Collector for a ArrayFIFOQueue
* @Type(T)
* @return a collector
*/
public static <T> Collector<T, ARRAY_FIFO_QUEUE<T>, ARRAY_FIFO_QUEUE<T>> toQueue() {
return Collector.of(ARRAY_FIFO_QUEUE::new, ARRAY_FIFO_QUEUE::enqueue, ARRAY_FIFO_QUEUE::merge);
}
/**
* Collects a Stream to a ArrayFIFOQueue
* @Type(T)
* @return a queue with the contents of the Stream
*/
public static <T> ARRAY_FIFO_QUEUE KEY_GENERIC_TYPE toQueue(Stream<T> stream) {
return stream.collect(ARRAY_FIFO_QUEUE::new, ARRAY_FIFO_QUEUE::enqueue, ARRAY_FIFO_QUEUE::merge);
}
private ARRAY_FIFO_QUEUE<T> merge(ARRAY_FIFO_QUEUE<T> a) {
enqueueAll(a.toArray((T[])new Object[a.size()]));
return this;
}
#else
/**
* Collects a Stream to a ArrayFIFOQueue
* @return a queue with the contents of the Stream
*/
public static ARRAY_FIFO_QUEUE toQueue(JAVA_STREAM stream) {
return stream.collect(ARRAY_FIFO_QUEUE::new, ARRAY_FIFO_QUEUE::enqueue, ARRAY_FIFO_QUEUE::merge);
}
private ARRAY_FIFO_QUEUE merge(ARRAY_FIFO_QUEUE a) {
enqueueAll(a.TO_ARRAY());
return this;
}
#endif
#endif
@Override @Override
public ITERATOR KEY_GENERIC_TYPE iterator() { public ITERATOR KEY_GENERIC_TYPE iterator() {
return new Iter(); return new Iter();
@@ -10,6 +10,14 @@ import java.util.function.BiFunction;
import java.util.Objects; import java.util.Objects;
#if JDK_TYPE #if JDK_TYPE
import java.util.OPTIONAL; import java.util.OPTIONAL;
#if SPLIT_ITERATOR_FEATURE && STREAM_FEATURE
#if !TYPE_OBJECT
import java.util.stream.JAVA_STREAM;
#else
import java.util.stream.Stream;
import java.util.stream.Collector;
#endif
#endif
#endif #endif
#if JDK_FUNCTION #if JDK_FUNCTION
import java.util.function.PREDICATE; import java.util.function.PREDICATE;
@@ -196,7 +204,47 @@ public class ARRAY_PRIORITY_QUEUE KEY_GENERIC_TYPE extends ABSTRACT_PRIORITY_QUE
queue.size = size; queue.size = size;
return queue; return queue;
} }
#if JDK_TYPE && SPLIT_ITERATOR_FEATURE && STREAM_FEATURE
#if TYPE_OBJECT
/**
* Creates a Collector for a ArrayPriorityQueue
* @Type(T)
* @return a collector
*/
public static <T> Collector<T, ARRAY_PRIORITY_QUEUE<T>, ARRAY_PRIORITY_QUEUE<T>> toQueue() {
return Collector.of(ARRAY_PRIORITY_QUEUE::new, ARRAY_PRIORITY_QUEUE::enqueue, ARRAY_PRIORITY_QUEUE::merge);
}
/**
* Collects a Stream to a ArrayPriorityQueue
* @Type(T)
* @return a queue with the contents of the Stream
*/
public static <T> ARRAY_PRIORITY_QUEUE KEY_GENERIC_TYPE toQueue(Stream<T> stream) {
return stream.collect(ARRAY_PRIORITY_QUEUE::new, ARRAY_PRIORITY_QUEUE::enqueue, ARRAY_PRIORITY_QUEUE::merge);
}
private ARRAY_PRIORITY_QUEUE<T> merge(ARRAY_PRIORITY_QUEUE<T> a) {
enqueueAll(a.toArray((T[])new Object[a.size()]));
return this;
}
#else
/**
* Collects a Stream to a ArrayPriorityQueue
* @return a queue with the contents of the Stream
*/
public static ARRAY_PRIORITY_QUEUE toQueue(JAVA_STREAM stream) {
return stream.collect(ARRAY_PRIORITY_QUEUE::new, ARRAY_PRIORITY_QUEUE::enqueue, ARRAY_PRIORITY_QUEUE::merge);
}
private ARRAY_PRIORITY_QUEUE merge(ARRAY_PRIORITY_QUEUE a) {
enqueueAll(a.TO_ARRAY());
return this;
}
#endif
#endif
@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 + (long)(array.length >> 1), (long)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));
@@ -10,6 +10,14 @@ import java.util.function.BiFunction;
import java.util.Objects; import java.util.Objects;
#if JDK_TYPE #if JDK_TYPE
import java.util.OPTIONAL; import java.util.OPTIONAL;
#if SPLIT_ITERATOR_FEATURE && STREAM_FEATURE
#if !TYPE_OBJECT
import java.util.stream.JAVA_STREAM;
#else
import java.util.stream.Stream;
import java.util.stream.Collector;
#endif
#endif
#endif #endif
#if JDK_FUNCTION #if JDK_FUNCTION
import java.util.function.PREDICATE; import java.util.function.PREDICATE;
@@ -199,6 +207,47 @@ public class HEAP_PRIORITY_QUEUE KEY_GENERIC_TYPE extends ABSTRACT_PRIORITY_QUEU
return queue; return queue;
} }
#if JDK_TYPE && SPLIT_ITERATOR_FEATURE && STREAM_FEATURE
#if TYPE_OBJECT
/**
* Creates a Collector for a ArrayFIFOQueue
* @Type(T)
* @return a collector
*/
public static <T> Collector<T, HEAP_PRIORITY_QUEUE<T>, HEAP_PRIORITY_QUEUE<T>> toQueue() {
return Collector.of(HEAP_PRIORITY_QUEUE::new, HEAP_PRIORITY_QUEUE::enqueue, HEAP_PRIORITY_QUEUE::merge);
}
/**
* Collects a Stream to a ArrayFIFOQueue
* @Type(T)
* @return a queue with the contents of the Stream
*/
public static <T> HEAP_PRIORITY_QUEUE KEY_GENERIC_TYPE toQueue(Stream<T> stream) {
return stream.collect(HEAP_PRIORITY_QUEUE::new, HEAP_PRIORITY_QUEUE::enqueue, HEAP_PRIORITY_QUEUE::merge);
}
private HEAP_PRIORITY_QUEUE<T> merge(HEAP_PRIORITY_QUEUE<T> a) {
enqueueAll(a.toArray((T[])new Object[a.size()]));
return this;
}
#else
/**
* Collects a Stream to a ArrayFIFOQueue
* @return a queue with the contents of the Stream
*/
public static HEAP_PRIORITY_QUEUE toQueue(JAVA_STREAM stream) {
return stream.collect(HEAP_PRIORITY_QUEUE::new, HEAP_PRIORITY_QUEUE::enqueue, HEAP_PRIORITY_QUEUE::merge);
}
private HEAP_PRIORITY_QUEUE merge(HEAP_PRIORITY_QUEUE a) {
enqueueAll(a.TO_ARRAY());
return this;
}
#endif
#endif
@Override @Override
public int size() { public int size() {
return size; return size;
@@ -12,6 +12,12 @@ import java.util.NoSuchElementException;
import java.util.Objects; import java.util.Objects;
#if JDK_TYPE #if JDK_TYPE
import java.util.OPTIONAL; import java.util.OPTIONAL;
#if !TYPE_OBJECT
import java.util.stream.JAVA_STREAM;
#else
import java.util.stream.Stream;
import java.util.stream.Collector;
#endif
#endif #endif
#if JDK_FUNCTION #if JDK_FUNCTION
import java.util.function.PREDICATE; import java.util.function.PREDICATE;
@@ -214,6 +220,42 @@ public class AVL_TREE_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE
while(iterator.hasNext()) add(iterator.NEXT()); while(iterator.hasNext()) add(iterator.NEXT());
} }
#if JDK_TYPE && SPLIT_ITERATOR_FEATURE && STREAM_FEATURE
#if TYPE_OBJECT
/**
* Creates a Collector for a AVLTreeSet
* @Type(T)
* @return a collector
*/
public static <T> Collector<T, AVL_TREE_SET<T>, AVL_TREE_SET<T>> toSet() {
return Collector.of(AVL_TREE_SET::new, AVL_TREE_SET::add, AVL_TREE_SET::merge);
}
/**
* Collects a Stream to a AVLTreeSet
* @Type(T)
* @return a set with the contents of the Stream
*/
public static <T> AVL_TREE_SET KEY_GENERIC_TYPE toSet(Stream<T> stream) {
return stream.collect(AVL_TREE_SET::new, AVL_TREE_SET::add, AVL_TREE_SET::merge);
}
private AVL_TREE_SET<T> merge(AVL_TREE_SET<T> a) {
addAll(a);
return this;
}
#else
/**
* Collects a Stream to a AVLTreeSet
* @return a set with the contents of the Stream
*/
public static AVL_TREE_SET toSet(JAVA_STREAM stream) {
return stream.collect(AVL_TREE_SET::new, AVL_TREE_SET::add, AVL_TREE_SET::addAll);
}
#endif
#endif
#if !TYPE_OBJECT #if !TYPE_OBJECT
@Override @Override
public void setDefaultMaxValue(KEY_TYPE value) { defaultMaxNotFound = value; } public void setDefaultMaxValue(KEY_TYPE value) { defaultMaxNotFound = value; }
@@ -74,6 +74,16 @@ public abstract class ABSTRACT_SET KEY_GENERIC_TYPE extends ABSTRACT_COLLECTION
return set.iterator(); return set.iterator();
} }
@Override
public void addFirst(KEY_TYPE o) {
set.addLast(o);
}
@Override
public void addLast(KEY_TYPE o) {
set.addFirst(o);
}
@Override @Override
#if !TYPE_OBJECT #if !TYPE_OBJECT
public boolean remove(KEY_TYPE o) { public boolean remove(KEY_TYPE o) {
@@ -10,6 +10,12 @@ import java.util.NoSuchElementException;
import java.util.Objects; import java.util.Objects;
#if JDK_TYPE #if JDK_TYPE
import java.util.OPTIONAL; import java.util.OPTIONAL;
#if !TYPE_OBJECT
import java.util.stream.JAVA_STREAM;
#else
import java.util.stream.Stream;
import java.util.stream.Collector;
#endif
#endif #endif
import java.util.Set; import java.util.Set;
#if JDK_FUNCTION #if JDK_FUNCTION
@@ -74,7 +80,7 @@ public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE im
* @param array the array that should be used for set. * @param array the array that should be used for set.
*/ */
public ARRAY_SET(KEY_TYPE[] array) { public ARRAY_SET(KEY_TYPE[] array) {
this(array, array.length); this(array, 0, array.length);
} }
/** /**
@@ -88,6 +94,18 @@ public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE im
addAll(array, length); addAll(array, length);
} }
/**
* Constructur using initial Array
* @param array the array that should be used for set.
* @param offset the starting offset of where the array should be copied from
* @param length the amount of elements present within the array
* @throws NegativeArraySizeException if the length is negative
*/
public ARRAY_SET(KEY_TYPE[] array, int offset, int length) {
this(length);
addAll(array, offset, length);
}
/** /**
* A Helper constructor that allows to create a Set with exactly the same values as the provided collection. * A Helper constructor that allows to create a Set with exactly the same values as the provided collection.
* @param c the elements that should be added to the set. * @param c the elements that should be added to the set.
@@ -131,6 +149,42 @@ public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE im
for(ITERATOR KEY_GENERIC_TYPE iter = s.iterator();iter.hasNext();data[size++] = iter.NEXT()); for(ITERATOR KEY_GENERIC_TYPE iter = s.iterator();iter.hasNext();data[size++] = iter.NEXT());
} }
#if JDK_TYPE && SPLIT_ITERATOR_FEATURE && STREAM_FEATURE
#if TYPE_OBJECT
/**
* Creates a Collector for a ArraySet
* @Type(T)
* @return a collector
*/
public static <T> Collector<T, ARRAY_SET<T>, ARRAY_SET<T>> toList() {
return Collector.of(ARRAY_SET::new, ARRAY_SET::add, ARRAY_SET::merge);
}
/**
* Collects a Stream to a ArraySet
* @Type(T)
* @return a set with the contents of the Stream
*/
public static <T> ARRAY_SET KEY_GENERIC_TYPE toList(Stream<T> stream) {
return stream.collect(ARRAY_SET::new, ARRAY_SET::add, ARRAY_SET::merge);
}
private ARRAY_SET<T> merge(ARRAY_SET<T> a) {
addAll(a);
return this;
}
#else
/**
* Collects a Stream to a ArraySet
* @return a set with the contents of the Stream
*/
public static ARRAY_SET toList(JAVA_STREAM stream) {
return stream.collect(ARRAY_SET::new, ARRAY_SET::add, ARRAY_SET::addAll);
}
#endif
#endif
@Override @Override
public boolean add(KEY_TYPE o) { public boolean add(KEY_TYPE o) {
int index = findIndex(o); int index = findIndex(o);
@@ -153,6 +207,25 @@ public class ARRAY_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE im
} }
#endif #endif
@Override
public void addFirst(KEY_TYPE o) {
int index = findIndex(o);
if(index == -1) {
if(data.length == size) data = Arrays.copyOf(data, size == 0 ? 2 : size * 2);
System.arraycopy(data, 0, data, 1, size++);
data[0] = o;
}
}
@Override
public void addLast(KEY_TYPE o) {
int index = findIndex(o);
if(index == -1) {
if(data.length == size) data = Arrays.copyOf(data, size == 0 ? 2 : size * 2);
data[size++] = o;
}
}
@Override @Override
public boolean addAndMoveToFirst(KEY_TYPE o) { public boolean addAndMoveToFirst(KEY_TYPE o) {
int index = findIndex(o); int index = findIndex(o);
@@ -264,6 +264,10 @@ public class IMMUTABLE_HASH_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERI
@Override @Override
public boolean addAll(COLLECTION KEY_GENERIC_TYPE c) { throw new UnsupportedOperationException(); } public boolean addAll(COLLECTION KEY_GENERIC_TYPE c) { throw new UnsupportedOperationException(); }
@Override @Override
public void addFirst(KEY_TYPE o) { throw new UnsupportedOperationException(); }
@Override
public void addLast(KEY_TYPE o) { throw new UnsupportedOperationException(); }
@Override
public boolean addAndMoveToFirst(KEY_TYPE o) { throw new UnsupportedOperationException(); } public boolean addAndMoveToFirst(KEY_TYPE o) { throw new UnsupportedOperationException(); }
@Override @Override
public boolean addAndMoveToLast(KEY_TYPE o) { throw new UnsupportedOperationException(); } public boolean addAndMoveToLast(KEY_TYPE o) { throw new UnsupportedOperationException(); }
@@ -11,6 +11,12 @@ import java.util.Iterator;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
#if JDK_TYPE #if JDK_TYPE
import java.util.OPTIONAL; import java.util.OPTIONAL;
#if !TYPE_OBJECT
import java.util.stream.JAVA_STREAM;
#else
import java.util.stream.Stream;
import java.util.stream.Collector;
#endif
#endif #endif
#if JDK_FUNCTION #if JDK_FUNCTION
import java.util.function.PREDICATE; import java.util.function.PREDICATE;
@@ -241,6 +247,82 @@ public class LINKED_CUSTOM_HASH_SET KEY_GENERIC_TYPE extends CUSTOM_HASH_SET KEY
} }
#endif #endif
#if JDK_TYPE && SPLIT_ITERATOR_FEATURE && STREAM_FEATURE
#if TYPE_OBJECT
/**
* Creates a Collector for a LinkedCustomHashSet
* @Type(T)
* @return a collector
*/
public static <T> Collector<T, LINKED_CUSTOM_HASH_SET<T>, LINKED_CUSTOM_HASH_SET<T>> toLinkedSet(STRATEGY KEY_SUPER_GENERIC_TYPE strategy) {
return Collector.of(() -> new LINKED_CUSTOM_HASH_SET<>(strategy), LINKED_CUSTOM_HASH_SET::add, LINKED_CUSTOM_HASH_SET::merge);
}
/**
* Collects a Stream to a LinkedCustomHashSet
* @Type(T)
* @return a set with the contents of the Stream
*/
public static <T> LINKED_CUSTOM_HASH_SET KEY_GENERIC_TYPE toLinkedSet(Stream<T> stream, STRATEGY KEY_SUPER_GENERIC_TYPE strategy) {
return stream.collect(() -> new LINKED_CUSTOM_HASH_SET<>(strategy), LINKED_CUSTOM_HASH_SET::add, LINKED_CUSTOM_HASH_SET::merge);
}
private LINKED_CUSTOM_HASH_SET<T> merge(LINKED_CUSTOM_HASH_SET<T> a) {
addAll(a);
return this;
}
#else
/**
* Collects a Stream to a LinkedCustomHashSet
* @return a set with the contents of the Stream
*/
public static LINKED_CUSTOM_HASH_SET toList(JAVA_STREAM stream, STRATEGY KEY_SUPER_GENERIC_TYPE strategy) {
return stream.collect(() -> new LINKED_CUSTOM_HASH_SET(strategy), LINKED_CUSTOM_HASH_SET::add, LINKED_CUSTOM_HASH_SET::addAll);
}
#endif
#endif
@Override
public void addFirst(KEY_TYPE o) {
if(strategy.equals(o, EMPTY_KEY_VALUE)) {
if(containsNull) return;
containsNull = true;
onNodeAdded(nullIndex);
moveToFirstIndex(nullIndex);
}
else {
int pos = HashUtil.mix(strategy.hashCode(o)) & mask;
while(!strategy.equals(keys[pos], EMPTY_KEY_VALUE)) {
if(strategy.equals(keys[pos], o)) return;
pos = ++pos & mask;
}
keys[pos] = o;
onNodeAdded(pos);
moveToFirstIndex(pos);
}
if(size++ >= maxFill) rehash(HashUtil.arraySize(size+1, loadFactor));
}
@Override
public void addLast(KEY_TYPE o) {
if(strategy.equals(o, EMPTY_KEY_VALUE)) {
if(containsNull) return;
containsNull = true;
onNodeAdded(nullIndex);
}
else {
int pos = HashUtil.mix(strategy.hashCode(o)) & mask;
while(!strategy.equals(keys[pos], EMPTY_KEY_VALUE)) {
if(strategy.equals(keys[pos], o)) return;
pos = ++pos & mask;
}
keys[pos] = o;
onNodeAdded(pos);
}
if(size++ >= maxFill) rehash(HashUtil.arraySize(size+1, loadFactor));
}
@Override @Override
public boolean addAndMoveToFirst(KEY_TYPE o) { public boolean addAndMoveToFirst(KEY_TYPE o) {
if(strategy.equals(o, EMPTY_KEY_VALUE)) { if(strategy.equals(o, EMPTY_KEY_VALUE)) {
@@ -7,6 +7,12 @@ import java.util.NoSuchElementException;
import java.util.Objects; import java.util.Objects;
#if JDK_TYPE #if JDK_TYPE
import java.util.OPTIONAL; import java.util.OPTIONAL;
#if !TYPE_OBJECT
import java.util.stream.JAVA_STREAM;
#else
import java.util.stream.Stream;
import java.util.stream.Collector;
#endif
#endif #endif
#if TYPE_OBJECT #if TYPE_OBJECT
import java.util.function.Consumer; import java.util.function.Consumer;
@@ -212,6 +218,82 @@ public class LINKED_HASH_SET KEY_GENERIC_TYPE extends HASH_SET KEY_GENERIC_TYPE
} }
#endif #endif
#if JDK_TYPE && SPLIT_ITERATOR_FEATURE && STREAM_FEATURE
#if TYPE_OBJECT
/**
* Creates a Collector for a LinkedHashSet
* @Type(T)
* @return a collector
*/
public static <T> Collector<T, LINKED_HASH_SET<T>, LINKED_HASH_SET<T>> toLinkedSet() {
return Collector.of(LINKED_HASH_SET::new, LINKED_HASH_SET::add, LINKED_HASH_SET::merge);
}
/**
* Collects a Stream to a LinkedHashSet
* @Type(T)
* @return a set with the contents of the Stream
*/
public static <T> LINKED_HASH_SET KEY_GENERIC_TYPE toLinkedSet(Stream<T> stream) {
return stream.collect(LINKED_HASH_SET::new, LINKED_HASH_SET::add, LINKED_HASH_SET::merge);
}
private LINKED_HASH_SET<T> merge(LINKED_HASH_SET<T> a) {
addAll(a);
return this;
}
#else
/**
* Collects a Stream to a LinkedHashSet
* @return a set with the contents of the Stream
*/
public static LINKED_HASH_SET toLinkedSet(JAVA_STREAM stream) {
return stream.collect(LINKED_HASH_SET::new, LINKED_HASH_SET::add, LINKED_HASH_SET::addAll);
}
#endif
#endif
@Override
public void addFirst(KEY_TYPE o) {
if(KEY_EQUALS_NULL(o)) {
if(containsNull) return;
containsNull = true;
onNodeAdded(nullIndex);
moveToFirstIndex(nullIndex);
}
else {
int pos = HashUtil.mix(KEY_TO_HASH(o)) & mask;
while(KEY_EQUALS_NOT_NULL(keys[pos])) {
if(KEY_EQUALS(keys[pos], o)) return;
pos = ++pos & mask;
}
keys[pos] = o;
onNodeAdded(pos);
moveToFirstIndex(pos);
}
if(size++ >= maxFill) rehash(HashUtil.arraySize(size+1, loadFactor));
}
@Override
public void addLast(KEY_TYPE o) {
if(KEY_EQUALS_NULL(o)) {
if(containsNull) return;
containsNull = true;
onNodeAdded(nullIndex);
}
else {
int pos = HashUtil.mix(KEY_TO_HASH(o)) & mask;
while(KEY_EQUALS_NOT_NULL(keys[pos])) {
if(KEY_EQUALS(keys[pos], o)) return;
pos = ++pos & mask;
}
keys[pos] = o;
onNodeAdded(pos);
}
if(size++ >= maxFill) rehash(HashUtil.arraySize(size+1, loadFactor));
}
@Override @Override
public boolean addAndMoveToFirst(KEY_TYPE o) { public boolean addAndMoveToFirst(KEY_TYPE o) {
if(KEY_EQUALS_NULL(o)) { if(KEY_EQUALS_NULL(o)) {
@@ -8,6 +8,12 @@ import java.util.NoSuchElementException;
import java.util.Objects; import java.util.Objects;
#if JDK_TYPE #if JDK_TYPE
import java.util.OPTIONAL; import java.util.OPTIONAL;
#if !TYPE_OBJECT
import java.util.stream.JAVA_STREAM;
#else
import java.util.stream.Stream;
import java.util.stream.Collector;
#endif
#endif #endif
#if TYPE_OBJECT #if TYPE_OBJECT
import java.util.function.Consumer; import java.util.function.Consumer;
@@ -257,6 +263,42 @@ public class CUSTOM_HASH_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_T
while(iterator.hasNext()) add(iterator.NEXT()); while(iterator.hasNext()) add(iterator.NEXT());
} }
#endif
#if JDK_TYPE && SPLIT_ITERATOR_FEATURE && STREAM_FEATURE
#if TYPE_OBJECT
/**
* Creates a Collector for a CustomHashSet
* @Type(T)
* @return a collector
*/
public static <T> Collector<T, CUSTOM_HASH_SET<T>, CUSTOM_HASH_SET<T>> toSet(STRATEGY KEY_SUPER_GENERIC_TYPE strategy) {
return Collector.of(() -> new CUSTOM_HASH_SET<>(strategy), CUSTOM_HASH_SET::add, CUSTOM_HASH_SET::merge);
}
/**
* Collects a Stream to a CustomHashSet
* @Type(T)
* @return a set with the contents of the Stream
*/
public static <T> CUSTOM_HASH_SET KEY_GENERIC_TYPE toSet(Stream<T> stream, STRATEGY KEY_SUPER_GENERIC_TYPE strategy) {
return stream.collect(() -> new CUSTOM_HASH_SET<>(strategy), CUSTOM_HASH_SET::add, CUSTOM_HASH_SET::merge);
}
private CUSTOM_HASH_SET<T> merge(CUSTOM_HASH_SET<T> a) {
addAll(a);
return this;
}
#else
/**
* Collects a Stream to a CustomHashSet
* @return a set with the contents of the Stream
*/
public static CUSTOM_HASH_SET toSet(JAVA_STREAM stream, STRATEGY KEY_SUPER_GENERIC_TYPE strategy) {
return stream.collect(() -> new CUSTOM_HASH_SET(strategy), CUSTOM_HASH_SET::add, CUSTOM_HASH_SET::addAll);
}
#endif
#endif #endif
/** /**
* Helper getter function to get the current strategy * Helper getter function to get the current strategy
@@ -8,6 +8,12 @@ import java.util.NoSuchElementException;
import java.util.Objects; import java.util.Objects;
#if JDK_TYPE #if JDK_TYPE
import java.util.OPTIONAL; import java.util.OPTIONAL;
#if !TYPE_OBJECT
import java.util.stream.JAVA_STREAM;
#else
import java.util.stream.Stream;
import java.util.stream.Collector;
#endif
#endif #endif
#if TYPE_OBJECT #if TYPE_OBJECT
import java.util.function.Consumer; import java.util.function.Consumer;
@@ -224,6 +230,42 @@ public class HASH_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE imp
while(iterator.hasNext()) add(iterator.NEXT()); while(iterator.hasNext()) add(iterator.NEXT());
} }
#endif
#if JDK_TYPE && SPLIT_ITERATOR_FEATURE && STREAM_FEATURE
#if TYPE_OBJECT
/**
* Creates a Collector for a HashSet
* @Type(T)
* @return a collector
*/
public static <T> Collector<T, HASH_SET<T>, HASH_SET<T>> toSet() {
return Collector.of(HASH_SET::new, HASH_SET::add, HASH_SET::merge);
}
/**
* Collects a Stream to a HashSet
* @Type(T)
* @return a set with the contents of the Stream
*/
public static <T> HASH_SET KEY_GENERIC_TYPE toSet(Stream<T> stream) {
return stream.collect(HASH_SET::new, HASH_SET::add, HASH_SET::merge);
}
private HASH_SET<T> merge(HASH_SET<T> a) {
addAll(a);
return this;
}
#else
/**
* Collects a Stream to a HashSet
* @return a set with the contents of the Stream
*/
public static HASH_SET toSet(JAVA_STREAM stream) {
return stream.collect(HASH_SET::new, HASH_SET::add, HASH_SET::addAll);
}
#endif
#endif #endif
@Override @Override
public boolean add(KEY_TYPE o) { public boolean add(KEY_TYPE o) {
@@ -5,6 +5,7 @@ import java.util.SequencedSet;
#endif #endif
import speiger.src.collections.PACKAGE.collections.BI_ITERATOR; import speiger.src.collections.PACKAGE.collections.BI_ITERATOR;
import speiger.src.collections.PACKAGE.collections.ORDERED_COLLECTION;
#if SPLIT_ITERATOR_FEATURE #if SPLIT_ITERATOR_FEATURE
import speiger.src.collections.PACKAGE.collections.SPLIT_ITERATOR; import speiger.src.collections.PACKAGE.collections.SPLIT_ITERATOR;
import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS; import speiger.src.collections.PACKAGE.utils.SPLIT_ITERATORS;
@@ -23,9 +24,9 @@ import speiger.src.collections.PACKAGE.utils.SETS;
* @Type(T) * @Type(T)
*/ */
#if JAVA_VERSION>=21 #if JAVA_VERSION>=21
public interface ORDERED_SET KEY_GENERIC_TYPE extends SET KEY_GENERIC_TYPE, SequencedSet<CLASS_TYPE> public interface ORDERED_SET KEY_GENERIC_TYPE extends SET KEY_GENERIC_TYPE, ORDERED_COLLECTION KEY_GENERIC_TYPE, SequencedSet<CLASS_TYPE>
#else #else
public interface ORDERED_SET KEY_GENERIC_TYPE extends SET KEY_GENERIC_TYPE public interface ORDERED_SET KEY_GENERIC_TYPE extends SET KEY_GENERIC_TYPE, ORDERED_COLLECTION KEY_GENERIC_TYPE
#endif #endif
{ {
/** /**
@@ -4,6 +4,12 @@ import java.util.Collection;
import java.util.Collections; import java.util.Collections;
#if JDK_TYPE #if JDK_TYPE
import java.util.OPTIONAL; import java.util.OPTIONAL;
#if !TYPE_OBJECT
import java.util.stream.JAVA_STREAM;
#else
import java.util.stream.Stream;
import java.util.stream.Collector;
#endif
#endif #endif
#if TYPE_OBJECT #if TYPE_OBJECT
import java.util.Comparator; import java.util.Comparator;
@@ -214,6 +220,42 @@ public class RB_TREE_SET KEY_GENERIC_TYPE extends ABSTRACT_SET KEY_GENERIC_TYPE
while(iterator.hasNext()) add(iterator.NEXT()); while(iterator.hasNext()) add(iterator.NEXT());
} }
#if JDK_TYPE && SPLIT_ITERATOR_FEATURE && STREAM_FEATURE
#if TYPE_OBJECT
/**
* Creates a Collector for a RBTreeSet
* @Type(T)
* @return a collector
*/
public static <T> Collector<T, RB_TREE_SET<T>, RB_TREE_SET<T>> toSet() {
return Collector.of(RB_TREE_SET::new, RB_TREE_SET::add, RB_TREE_SET::merge);
}
/**
* Collects a Stream to a RBTreeSet
* @Type(T)
* @return a set with the contents of the Stream
*/
public static <T> RB_TREE_SET KEY_GENERIC_TYPE toSet(Stream<T> stream) {
return stream.collect(RB_TREE_SET::new, RB_TREE_SET::add, RB_TREE_SET::merge);
}
private RB_TREE_SET<T> merge(RB_TREE_SET<T> a) {
addAll(a);
return this;
}
#else
/**
* Collects a Stream to a RBTreeSet
* @return a set with the contents of the Stream
*/
public static RB_TREE_SET toSet(JAVA_STREAM stream) {
return stream.collect(RB_TREE_SET::new, RB_TREE_SET::add, RB_TREE_SET::addAll);
}
#endif
#endif
#if !TYPE_OBJECT #if !TYPE_OBJECT
@Override @Override
public void setDefaultMaxValue(KEY_TYPE value) { defaultMaxNotFound = value; } public void setDefaultMaxValue(KEY_TYPE value) { defaultMaxNotFound = value; }
@@ -17,6 +17,7 @@ import java.util.function.IntFunction;
#endif #endif
import speiger.src.collections.PACKAGE.collections.ITERATOR; import speiger.src.collections.PACKAGE.collections.ITERATOR;
import speiger.src.collections.utils.SanityChecks; import speiger.src.collections.utils.SanityChecks;
import speiger.src.collections.utils.Swapper;
/** /**
* A Helper class for Arrays * A Helper class for Arrays
@@ -337,6 +338,69 @@ public class ARRAYS
return array; return array;
} }
/**
* Simple Shuffle method for Arrays.
* With a Callback for indirect shuffling
* @param array the elements that should be shuffled
* @param swapper the callback on the swaps
* @ArrayType(T)
* @note This uses the SanityChecks#getRandom
* @return the provided sorted array
*/
public static GENERIC_KEY_BRACES KEY_TYPE[] indirectShuffle(KEY_TYPE[] array, Swapper swapper) {
return indirectShuffle(array, SanityChecks.getRandom(), swapper);
}
/**
* Simple Shuffle method for Arrays.
* With a Callback for indirect shuffling
* @param array the elements that should be shuffled
* @param random the Random Number Generator that should be used for the shuffling
* @param swapper the callback on the swaps
* @ArrayType(T)
* @return the provided sorted array
*/
public static GENERIC_KEY_BRACES KEY_TYPE[] indirectShuffle(KEY_TYPE[] array, RANDOM random, Swapper swapper) {
return indirectShuffle(array, 0, array.length, random, swapper);
}
/**
* Simple Shuffle method for Arrays.
* With a Callback for indirect shuffling
* @param array the elements that should be shuffled
* @param length the length of the array
* @param random the Random Number Generator that should be used for the shuffling
* @param swapper the callback on the swaps
* @ArrayType(T)
* @return the provided sorted array
*/
public static GENERIC_KEY_BRACES KEY_TYPE[] indirectShuffle(KEY_TYPE[] array, int length, RANDOM random, Swapper swapper) {
return indirectShuffle(array, 0, length, random, swapper);
}
/**
* Simple Shuffle method for Arrays.
* With a Callback for indirect shuffling
* @param array the elements that should be shuffled
* @param offset the start array
* @param length the length of the array
* @param random the Random Number Generator that should be used for the shuffling
* @param swapper the callback on the swaps
* @ArrayType(T)
* @return the provided sorted array
*/
public static GENERIC_KEY_BRACES KEY_TYPE[] indirectShuffle(KEY_TYPE[] array, int offset, int length, RANDOM random, Swapper swapper) {
for(int i = length-1; i>=0;i--) {
int j = offset + i;
int p = offset + random.nextInt(i + 1);
swapper.swap(j, p);
KEY_TYPE t = array[j];
array[j] = array[p];
array[p] = t;
}
return array;
}
/** /**
* Simple Array Reversal method * Simple Array Reversal method
* @param array the Array that should flip * @param array the Array that should flip
@@ -575,6 +639,55 @@ public class ARRAYS
} }
} }
/**
* Sorts the specified range of elements according to the order induced by the specified comparator using Insertion Sort,
* On top of that allows to sort other things along with it.
* @param array the array that needs to be sorted
* @param comp the Comparator that decides the sorting order
* @param swapper the callback which elements were swapped
* @ArrayType(T)
* @return input array
*/
public static GENERIC_KEY_BRACES KEY_TYPE[] indirectInsertionSort(KEY_TYPE[] array, COMPARATOR KEY_GENERIC_TYPE comp, Swapper swapper) {
indirectInsertionSort(array, 0, array.length, comp, swapper);
return array;
}
/**
* Sorts the specified range of elements according to the order induced by the specified comparator using Insertion Sort,
* On top of that allows to sort other things along with it.
* @param array the array that needs to be sorted
* @param length the maxmium size of the array to be sorted
* @param comp the Comparator that decides the sorting order
* @param swapper the callback which elements were swapped
* @ArrayType(T)
*/
public static GENERIC_KEY_BRACES void indirectInsertionSort(KEY_TYPE[] array, int length, COMPARATOR KEY_GENERIC_TYPE comp, Swapper swapper) {
indirectInsertionSort(array, 0, length, comp, swapper);
}
/**
* Sorts the specified range of elements according to the order induced by the specified comparator using Insertion Sort,
* On top of that allows to sort other things along with it.
* @param array the array that needs to be sorted
* @param from where the array should be sorted from
* @param to where the array should be sorted to
* @param comp the Comparator that decides the sorting order
* @param swapper the callback which elements were swapped
* @ArrayType(T)
*/
public static GENERIC_KEY_BRACES void indirectInsertionSort(KEY_TYPE[] array, int from, int to, COMPARATOR KEY_GENERIC_TYPE comp, Swapper swapper) {
for (int i = from+1;i<to; i++) {
KEY_TYPE current = array[i];
int j = i - 1;
while(j >= from && comp.compare(current, array[j]) < 0) {
swapper.swap(j+1, j);
array[j+1] = array[j--];
}
array[j+1] = current;
}
}
/** /**
* 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
@@ -661,6 +774,60 @@ public class ARRAYS
} }
} }
/**
* Sorts the specified range of elements according to the order induced by the specified comparator using Selection Sort,
* On top of that allows to sort other things along with it.
* @param array the array that needs to be sorted
* @param comp the Comparator that decides the sorting order
* @param swapper the callback which elements were swapped
* @ArrayType(T)
* @return input array
*/
public static GENERIC_KEY_BRACES KEY_TYPE[] indirectSelectionSort(KEY_TYPE[] array, COMPARATOR KEY_GENERIC_TYPE comp, Swapper swapper) {
indirectSelectionSort(array, 0, array.length, comp, swapper);
return array;
}
/**
* Sorts the specified range of elements according to the order induced by the specified comparator using Selection Sort,
* On top of that allows to sort other things along with it.
* @param array the array that needs to be sorted
* @param length the maxmium size of the array to be sorted
* @param comp the Comparator that decides the sorting order
* @param swapper the callback which elements were swapped
* @ArrayType(T)
*/
public static GENERIC_KEY_BRACES void indirectSelectionSort(KEY_TYPE[] array, int length, COMPARATOR KEY_GENERIC_TYPE comp, Swapper swapper) {
indirectSelectionSort(array, 0, length, comp, swapper);
}
/**
* Sorts the specified range of elements according to the order induced by the specified comparator using Selection Sort,
* On top of that allows to sort other things along with it.
* @param array the array that needs to be sorted
* @param from where the array should be sorted from
* @param to where the array should be sorted to
* @param comp the Comparator that decides the sorting order
* @param swapper the callback which elements were swapped
* @ArrayType(T)
*/
public static GENERIC_KEY_BRACES void indirectSelectionSort(KEY_TYPE[] array, int from, int to, COMPARATOR KEY_GENERIC_TYPE comp, Swapper swapper) {
for (int i = from; i < to; i++) {
KEY_TYPE min = array[i];
int minId = i;
for(int j = i+1; j < to; j++) {
if(comp.compare(array[j], min) < 0) {
min = array[j];
minId = j;
}
}
swapper.swap(i, minId);
KEY_TYPE temp = array[i];
array[i] = min;
array[minId] = temp;
}
}
/** /**
* 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
@@ -760,6 +927,72 @@ public class ARRAYS
} }
} }
/**
* Sorts the specified range of elements according to the order induced by the specified comparator using Merge Sort,
* On top of that allows to sort other things along with it.
* 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 comp the Comparator that decides the sorting order
* @param swapper the callback which elements were swapped
* @ArrayType(T)
* @return input array
*/
public static GENERIC_KEY_BRACES KEY_TYPE[] indirectMergeSort(KEY_TYPE[] array, COMPARATOR KEY_GENERIC_TYPE comp, Swapper swapper) {
indirectMergeSort(array, null, 0, array.length, comp, swapper);
return array;
}
/**
* Sorts the specified range of elements according to the order induced by the specified comparator using Merge Sort,
* On top of that allows to sort other things along with it.
* 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 length the maxmium size of the array to be sorted
* @param comp the Comparator that decides the sorting order
* @param swapper the callback which elements were swapped
* @ArrayType(T)
*/
public static GENERIC_KEY_BRACES void indirectMergeSort(KEY_TYPE[] array, int length, COMPARATOR KEY_GENERIC_TYPE comp, Swapper swapper) {
indirectMergeSort(array, null, 0, length, comp, swapper);
}
/**
* Sorts the specified range of elements according to the order induced by the specified comparator using Merge Sort,
* On top of that allows to sort other things along with it.
* 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 supp the auxillary array that is used to simplify the sorting
* @param from where the array should be sorted from
* @param to where the array should be sorted to
* @param comp the Comparator that decides the sorting order
* @param swapper the callback which elements were swapped
* @ArrayType(T)
*/
public static GENERIC_KEY_BRACES void indirectMergeSort(KEY_TYPE[] array, KEY_TYPE[] supp, int from, int to, COMPARATOR KEY_GENERIC_TYPE comp, Swapper swapper) {
if(to - from < BASE_THRESHOLD) {
indirectInsertionSort(array, from, to, comp, swapper);
return;
}
if(supp == null) supp = Arrays.copyOf(array, to);
int mid = (from + to) >>> 1;
indirectMergeSort(supp, array, from, mid, comp, swapper);
indirectMergeSort(supp, array, mid, to, comp, swapper);
if(comp.compare(supp[mid - 1], supp[mid]) <= 0)
{
System.arraycopy(supp, from, array, from, to - from);
return;
}
for(int p = from, q = mid;from < to;from++) {
if(q >= to || p < mid && comp.compare(supp[p], supp[q]) < 0) {
swapper.swap(from, p);
array[from] = supp[p++];
continue;
}
swapper.swap(from, q);
array[from] = supp[q++];
}
}
/** /**
* Sorts an array according to the natural ascending order using Merge Sort, * Sorts an array according to the natural ascending order using Merge Sort,
* 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
@@ -856,6 +1089,56 @@ public class ARRAYS
mergeSort(array, supp, from, to, comp); mergeSort(array, supp, from, to, comp);
} }
/**
* Sorts the specified range of elements according to the order induced by the specified comparator using a Parallel Merge Sort,
* On top of that allows to sort other things along with it.
* 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 comp the Comparator that decides the sorting order
* @param swapper the callback which elements were swapped
* @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed
* @ArrayType(T)
*/
public static GENERIC_KEY_BRACES void indirectParallelMergeSort(KEY_TYPE[] array, COMPARATOR KEY_GENERIC_TYPE comp, Swapper swapper) {
indirectParallelMergeSort(array, null, 0, array.length, comp, swapper);
}
/**
* Sorts the specified range of elements according to the order induced by the specified comparator using Parallel Merge Sort,
* On top of that allows to sort other things along with it.
* 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 length the maxmium size of the array to be sorted
* @param swapper the callback which elements were swapped
* @param comp the Comparator that decides the sorting order
* @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed
* @ArrayType(T)
*/
public static GENERIC_KEY_BRACES void indirectParallelMergeSort(KEY_TYPE[] array, int length, COMPARATOR KEY_GENERIC_TYPE comp, Swapper swapper) {
indirectParallelMergeSort(array, null, 0, length, comp, swapper);
}
/**
* Sorts the specified range of elements according to the order induced by the specified comparator using Parallel Merge Sort,
* On top of that allows to sort other things along with it.
* 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 supp the auxillary array that is used to simplify the sorting
* @param from where the array should be sorted from
* @param to where the array should be sorted to
* @param comp the Comparator that decides the sorting order
* @param swapper the callback which elements were swapped
* @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed
* @ArrayType(T)
*/
public static GENERIC_KEY_BRACES void indirectParallelMergeSort(KEY_TYPE[] array, KEY_TYPE[] supp, int from, int to, COMPARATOR KEY_GENERIC_TYPE comp, Swapper swapper) {
if(SanityChecks.canParallelTask() && to - from >= PARALLEL_THRESHOLD) {
SanityChecks.invokeTask(new MergeSortActionCompSwapBRACES(array, supp, from, to, comp, swapper));
return;
}
indirectMergeSort(array, supp, from, to, comp, swapper);
}
/** /**
* Sorts an array according to the natural ascending order using Parallel Merge Sort, * Sorts an array according to the natural ascending order using Parallel Merge Sort,
* 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
@@ -1209,6 +1492,73 @@ public class ARRAYS
if((length = d - c) > 1) quickSort(array, to - length, to, comp); if((length = d - c) > 1) quickSort(array, to - length, to, comp);
} }
/**
* Sorts the specified range of elements according to the order induced by the specified comparator using Quick Sort,
* On top of that allows to sort other things along with it.
* This implementation is a custom of <a href="https://github.com/vigna/fastutil">FastUtil</a> quicksort but with a different code structure,
* 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 comp the Comparator that decides the sorting order
* @param swapper the callback which elements were swapped
* @ArrayType(T)
* @return input array
*/
public static GENERIC_KEY_BRACES KEY_TYPE[] indirectQuickSort(KEY_TYPE[] array, COMPARATOR KEY_GENERIC_TYPE comp, Swapper swapper) {
indirectQuickSort(array, 0, array.length, comp, swapper);
return array;
}
/**
* Sorts the specified range of elements according to the order induced by the specified comparator using Quick Sort,
* On top of that allows to sort other things along with it.
* This implementation is a custom of <a href="https://github.com/vigna/fastutil">FastUtil</a> quicksort but with a different code structure,
* 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 length the maxmium size of the array to be sorted
* @param comp the Comparator that decides the sorting order
* @param swapper the callback which elements were swapped
* @ArrayType(T)
*/
public static GENERIC_KEY_BRACES void indirectQuickSort(KEY_TYPE[] array, int length, COMPARATOR KEY_GENERIC_TYPE comp, Swapper swapper) {
indirectQuickSort(array, 0, length, comp, swapper);
}
/**
* Sorts the specified range of elements according to the order induced by the specified comparator using Quick Sort,
* On top of that allows to sort other things along with it.
* This implementation is a custom of <a href="https://github.com/vigna/fastutil">FastUtil</a> quicksort but with a different code structure,
* 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 from where the array should be sorted from
* @param to where the array should be sorted to
* @param comp the Comparator that decides the sorting order
* @param swapper the callback which elements were swapped
* @ArrayType(T)
*/
public static GENERIC_KEY_BRACES void indirectQuickSort(KEY_TYPE[] array, int from, int to, COMPARATOR KEY_GENERIC_TYPE comp, Swapper swapper) {
int length = to - from;
if(length <= 0) return;
if(length < BASE_THRESHOLD) {
indirectSelectionSort(array, from, to, comp, swapper);
return;
}
KEY_TYPE pivot = array[length > 128 ? subMedium(array, from, from + (length / 2), to - 1, length / 8, comp) : medium(array, from, from + (length / 2), to - 1, comp)];
int a = from, b = a, c = to - 1, d = c;
for(int compare;;swap(array, b++, c--, swapper)) {
for(;b<=c && (compare = comp.compare(array[b], pivot)) <= 0;b++) {
if(compare == 0) swap(array, a++, b, swapper);
}
for(;c>=b && (compare = comp.compare(array[c], pivot)) >= 0;c--) {
if(compare == 0) swap(array, c, d--, swapper);
}
if(b>c) break;
}
swap(array, from, b, Math.min(a - from, b - a), swapper);
swap(array, b, to, Math.min(d - c, to - d - 1), swapper);
if((length = b - a) > 1) indirectQuickSort(array, from, from + length, comp, swapper);
if((length = d - c) > 1) indirectQuickSort(array, to - length, to, comp, swapper);
}
/** /**
* Sorts an array according to the natural ascending order using Quick Sort, * Sorts an array according to the natural ascending order using Quick Sort,
* This implementation is a custom of <a href="https://github.com/vigna/fastutil">FastUtil</a> quicksort but with a different code structure, * This implementation is a custom of <a href="https://github.com/vigna/fastutil">FastUtil</a> quicksort but with a different code structure,
@@ -1313,6 +1663,58 @@ public class ARRAYS
quickSort(array, from, to, comp); quickSort(array, from, to, comp);
} }
/**
* Sorts the specified range of elements according to the order induced by the specified comparator using Parallel Quick Sort,
* On top of that allows to sort other things along with it.
* This implementation is a custom of <a href="https://github.com/vigna/fastutil">FastUtil</a> quicksort but with a different code structure,
* 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 comp the Comparator that decides the sorting order
* @param swapper the callback which elements were swapped
* @ArrayType(T)
* @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed
*/
public static GENERIC_KEY_BRACES void indirectParallelQuickSort(KEY_TYPE[] array, COMPARATOR KEY_GENERIC_TYPE comp, Swapper swapper) {
indirectParallelQuickSort(array, 0, array.length, comp, swapper);
}
/**
* Sorts the specified range of elements according to the order induced by the specified comparator using Parallel Quick Sort,
* On top of that allows to sort other things along with it.
* This implementation is a custom of <a href="https://github.com/vigna/fastutil">FastUtil</a> quicksort but with a different code structure,
* 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 length the maxmium size of the array to be sorted
* @param comp the Comparator that decides the sorting order
* @param swapper the callback which elements were swapped
* @ArrayType(T)
* @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed
*/
public static GENERIC_KEY_BRACES void indirectParallelQuickSort(KEY_TYPE[] array, int length, COMPARATOR KEY_GENERIC_TYPE comp, Swapper swapper) {
indirectParallelQuickSort(array, 0, length, comp, swapper);
}
/**
* Sorts the specified range of elements according to the order induced by the specified comparator using Parallel Quick Sort,
* On top of that allows to sort other things along with it.
* This implementation is a custom of <a href="https://github.com/vigna/fastutil">FastUtil</a> quicksort but with a different code structure,
* 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 from where the array should be sorted from
* @param to where the array should be sorted to
* @param comp the Comparator that decides the sorting order
* @param swapper the callback which elements were swapped
* @ArrayType(T)
* @note This parallelization is invoked through {@link SanityChecks#invokeTask} which the threadpool can be changed as needed
*/
public static GENERIC_KEY_BRACES void indirectParallelQuickSort(KEY_TYPE[] array, int from, int to, COMPARATOR KEY_GENERIC_TYPE comp, Swapper swapper) {
if(SanityChecks.canParallelTask() && to - from >= PARALLEL_THRESHOLD) {
SanityChecks.invokeTask(new QuickSortActionCompSwapBRACES(array, from, to, comp, swapper));
return;
}
indirectQuickSort(array, from, to, comp, swapper);
}
/** /**
* Sorts an array according to the natural ascending order using Parallel Quick Sort, * Sorts an array according to the natural ascending order using Parallel Quick Sort,
* This implementation is a custom of <a href="https://github.com/vigna/fastutil">FastUtil</a> quicksort but with a different code structure, * This implementation is a custom of <a href="https://github.com/vigna/fastutil">FastUtil</a> quicksort but with a different code structure,
@@ -1367,6 +1769,18 @@ public class ARRAYS
for(int i = 0;i<length;i++,swap(a, from++, to++)); for(int i = 0;i<length;i++,swap(a, from++, to++));
} }
static GENERIC_KEY_BRACES void swap(KEY_TYPE[] a, int from, int to, Swapper swapper) {
swapper.swap(from, to);
KEY_TYPE t = a[from];
a[from] = a[to];
a[to] = t;
}
static GENERIC_KEY_BRACES void swap(KEY_TYPE[] a, int from, int to, int length, Swapper swapper) {
to -= length;
for(int i = 0;i<length;i++,swap(a, from++, to++, swapper));
}
static GENERIC_KEY_BRACES int subMedium(KEY_TYPE[] data, int a, int b, int c, int length, COMPARATOR KEY_GENERIC_TYPE comp) { static GENERIC_KEY_BRACES int subMedium(KEY_TYPE[] data, int a, int b, int c, int length, COMPARATOR KEY_GENERIC_TYPE comp) {
return medium(data, medium(data, a, a + length, a + (length * 2), comp), medium(data, b - length, b, b + length, comp), medium(data, c - (length * 2), c - length, c, comp), comp); return medium(data, medium(data, a, a + length, a + (length * 2), comp), medium(data, b - length, b, b + length, comp), medium(data, c - (length * 2), c - length, c, comp), comp);
} }
@@ -1389,16 +1803,14 @@ public class ARRAYS
int from; int from;
int to; int to;
QuickSortAction(KEY_TYPE[] array, int from, int to) QuickSortAction(KEY_TYPE[] array, int from, int to) {
{
this.array = array; this.array = array;
this.from = from; this.from = from;
this.to = to; this.to = to;
} }
@Override @Override
protected void compute() protected void compute() {
{
int length = to - from; int length = to - from;
if(length <= 0) return; if(length <= 0) return;
if(length < BASE_THRESHOLD) { if(length < BASE_THRESHOLD) {
@@ -1431,8 +1843,7 @@ public class ARRAYS
int to; int to;
COMPARATOR KEY_GENERIC_TYPE comp; COMPARATOR KEY_GENERIC_TYPE comp;
QuickSortActionComp(KEY_TYPE[] array, int from, int to, COMPARATOR KEY_GENERIC_TYPE comp) QuickSortActionComp(KEY_TYPE[] array, int from, int to, COMPARATOR KEY_GENERIC_TYPE comp) {
{
this.array = array; this.array = array;
this.from = from; this.from = from;
this.to = to; this.to = to;
@@ -1440,8 +1851,7 @@ public class ARRAYS
} }
@Override @Override
protected void compute() protected void compute() {
{
int length = to - from; int length = to - from;
if(length <= 0) return; if(length <= 0) return;
if(length < BASE_THRESHOLD) { if(length < BASE_THRESHOLD) {
@@ -1467,6 +1877,49 @@ public class ARRAYS
} }
} }
static class QuickSortActionCompSwap KEY_GENERIC_TYPE extends RecursiveAction {
private static final long serialVersionUID = 0L;
KEY_TYPE[] array;
int from;
int to;
COMPARATOR KEY_GENERIC_TYPE comp;
Swapper swapper;
QuickSortActionCompSwap(KEY_TYPE[] array, int from, int to, COMPARATOR KEY_GENERIC_TYPE comp, Swapper swapper) {
this.array = array;
this.from = from;
this.to = to;
this.comp = comp;
this.swapper = swapper;
}
@Override
protected void compute() {
int length = to - from;
if(length <= 0) return;
if(length < BASE_THRESHOLD) {
indirectSelectionSort(array, from, to, comp, swapper);
return;
}
KEY_TYPE pivot = array[length > 128 ? subMedium(array, from, from + (length / 2), to - 1, length / 8, comp) : medium(array, from, from + (length / 2), to - 1, comp)];
int a = from, b = a, c = to - 1, d = c;
for(int compare;;swap(array, b++, c--, swapper)) {
for(;b<=c && (compare = comp.compare(array[b], pivot)) <= 0;b++) {
if(compare == 0) swap(array, a++, b, swapper);
}
for(;c>=b && (compare = comp.compare(array[c], pivot)) >= 0;c--) {
if(compare == 0) swap(array, c, d--, swapper);
}
if(b>c) break;
}
swap(array, from, b, Math.min(a - from, b - a), swapper);
swap(array, b, to, Math.min(d - c, to - d - 1), swapper);
if(b - a > 1 && d - c > 1) invokeAll(new QuickSortActionCompSwapBRACES(array, from, from + (b - a), comp, swapper), new QuickSortActionCompSwapBRACES(array, to - (d - c), to, comp, swapper));
else if(b - a > 1) new QuickSortActionCompSwapBRACES(array, from, from + (b - a), comp, swapper).invoke();
else if(d - c > 1) new QuickSortActionCompSwapBRACES(array, to - (d - c), to, comp, swapper).invoke();
}
}
static class MergeSortAction KEY_GENERIC_TYPE extends RecursiveAction { static class MergeSortAction KEY_GENERIC_TYPE extends RecursiveAction {
private static final long serialVersionUID = 0L; private static final long serialVersionUID = 0L;
KEY_TYPE[] array; KEY_TYPE[] array;
@@ -1474,8 +1927,7 @@ public class ARRAYS
int from; int from;
int to; int to;
MergeSortAction(KEY_TYPE[] array, KEY_TYPE[] supp, int from, int to) MergeSortAction(KEY_TYPE[] array, KEY_TYPE[] supp, int from, int to) {
{
this.array = array; this.array = array;
this.supp = supp; this.supp = supp;
this.from = from; this.from = from;
@@ -1483,8 +1935,7 @@ public class ARRAYS
} }
@Override @Override
protected void compute() protected void compute() {
{
if(to - from < BASE_THRESHOLD) { if(to - from < BASE_THRESHOLD) {
insertionSort(array, from, to); insertionSort(array, from, to);
return; return;
@@ -1512,8 +1963,7 @@ public class ARRAYS
int to; int to;
COMPARATOR KEY_GENERIC_TYPE comp; COMPARATOR KEY_GENERIC_TYPE comp;
MergeSortActionComp(KEY_TYPE[] array, KEY_TYPE[] supp, int from, int to, COMPARATOR KEY_GENERIC_TYPE comp) MergeSortActionComp(KEY_TYPE[] array, KEY_TYPE[] supp, int from, int to, COMPARATOR KEY_GENERIC_TYPE comp) {
{
this.array = array; this.array = array;
this.supp = supp; this.supp = supp;
this.from = from; this.from = from;
@@ -1522,8 +1972,7 @@ public class ARRAYS
} }
@Override @Override
protected void compute() protected void compute() {
{
if(to - from < BASE_THRESHOLD) { if(to - from < BASE_THRESHOLD) {
insertionSort(array, from, to, comp); insertionSort(array, from, to, comp);
return; return;
@@ -1543,22 +1992,64 @@ public class ARRAYS
} }
} }
static class MergeSortActionCompSwap KEY_GENERIC_TYPE extends RecursiveAction {
private static final long serialVersionUID = 0L;
KEY_TYPE[] array;
KEY_TYPE[] supp;
int from;
int to;
COMPARATOR KEY_GENERIC_TYPE comp;
Swapper swapper;
MergeSortActionCompSwap(KEY_TYPE[] array, KEY_TYPE[] supp, int from, int to, COMPARATOR KEY_GENERIC_TYPE comp, Swapper swapper) {
this.array = array;
this.supp = supp;
this.from = from;
this.to = to;
this.comp = comp;
this.swapper = swapper;
}
@Override
protected void compute() {
if(to - from < BASE_THRESHOLD) {
indirectInsertionSort(array, from, to, comp, swapper);
return;
}
if(supp == null) supp = Arrays.copyOf(array, to);
int mid = (from + to) >>> 1;
invokeAll(new MergeSortActionCompSwapBRACES(supp, array, from, mid, comp, swapper), new MergeSortActionCompSwapBRACES(supp, array, mid, to, comp, swapper));
if(comp.compare(supp[mid - 1], supp[mid]) <= 0)
{
System.arraycopy(supp, from, array, from, to - from);
return;
}
for(int p = from, q = mid;from < to;from++) {
if(q >= to || p < mid && comp.compare(supp[p], supp[q]) < 0) {
swapper.swap(from, p);
array[from] = supp[p++];
continue;
}
swapper.swap(from, q);
array[from] = supp[q++];
}
}
}
static class MemFreeMergeSortAction KEY_GENERIC_TYPE extends RecursiveAction { static class MemFreeMergeSortAction KEY_GENERIC_TYPE extends RecursiveAction {
private static final long serialVersionUID = 0L; private static final long serialVersionUID = 0L;
KEY_TYPE[] array; KEY_TYPE[] array;
int from; int from;
int to; int to;
MemFreeMergeSortAction(KEY_TYPE[] array, int from, int to) MemFreeMergeSortAction(KEY_TYPE[] array, int from, int to) {
{
this.array = array; this.array = array;
this.from = from; this.from = from;
this.to = to; this.to = to;
} }
@Override @Override
protected void compute() protected void compute() {
{
if(to - from < BASE_THRESHOLD) { if(to - from < BASE_THRESHOLD) {
insertionSort(array, from, to); insertionSort(array, from, to);
return; return;
@@ -1604,8 +2095,7 @@ public class ARRAYS
int to; int to;
COMPARATOR KEY_GENERIC_TYPE comp; COMPARATOR KEY_GENERIC_TYPE comp;
MemFreeMergeSortActionComp(KEY_TYPE[] array, int from, int to, COMPARATOR KEY_GENERIC_TYPE comp) MemFreeMergeSortActionComp(KEY_TYPE[] array, int from, int to, COMPARATOR KEY_GENERIC_TYPE comp) {
{
this.array = array; this.array = array;
this.from = from; this.from = from;
this.to = to; this.to = to;
@@ -1613,8 +2103,7 @@ public class ARRAYS
} }
@Override @Override
protected void compute() protected void compute() {
{
if(to - from < BASE_THRESHOLD) { if(to - from < BASE_THRESHOLD) {
insertionSort(array, from, to, comp); insertionSort(array, from, to, comp);
return; return;
@@ -7,6 +7,11 @@ 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 JDK_TYPE
import java.util.OPTIONAL;
#else
import speiger.src.collections.PACKAGE.functions.OPTIONAL;
#endif
#if !TYPE_OBJECT #if !TYPE_OBJECT
import speiger.src.collections.PACKAGE.functions.CONSUMER; import speiger.src.collections.PACKAGE.functions.CONSUMER;
@@ -299,9 +304,8 @@ public class ASYNC_BUILDER KEY_GENERIC_TYPE
* @param operator that reduces the elements. * @param operator that reduces the elements.
* @return self with the reduce action applied * @return self with the reduce action applied
*/ */
public ASYNC_BUILDER KEY_GENERIC_TYPE reduce(UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { public ObjectAsyncBuilder<OPTIONAL KEY_GENERIC_TYPE> reduce(UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
task = new SimpleReduceTaskBRACES(iterable.iterator(), operator); return new ObjectAsyncBuilder<>(new SimpleReduceTaskBRACES(iterable.iterator(), operator));
return this;
} }
#if TYPE_OBJECT #if TYPE_OBJECT
@@ -435,9 +439,8 @@ public class ASYNC_BUILDER KEY_GENERIC_TYPE
* @param filter that decides the desired elements * @param filter that decides the desired elements
* @return self with the findFirst function applied * @return self with the findFirst function applied
*/ */
public ASYNC_BUILDER KEY_GENERIC_TYPE findFirst(PREDICATE KEY_GENERIC_TYPE filter) { public ObjectAsyncBuilder<OPTIONAL KEY_GENERIC_TYPE> findFirst(PREDICATE KEY_GENERIC_TYPE filter) {
task = new FindFirstTaskBRACES(iterable.iterator(), filter); return new ObjectAsyncBuilder<>(new FindFirstTaskBRACES(iterable.iterator(), filter));
return this;
} }
#if INT_ASYNC_MODULE #if INT_ASYNC_MODULE
@@ -590,7 +593,7 @@ public class ASYNC_BUILDER KEY_GENERIC_TYPE
} }
#endif #endif
private static class SimpleReduceTask KEY_GENERIC_TYPE extends BASE_TASK KEY_GENERIC_TYPE private static class SimpleReduceTask KEY_GENERIC_TYPE extends BaseObjectTask<OPTIONAL KEY_GENERIC_TYPE>
{ {
ITERATOR KEY_GENERIC_TYPE iter; ITERATOR KEY_GENERIC_TYPE iter;
UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator; UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator;
@@ -600,6 +603,7 @@ public class ASYNC_BUILDER KEY_GENERIC_TYPE
public SimpleReduceTask(ITERATOR KEY_GENERIC_TYPE iter, UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) { public SimpleReduceTask(ITERATOR KEY_GENERIC_TYPE iter, UNARY_OPERATOR KEY_KEY_GENERIC_TYPE operator) {
this.iter = iter; this.iter = iter;
this.operator = operator; this.operator = operator;
this.setResult(OPTIONAL.empty());
} }
@Override @Override
@@ -614,7 +618,7 @@ public class ASYNC_BUILDER KEY_GENERIC_TYPE
} }
} }
if(!iter.hasNext()) { if(!iter.hasNext()) {
setResult(value); setResult(OPTIONAL.GET_OPTIONAL(value));
return true; return true;
} }
return false; return false;
@@ -689,7 +693,7 @@ public class ASYNC_BUILDER KEY_GENERIC_TYPE
} }
#endif #endif
private static class FindFirstTask KEY_GENERIC_TYPE extends BASE_TASK KEY_GENERIC_TYPE private static class FindFirstTask KEY_GENERIC_TYPE extends BaseObjectTask<OPTIONAL KEY_GENERIC_TYPE>
{ {
ITERATOR KEY_GENERIC_TYPE iter; ITERATOR KEY_GENERIC_TYPE iter;
PREDICATE KEY_GENERIC_TYPE filter; PREDICATE KEY_GENERIC_TYPE filter;
@@ -697,6 +701,7 @@ public class ASYNC_BUILDER KEY_GENERIC_TYPE
public FindFirstTask(ITERATOR KEY_GENERIC_TYPE iter, PREDICATE KEY_GENERIC_TYPE filter) { public FindFirstTask(ITERATOR KEY_GENERIC_TYPE iter, PREDICATE KEY_GENERIC_TYPE filter) {
this.iter = iter; this.iter = iter;
this.filter = filter; this.filter = filter;
this.setResult(OPTIONAL.empty());
} }
@Override @Override
@@ -704,7 +709,7 @@ public class ASYNC_BUILDER KEY_GENERIC_TYPE
while(shouldRun() && iter.hasNext()) { while(shouldRun() && iter.hasNext()) {
KEY_TYPE entry = iter.NEXT(); KEY_TYPE entry = iter.NEXT();
if(filter.test(iter.NEXT())) { if(filter.test(iter.NEXT())) {
setResult(entry); setResult(OPTIONAL.GET_OPTIONAL(entry));
return true; return true;
} }
} }
@@ -147,7 +147,10 @@ public class COLLECTIONS
return new SingletonCollectionBRACES(element); return new SingletonCollectionBRACES(element);
} }
protected static GENERIC_KEY_BRACES CollectionWrapper KEY_GENERIC_TYPE wrapper() { /**
* Internal Use mainly. Its a collection wrapper with 0 dependencies for those actions where a collector is needed.
*/
public static GENERIC_KEY_BRACES CollectionWrapper KEY_GENERIC_TYPE wrapper() {
return new CollectionWrapperBRACES(); return new CollectionWrapperBRACES();
} }
@@ -360,6 +360,10 @@ public class SETS
s = c; s = c;
} }
@Override
public void addFirst(KEY_TYPE o) { throw new UnsupportedOperationException(); }
@Override
public void addLast(KEY_TYPE o) { throw new UnsupportedOperationException(); }
@Override @Override
public boolean addAndMoveToFirst(KEY_TYPE o) { throw new UnsupportedOperationException(); } public boolean addAndMoveToFirst(KEY_TYPE o) { throw new UnsupportedOperationException(); }
@Override @Override
@@ -651,6 +655,10 @@ public class SETS
s = c; s = c;
} }
@Override
public void addFirst(KEY_TYPE o) { synchronized(mutex) { s.addFirst(o); } }
@Override
public void addLast(KEY_TYPE o) { synchronized(mutex) { s.addLast(o); } }
@Override @Override
public boolean addAndMoveToFirst(KEY_TYPE o) { synchronized(mutex) { return s.addAndMoveToFirst(o); } } public boolean addAndMoveToFirst(KEY_TYPE o) { synchronized(mutex) { return s.addAndMoveToFirst(o); } }
@Override @Override
@@ -755,6 +755,10 @@ public class MAPS
set = c; set = c;
} }
@Override
public void addFirst(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); }
@Override
public void addLast(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); }
@Override @Override
public boolean addAndMoveToFirst(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); } public boolean addAndMoveToFirst(MAP.Entry KEY_VALUE_GENERIC_TYPE o) { throw new UnsupportedOperationException(); }
@Override @Override
@@ -20,6 +20,7 @@ import speiger.src.testers.PACKAGE.generators.maps.TEST_ORDERED_MAP_GENERATOR;
import speiger.src.testers.PACKAGE.impl.maps.DERIVED_MAP_GENERATORS; import speiger.src.testers.PACKAGE.impl.maps.DERIVED_MAP_GENERATORS;
import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEOrderedMapMoveTester; import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEOrderedMapMoveTester;
import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEOrderedMapNavigationTester; import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEOrderedMapNavigationTester;
import speiger.src.testers.PACKAGE.tests.maps.FILE_KEY_TYPE2FILE_VALUE_TYPEOrderedMapPutTester;
#if !TYPE_OBJECT #if !TYPE_OBJECT
import speiger.src.testers.objects.builder.ObjectSetTestSuiteBuilder; import speiger.src.testers.objects.builder.ObjectSetTestSuiteBuilder;
import speiger.src.testers.objects.generators.TestObjectSetGenerator; import speiger.src.testers.objects.generators.TestObjectSetGenerator;
@@ -41,6 +42,7 @@ public class ORDERED_MAP_TEST_BUILDER KEY_VALUE_GENERIC_TYPE extends MAP_TEST_BU
List<Class<? extends AbstractTester>> testers = super.getTesters(); List<Class<? extends AbstractTester>> testers = super.getTesters();
testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEOrderedMapMoveTester.class); testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEOrderedMapMoveTester.class);
testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEOrderedMapNavigationTester.class); testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEOrderedMapNavigationTester.class);
testers.add(FILE_KEY_TYPE2FILE_VALUE_TYPEOrderedMapPutTester.class);
return testers; return testers;
} }
@@ -77,7 +79,7 @@ public class ORDERED_MAP_TEST_BUILDER KEY_VALUE_GENERIC_TYPE extends MAP_TEST_BU
features.addAll(parentBuilder.getFeatures()); features.addAll(parentBuilder.getFeatures());
features.remove(SpecialFeature.COPYING); features.remove(SpecialFeature.COPYING);
features.remove(SpecialFeature.CHILDREN_COPY); features.remove(SpecialFeature.CHILDREN_COPY);
return ORDERED_MAP_TEST_BUILDER.using(new DERIVED_MAP_GENERATORS.ReverseTestOrderedMapGenerator(delegate)) return ORDERED_MAP_TEST_BUILDER.using(new DERIVED_MAP_GENERATORS.ReverseTestOrderedMapGeneratorKV_BRACES(delegate))
.named(parentBuilder.getName() + " reversed").withFeatures(features) .named(parentBuilder.getName() + " reversed").withFeatures(features)
.suppressing(parentBuilder.getSuppressedTests()).createTestSuite(); .suppressing(parentBuilder.getSuppressedTests()).createTestSuite();
} }
@@ -27,6 +27,8 @@ import speiger.src.collections.PACKAGE.maps.impl.concurrent.CONCURRENT_HASH_MAP;
#if TYPE_OBJECT #if TYPE_OBJECT
import speiger.src.collections.PACKAGE.maps.impl.misc.ENUM_MAP; import speiger.src.collections.PACKAGE.maps.impl.misc.ENUM_MAP;
import speiger.src.collections.PACKAGE.maps.impl.misc.LINKED_ENUM_MAP; import speiger.src.collections.PACKAGE.maps.impl.misc.LINKED_ENUM_MAP;
import speiger.src.collections.PACKAGE.maps.impl.reference.REF_MAP;
import speiger.src.collections.PACKAGE.maps.impl.reference.LINKED_REF_MAP;
#endif #endif
import speiger.src.collections.PACKAGE.maps.impl.tree.RB_TREE_MAP; import speiger.src.collections.PACKAGE.maps.impl.tree.RB_TREE_MAP;
@@ -134,6 +136,97 @@ public class MAP_CONSTRUCTOR_TESTS
} }
#if TYPE_OBJECT #if TYPE_OBJECT
public static class RefMap extends FILE_KEY_TYPE2FILE_VALUE_TYPEMapConstructorTester KEY_VALUE_STRING_GENERIC_TYPE
{
public RefMap() {
setSimpleConstructor(REF_MAP::new);
setSizeConstructor(REF_MAP::new);
setPArrayConstructor(REF_MAP::new);
#if !TYPE_OBJECT || !VALUE_OBJECT
setArrayConstructor(REF_MAP::new);
#endif
setPMapConstructor(REF_MAP::new);
setMapConstructor(REF_MAP::new);
}
@Test
public void testWrongLoadFactorSize() {
setSizeConstructor(T -> new REF_MAP KEY_VALUE_STRING_GENERIC_TYPE(T, 0F));
try {
testSizeConstructor_smallSize();
fail("A Constructor using a 0 LoadFactor should error");
} catch(IllegalStateException e) {}
setSizeConstructor(T -> new REF_MAP KEY_VALUE_STRING_GENERIC_TYPE(T, 1F));
try {
testSizeConstructor_smallSize();
fail("A Constructor using a 1 LoadFactor should error");
} catch(IllegalStateException e) {}
}
#if TYPE_OBJECT
@Override
protected String[] createKeyElements() {
return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100);
}
#endif
#if VALUE_OBJECT
@Override
protected String[] createValueElements() {
return Arrays.copyOfRange(StringSortTest.NAMES, 100, 200);
}
#endif
}
public static class LinkedRefMap extends FILE_KEY_TYPE2FILE_VALUE_TYPEMapConstructorTester KEY_VALUE_STRING_GENERIC_TYPE
{
public LinkedRefMap() {
setSimpleConstructor(LINKED_REF_MAP::new);
setSizeConstructor(LINKED_REF_MAP::new);
setPArrayConstructor(LINKED_REF_MAP::new);
#if !TYPE_OBJECT || !VALUE_OBJECT
setArrayConstructor(LINKED_REF_MAP::new);
#endif
setPMapConstructor(LINKED_REF_MAP::new);
setMapConstructor(LINKED_REF_MAP::new);
}
@Test
public void testWrongLoadFactorSize() {
setSizeConstructor(T -> new LINKED_REF_MAP KEY_VALUE_STRING_GENERIC_TYPE(T, 0F));
try {
testSizeConstructor_smallSize();
fail("A Constructor using a 0 LoadFactor should error");
} catch(IllegalStateException e) {
}
setSizeConstructor(T -> new LINKED_REF_MAP KEY_VALUE_STRING_GENERIC_TYPE(T, 1F));
try {
testSizeConstructor_smallSize();
fail("A Constructor using a 1 LoadFactor should error");
} catch(IllegalStateException e) {
}
}
#if TYPE_OBJECT
@Override
protected String[] createKeyElements() {
return Arrays.copyOfRange(StringSortTest.NAMES, 0, 100);
}
#endif
#if VALUE_OBJECT
@Override
protected String[] createValueElements() {
return Arrays.copyOfRange(StringSortTest.NAMES, 100, 200);
}
#endif
}
#if VALUE_OBJECT #if VALUE_OBJECT
public static class EnumMap extends FILE_KEY_TYPE2FILE_VALUE_TYPEMapConstructorTester<AnEnum, String> public static class EnumMap extends FILE_KEY_TYPE2FILE_VALUE_TYPEMapConstructorTester<AnEnum, String>
#else #else
@@ -27,6 +27,7 @@ public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapContainsTester KEY_VALUE_GENERIC_TY
#ignore #ignore
@CollectionSize.Require(absent = ZERO) @CollectionSize.Require(absent = ZERO)
@SuppressWarnings("unlikely-arg-type")
#endignore #endignore
public void testContainsObject_yes() { public void testContainsObject_yes() {
assertTrue("contains(present) should return true", getMap().ENTRY_SET().contains(new AbstractMap.SimpleEntry<>(e0()))); assertTrue("contains(present) should return true", getMap().ENTRY_SET().contains(new AbstractMap.SimpleEntry<>(e0())));
@@ -36,6 +37,7 @@ public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapContainsTester KEY_VALUE_GENERIC_TY
assertFalse("contains(notPresent) should return false", getMap().ENTRY_SET().contains(e3())); assertFalse("contains(notPresent) should return false", getMap().ENTRY_SET().contains(e3()));
} }
@SuppressWarnings("unlikely-arg-type")
public void testContainsObject_no() { public void testContainsObject_no() {
assertFalse("contains(notPresent) should return false", getMap().ENTRY_SET().contains(new AbstractMap.SimpleEntry<>(e3()))); assertFalse("contains(notPresent) should return false", getMap().ENTRY_SET().contains(new AbstractMap.SimpleEntry<>(e3())));
} }
@@ -136,6 +136,7 @@ public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapRemoveEntryTester KEY_VALUE_GENERIC
#ignore #ignore
@CollectionSize.Require(ONE) @CollectionSize.Require(ONE)
@MapFeature.Require(SUPPORTS_REMOVE) @MapFeature.Require(SUPPORTS_REMOVE)
@SuppressWarnings("unlikely-arg-type")
#endignore #endignore
public void testRemove_supportedObjectEntryPresent() { public void testRemove_supportedObjectEntryPresent() {
assertTrue(getMap().ENTRY_SET().remove(new AbstractMap.SimpleEntry<>(e0()))); assertTrue(getMap().ENTRY_SET().remove(new AbstractMap.SimpleEntry<>(e0())));
@@ -154,6 +155,7 @@ public class FILE_KEY_TYPE2FILE_VALUE_TYPEMapRemoveEntryTester KEY_VALUE_GENERIC
#ignore #ignore
@CollectionSize.Require(ONE) @CollectionSize.Require(ONE)
@MapFeature.Require(SUPPORTS_REMOVE) @MapFeature.Require(SUPPORTS_REMOVE)
@SuppressWarnings("unlikely-arg-type")
#endignore #endignore
public void testRemove_supportedObjectEntryMissing() { public void testRemove_supportedObjectEntryMissing() {
assertFalse(getMap().ENTRY_SET().remove(new AbstractMap.SimpleEntry<>(e3()))); assertFalse(getMap().ENTRY_SET().remove(new AbstractMap.SimpleEntry<>(e3())));
@@ -0,0 +1,118 @@
package speiger.src.testers.PACKAGE.tests.maps;
#ignore
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT;
import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_REMOVE;
import static org.junit.Assert.assertNotEquals;
#endignore
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;
import speiger.src.collections.PACKAGE.maps.interfaces.MAP;
import speiger.src.collections.PACKAGE.maps.interfaces.ORDERED_MAP;
import speiger.src.collections.objects.lists.ObjectList;
import speiger.src.testers.PACKAGE.tests.base.maps.ABSTRACT_MAP_TESTER;
import speiger.src.testers.objects.utils.ObjectHelpers;
@SuppressWarnings("javadoc")
public class FILE_KEY_TYPE2FILE_VALUE_TYPEOrderedMapPutTester KEY_VALUE_GENERIC_TYPE extends ABSTRACT_MAP_TESTER KEY_VALUE_GENERIC_TYPE
{
private ORDERED_MAP KEY_VALUE_GENERIC_TYPE orderedMap;
private ObjectList<MAP.Entry KEY_VALUE_GENERIC_TYPE> values;
private KEY_TYPE a;
private VALUE_TYPE aValue;
@Override
public void setUp() throws Exception {
super.setUp();
orderedMap = (ORDERED_MAP KEY_VALUE_GENERIC_TYPE)getMap();
values = ObjectHelpers.copyToList(getSampleElements(getSubjectGenerator().getCollectionSize().getNumElements()));
if (values.size() >= 1) {
a = values.get(0).ENTRY_KEY();
aValue = values.get(0).ENTRY_VALUE();
}
}
#ignore
@MapFeature.Require(SUPPORTS_PUT)
@CollectionSize.Require(absent = ZERO)
#endignore
public void testPutFirst() {
assertEquals(aValue, orderedMap.putFirst(a, v3()));
assertNotEquals(v3(), orderedMap.FIRST_ENTRY_VALUE());
assertEquals(orderedMap.getDefaultReturnValue(), orderedMap.putFirst(k4(), v4()));
assertEquals(v4(), orderedMap.FIRST_ENTRY_VALUE());
assertEquals(e4(), orderedMap.firstEntry());
}
#ignore
@MapFeature.Require(SUPPORTS_PUT)
@CollectionSize.Require(absent = ZERO)
#endignore
public void testPutLast() {
assertEquals(aValue, orderedMap.putLast(a, v3()));
assertNotEquals(v3(), orderedMap.LAST_ENTRY_VALUE());
assertEquals(orderedMap.getDefaultReturnValue(), orderedMap.putLast(k4(), v4()));
assertEquals(v4(), orderedMap.LAST_ENTRY_VALUE());
assertEquals(e4(), orderedMap.lastEntry());
}
#ignore
@MapFeature.Require(SUPPORTS_REMOVE)
@CollectionSize.Require(CollectionSize.ONE)
#endignore
public void testPollFirst() {
assertFalse(orderedMap.isEmpty());
assertEquals(e0(), orderedMap.pollFirstEntry());
assertTrue(orderedMap.isEmpty());
}
#ignore
@MapFeature.Require(SUPPORTS_REMOVE)
@CollectionSize.Require(CollectionSize.ONE)
#endignore
public void testPollLast() {
assertFalse(orderedMap.isEmpty());
assertEquals(e0(), orderedMap.pollLastEntry());
assertTrue(orderedMap.isEmpty());
}
#ignore
@MapFeature.Require(absent = SUPPORTS_PUT)
#endignore
public void testUnsupportedPutFirst() {
try { orderedMap.putFirst(a, aValue); }
catch (UnsupportedOperationException tolerated) {}
expectUnchanged();
}
#ignore
@MapFeature.Require(absent = SUPPORTS_PUT)
#endignore
public void testUnsupportedPutLast() {
try { orderedMap.putLast(a, aValue); }
catch (UnsupportedOperationException tolerated) {}
expectUnchanged();
}
#ignore
@MapFeature.Require(absent = SUPPORTS_REMOVE)
#endignore
public void testUnsupportedPollFirst() {
try { orderedMap.pollFirstEntry(); }
catch (UnsupportedOperationException tolerated) {}
expectUnchanged();
}
#ignore
@MapFeature.Require(absent = SUPPORTS_REMOVE)
#endignore
public void testUnsupportedPollLast() {
try { orderedMap.pollFirstEntry(); }
catch (UnsupportedOperationException tolerated) {}
expectUnchanged();
}
}
@@ -2,6 +2,11 @@ package speiger.src.testers.PACKAGE.tests.queue.iterators;
#if TYPE_OBJECT #if TYPE_OBJECT
import java.util.Objects; import java.util.Objects;
#endif
#if JDK_TYPE
import java.util.OPTIONAL;
#else
import speiger.src.collections.PACKAGE.functions.OPTIONAL;
#endif #endif
import org.junit.Ignore; import org.junit.Ignore;
@@ -27,17 +32,17 @@ public class FILE_KEY_TYPEQueueFindFirstTester KEY_GENERIC_TYPE extends ABSTRACT
@CollectionSize.Require(absent = CollectionSize.ZERO) @CollectionSize.Require(absent = CollectionSize.ZERO)
#endignore #endignore
public void testQueueFindFirst_FindFirstElements() { public void testQueueFindFirst_FindFirstElements() {
assertEquals("First Element should be found", e0(), queue.findFirst(T -> KEY_EQUALS(T, e0()))); assertEquals("First Element should be found", e0(), queue.findFirst(T -> KEY_EQUALS(T, e0())).SUPPLY_GET());
} }
public void testQueueFindFirst_FindNothing() { public void testQueueFindFirst_FindNothing() {
assertEquals("No element should be found", EMPTY_KEY_VALUE, queue.findFirst(T -> KEY_EQUALS(T, e4()))); assertEquals("No element should be found", OPTIONAL.empty(), queue.findFirst(T -> KEY_EQUALS(T, e4())));
} }
#ignore #ignore
@CollectionSize.Require(CollectionSize.SEVERAL) @CollectionSize.Require(CollectionSize.SEVERAL)
#endignore #endignore
public void testQueueFindFirst_FindLastElement() { public void testQueueFindFirst_FindLastElement() {
assertEquals("Last Element should be found", e2(), queue.findFirst(T -> KEY_EQUALS(T, e2()))); assertEquals("Last Element should be found", e2(), queue.findFirst(T -> KEY_EQUALS(T, e2())).SUPPLY_GET());
} }
} }
@@ -3,10 +3,16 @@ package speiger.src.testers.PACKAGE.tests.queue.iterators;
#if TYPE_OBJECT #if TYPE_OBJECT
import java.util.Objects; import java.util.Objects;
#endif
#if JDK_TYPE
import java.util.OPTIONAL;
#else
import speiger.src.collections.PACKAGE.functions.OPTIONAL;
#endif #endif
import org.junit.Ignore; import org.junit.Ignore;
import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_QUEUE_TESTER; import speiger.src.testers.PACKAGE.tests.base.ABSTRACT_QUEUE_TESTER;
import com.google.common.collect.testing.features.CollectionSize;
@Ignore @Ignore
@SuppressWarnings("javadoc") @SuppressWarnings("javadoc")
@@ -29,7 +35,7 @@ public class FILE_KEY_TYPEQueueReduceTester KEY_GENERIC_TYPE extends ABSTRACT_QU
} }
public void testQueueReduce() { public void testQueueReduce() {
assertEquals("The sum of the queue should match", getSum(), queue.reduce(this::sum)); assertEquals("The sum of the queue should match", size == CollectionSize.ZERO ? OPTIONAL.empty() : OPTIONAL.GET_OPTIONAL(getSum()), queue.reduce(this::sum));
} }
public void testQueueExtraReduce() { public void testQueueExtraReduce() {
@@ -12,6 +12,9 @@ import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.SetFeature; import com.google.common.collect.testing.features.SetFeature;
import com.google.common.collect.testing.features.Feature; import com.google.common.collect.testing.features.Feature;
#if TYPE_OBJECT #if TYPE_OBJECT
import com.google.common.collect.testing.testers.CollectionAddTester;
import com.google.common.collect.testing.testers.CollectionAddAllTester;
import com.google.common.collect.testing.testers.CollectionCreationTester;
import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.CollectionFeature;
#endif #endif
import junit.framework.Test; import junit.framework.Test;
@@ -122,6 +125,9 @@ public class SET_TESTS extends TestCase
#ignore #ignore
.withFeatures(getSizes(size)).withFeatures(features); .withFeatures(getSizes(size)).withFeatures(features);
if(nullValues) builder.withFeatures(CollectionFeature.ALLOWS_NULL_VALUES); if(nullValues) builder.withFeatures(CollectionFeature.ALLOWS_NULL_VALUES);
builder.suppressing(CollectionAddTester.getAddNullUnsupportedMethod(), CollectionAddTester.getAddNullSupportedMethod());
builder.suppressing(CollectionAddAllTester.getAddAllNullUnsupportedMethod());
builder.suppressing(CollectionCreationTester.getCreateWithNullUnsupportedMethod());
#endignore #endignore
return builder.createTestSuite(); return builder.createTestSuite();
} }
@@ -41,6 +41,8 @@ import speiger.src.collections.PACKAGE.maps.impl.misc.ARRAY_MAP;
#if TYPE_OBJECT #if TYPE_OBJECT
import speiger.src.collections.PACKAGE.maps.impl.misc.ENUM_MAP; import speiger.src.collections.PACKAGE.maps.impl.misc.ENUM_MAP;
import speiger.src.collections.PACKAGE.maps.impl.misc.LINKED_ENUM_MAP; import speiger.src.collections.PACKAGE.maps.impl.misc.LINKED_ENUM_MAP;
import speiger.src.collections.PACKAGE.maps.impl.reference.REF_MAP;
import speiger.src.collections.PACKAGE.maps.impl.reference.LINKED_REF_MAP;
#endif #endif
import speiger.src.collections.PACKAGE.maps.impl.tree.AVL_TREE_MAP; import speiger.src.collections.PACKAGE.maps.impl.tree.AVL_TREE_MAP;
import speiger.src.collections.PACKAGE.maps.impl.tree.RB_TREE_MAP; import speiger.src.collections.PACKAGE.maps.impl.tree.RB_TREE_MAP;
@@ -104,6 +106,7 @@ public class MAP_TESTS extends TestCase
#if TYPE_OBJECT #if TYPE_OBJECT
constructors.addTest(new TestSuite(MAP_CONSTRUCTOR_TESTS.EnumMap.class)); constructors.addTest(new TestSuite(MAP_CONSTRUCTOR_TESTS.EnumMap.class));
constructors.addTest(new TestSuite(MAP_CONSTRUCTOR_TESTS.LinkedEnumMap.class)); constructors.addTest(new TestSuite(MAP_CONSTRUCTOR_TESTS.LinkedEnumMap.class));
constructors.addTest(new TestSuite(MAP_CONSTRUCTOR_TESTS.RefMap.class));
#endif #endif
constructors.addTest(new TestSuite(MAP_CONSTRUCTOR_TESTS.CustomHashMap.class)); constructors.addTest(new TestSuite(MAP_CONSTRUCTOR_TESTS.CustomHashMap.class));
constructors.addTest(new TestSuite(MAP_CONSTRUCTOR_TESTS.LinkedCustomHashMap.class)); constructors.addTest(new TestSuite(MAP_CONSTRUCTOR_TESTS.LinkedCustomHashMap.class));
@@ -130,27 +133,29 @@ public class MAP_TESTS extends TestCase
} }
public static void suite(TestSuite suite) { public static void suite(TestSuite suite) {
suite.addTest(mapSuite("HASH_MAP", HASH_MAP::new, getFeatures(), -1, true)); suite.addTest(mapSuite("HASH_MAP", HASH_MAP::new, getFeatures(), -1, true, true));
suite.addTest(orderedMapSuite("LINKED_HASH_MAP", LINKED_HASH_MAP::new, getFeatures(), -1)); suite.addTest(orderedMapSuite("LINKED_HASH_MAP", LINKED_HASH_MAP::new, getFeatures(), -1, true));
suite.addTest(orderedMapSuite("IMMUTABLE_HASH_MAP", IMMUTABLE_HASH_MAP::new, getImmutableFeatures(), -1)); suite.addTest(orderedMapSuite("IMMUTABLE_HASH_MAP", IMMUTABLE_HASH_MAP::new, getImmutableFeatures(), -1, true));
#if TYPE_OBJECT #if TYPE_OBJECT
suite.addTest(enumMapSuite("ENUM_MAP", ENUM_MAP::new, getFeatures(), 5)); suite.addTest(enumMapSuite("ENUM_MAP", ENUM_MAP::new, getFeatures(), 5));
suite.addTest(enumOrderedMapSuite("LINKED_ENUM_MAP", (K, V) -> K.length <= 0 ? new LINKED_ENUM_MAP<>(AnEnum.class) : new LINKED_ENUM_MAP<>(K, V), getFeatures(), 5)); suite.addTest(enumOrderedMapSuite("LINKED_ENUM_MAP", (K, V) -> K.length <= 0 ? new LINKED_ENUM_MAP<>(AnEnum.class) : new LINKED_ENUM_MAP<>(K, V), getFeatures(), 5));
suite.addTest(mapSuite("REF_MAP", REF_MAP::new, getFeatures(), - 1, true, false));
suite.addTest(orderedMapSuite("LINKED_REF_MAP", LINKED_REF_MAP::new, getFeatures(), - 1, false));
#endif #endif
suite.addTest(mapSuite("CUSTOM_HASH_MAP", (K, V) -> new CUSTOM_HASH_MAPKV_BRACES(K, V, HashStrategy.INSTANCE), getFeatures(), -1, true)); suite.addTest(mapSuite("CUSTOM_HASH_MAP", (K, V) -> new CUSTOM_HASH_MAPKV_BRACES(K, V, HashStrategy.INSTANCE), getFeatures(), -1, true, true));
suite.addTest(orderedMapSuite("LINKED_CUSTOM_HASH_MAP", (K, V) -> new LINKED_CUSTOM_HASH_MAPKV_BRACES(K, V, HashStrategy.INSTANCE), getFeatures(), -1)); suite.addTest(orderedMapSuite("LINKED_CUSTOM_HASH_MAP", (K, V) -> new LINKED_CUSTOM_HASH_MAPKV_BRACES(K, V, HashStrategy.INSTANCE), getFeatures(), -1, true));
suite.addTest(orderedMapSuite("ARRAY_MAP", ARRAY_MAP::new, getFeatures(), -1)); suite.addTest(orderedMapSuite("ARRAY_MAP", ARRAY_MAP::new, getFeatures(), -1, true));
suite.addTest(concurrentMapSuite("CONCURRENT_HASH_MAP", CONCURRENT_HASH_MAP::new, getFeatures(), 2)); suite.addTest(concurrentMapSuite("CONCURRENT_HASH_MAP", CONCURRENT_HASH_MAP::new, getFeatures(), 2));
suite.addTest(concurrentMapSuite("CONCURRENT_HASH_MAP", CONCURRENT_HASH_MAP::new, getFeatures(), 3)); suite.addTest(concurrentMapSuite("CONCURRENT_HASH_MAP", CONCURRENT_HASH_MAP::new, getFeatures(), 3));
suite.addTest(navigableMapSuite("RB_TREE_MAP", RB_TREE_MAP::new, getFeatures(), -1)); suite.addTest(navigableMapSuite("RB_TREE_MAP", RB_TREE_MAP::new, getFeatures(), -1));
suite.addTest(navigableMapSuite("AVL_TREE_MAP", AVL_TREE_MAP::new, getFeatures(), -1)); suite.addTest(navigableMapSuite("AVL_TREE_MAP", AVL_TREE_MAP::new, getFeatures(), -1));
suite.addTest(navigableMapSuite("SynchronizedRB_TREE_MAP", (K, V) -> new RB_TREE_MAPKV_BRACES(K, V).synchronize(), getLimitedFeatures(), -1)); suite.addTest(navigableMapSuite("SynchronizedRB_TREE_MAP", (K, V) -> new RB_TREE_MAPKV_BRACES(K, V).synchronize(), getLimitedFeatures(), -1));
suite.addTest(navigableMapSuite("UnmodifiableRB_TREE_MAP", (K, V) -> new RB_TREE_MAPKV_BRACES(K, V).unmodifiable(), getLimitedImmutableFeatures(), -1)); suite.addTest(navigableMapSuite("UnmodifiableRB_TREE_MAP", (K, V) -> new RB_TREE_MAPKV_BRACES(K, V).unmodifiable(), getLimitedImmutableFeatures(), -1));
suite.addTest(orderedMapSuite("SynchronizedORDERED_MAP", (K, V) -> new LINKED_HASH_MAPKV_BRACES(K, V).synchronize(), getFeatures(), -1)); suite.addTest(orderedMapSuite("SynchronizedORDERED_MAP", (K, V) -> new LINKED_HASH_MAPKV_BRACES(K, V).synchronize(), getFeatures(), -1, true));
suite.addTest(orderedMapSuite("UnmodifiableORDERED_MAP", (K, V) -> new LINKED_HASH_MAPKV_BRACES(K, V).unmodifiable(), getImmutableFeatures(), -1)); suite.addTest(orderedMapSuite("UnmodifiableORDERED_MAP", (K, V) -> new LINKED_HASH_MAPKV_BRACES(K, V).unmodifiable(), getImmutableFeatures(), -1, true));
suite.addTest(mapSuite("EmptyMAP", (K, V) -> MAPS.empty(), getEmptyFeatures(), 0, false)); suite.addTest(mapSuite("EmptyMAP", (K, V) -> MAPS.empty(), getEmptyFeatures(), 0, false, true));
suite.addTest(mapSuite("SingletonMAP", (K, V) -> MAPS.singleton(K[0], V[0]), getEmptyFeatures(), 1, false)); suite.addTest(mapSuite("SingletonMAP", (K, V) -> MAPS.singleton(K[0], V[0]), getEmptyFeatures(), 1, false, true));
suite.addTest(mapSuite("AbstractMap", SIMPLE_TEST_MAP::new, getTestFeatures(), -1, false)); suite.addTest(mapSuite("AbstractMap", SIMPLE_TEST_MAP::new, getTestFeatures(), -1, false, true));
} }
#if TYPE_OBJECT #if TYPE_OBJECT
@@ -209,14 +214,14 @@ public class MAP_TESTS extends TestCase
#endif #endif
private static Test mapSuite(String name, BiFunction<KEY_STRING_TYPE[], VALUE_STRING_TYPE[], MAP KEY_VALUE_STRING_GENERIC_TYPE> factory, Collection<Feature<?>> features, int size, boolean sorted) { private static Test mapSuite(String name, BiFunction<KEY_STRING_TYPE[], VALUE_STRING_TYPE[], MAP KEY_VALUE_STRING_GENERIC_TYPE> factory, Collection<Feature<?>> features, int size, boolean sorted, boolean allowNullKeys) {
SIMPLE_MAP_TEST_GENERATOR.Maps KEY_VALUE_STRING_GENERIC_TYPE generator = new SIMPLE_MAP_TEST_GENERATOR.Maps KEY_VALUE_STRING_GENERIC_TYPE(factory); SIMPLE_MAP_TEST_GENERATOR.Maps KEY_VALUE_STRING_GENERIC_TYPE generator = new SIMPLE_MAP_TEST_GENERATOR.Maps KEY_VALUE_STRING_GENERIC_TYPE(factory);
MAP_TEST_BUILDER KEY_VALUE_STRING_GENERIC_TYPE builder = MAP_TEST_BUILDER.using(generator); MAP_TEST_BUILDER KEY_VALUE_STRING_GENERIC_TYPE builder = MAP_TEST_BUILDER.using(generator);
builder.shouldBlockKeys(sorted); builder.shouldBlockKeys(sorted);
#if TYPE_OBJECT #if TYPE_OBJECT
generator.setKeys(createKeys()); generator.setKeys(createKeys());
#ignore #ignore
builder.withFeatures(MapFeature.ALLOWS_NULL_KEYS); if(allowNullKeys) builder.withFeatures(MapFeature.ALLOWS_NULL_KEYS);
#endignore #endignore
#endif #endif
#if VALUE_OBJECT #if VALUE_OBJECT
@@ -265,13 +270,13 @@ public class MAP_TESTS extends TestCase
return builder.named(name).createTestSuite(); return builder.named(name).createTestSuite();
} }
private static Test orderedMapSuite(String name, BiFunction<KEY_STRING_TYPE[], VALUE_STRING_TYPE[], ORDERED_MAP KEY_VALUE_STRING_GENERIC_TYPE> factory, Collection<Feature<?>> features, int size) { private static Test orderedMapSuite(String name, BiFunction<KEY_STRING_TYPE[], VALUE_STRING_TYPE[], ORDERED_MAP KEY_VALUE_STRING_GENERIC_TYPE> factory, Collection<Feature<?>> features, int size, boolean allowNullKeys) {
SIMPLE_MAP_TEST_GENERATOR.OrderedMaps KEY_VALUE_STRING_GENERIC_TYPE generator = new SIMPLE_MAP_TEST_GENERATOR.OrderedMaps KEY_VALUE_STRING_GENERIC_TYPE(factory); SIMPLE_MAP_TEST_GENERATOR.OrderedMaps KEY_VALUE_STRING_GENERIC_TYPE generator = new SIMPLE_MAP_TEST_GENERATOR.OrderedMaps KEY_VALUE_STRING_GENERIC_TYPE(factory);
ORDERED_MAP_TEST_BUILDER KEY_VALUE_STRING_GENERIC_TYPE builder = ORDERED_MAP_TEST_BUILDER.using(generator); ORDERED_MAP_TEST_BUILDER KEY_VALUE_STRING_GENERIC_TYPE builder = ORDERED_MAP_TEST_BUILDER.using(generator);
#if TYPE_OBJECT #if TYPE_OBJECT
generator.setKeys(createKeys()); generator.setKeys(createKeys());
#ignore #ignore
builder.withFeatures(MapFeature.ALLOWS_NULL_KEYS); if(allowNullKeys) builder.withFeatures(MapFeature.ALLOWS_NULL_KEYS);
#endignore #endignore
#endif #endif
#if VALUE_OBJECT #if VALUE_OBJECT
@@ -0,0 +1,318 @@
package speiger.src.collections.booleans.collections;
import java.util.Collection;
import java.util.function.Supplier;
import java.util.Objects;
import java.util.AbstractCollection;
import speiger.src.collections.booleans.lists.BooleanListIterator;
import speiger.src.collections.booleans.functions.BooleanConsumer;
import speiger.src.collections.booleans.utils.BooleanIterators;
import speiger.src.collections.booleans.utils.BooleanArrays;
/**
* Abstract Type Specific Collection that reduces boxing/unboxing
*/
public abstract class AbstractBooleanCollection extends AbstractCollection<Boolean> implements BooleanCollection
{
@Override
public abstract BooleanIterator iterator();
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
public boolean add(Boolean e) { return BooleanCollection.super.add(e); }
@Override
public boolean addAll(BooleanCollection c) {
boolean modified = false;
for(BooleanIterator iter = c.iterator();iter.hasNext();modified |= add(iter.nextBoolean()));
return modified;
}
@Override
public BooleanCollection copy() { throw new UnsupportedOperationException(); }
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
public boolean contains(Object e) { return BooleanCollection.super.contains(e); }
/**
* A Type-Specific implementation of contains. This implementation iterates over the elements and returns true if the value match.
* @param e the element that should be searched for.
* @return true if the value was found.
*/
@Override
public boolean contains(boolean e) {
for(BooleanIterator iter = iterator();iter.hasNext();) { if(iter.nextBoolean() == e) return true; }
return false;
}
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
public boolean addAll(Collection<? extends Boolean> c)
{
return c instanceof BooleanCollection ? addAll((BooleanCollection)c) : super.addAll(c);
}
/**
* A Type-Specific implementation of containsAll. This implementation iterates over all elements and checks all elements are present in the other collection.
* @param c the collection that should be checked if it contains all elements.
* @return true if all elements were found in the collection
* @throws java.lang.NullPointerException if the collection is null
*/
@Override
public boolean containsAll(BooleanCollection c) {
Objects.requireNonNull(c);
if(c.isEmpty()) return true;
for(BooleanIterator iter = c.iterator();iter.hasNext();)
if(!contains(iter.nextBoolean()))
return false;
return true;
}
@Override
public boolean containsAll(Collection<?> c) {
Objects.requireNonNull(c);
return c instanceof BooleanCollection ? containsAll((BooleanCollection)c) : super.containsAll(c);
}
/**
* This implementation iterates over the elements of the collection and checks if they are stored in this collection
* @param c the elements that should be checked for
* @return true if any element is in this collection
* @throws java.lang.NullPointerException if the collection is null
*/
@Override
@Deprecated
public boolean containsAny(Collection<?> c) {
Objects.requireNonNull(c);
if(c.isEmpty()) return false;
for(Object e : c)
if(contains(e))
return true;
return false;
}
/**
* This implementation iterates over the elements of the collection and checks if they are stored in this collection.
* @param c the elements that should be checked for
* @return true if any element is in this collection
* @throws java.lang.NullPointerException if the collection is null
*/
@Override
public boolean containsAny(BooleanCollection c) {
Objects.requireNonNull(c);
if(c.isEmpty()) return false;
for(BooleanIterator iter = c.iterator();iter.hasNext();)
if(contains(iter.nextBoolean()))
return true;
return false;
}
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
public boolean remove(Object e) { return BooleanCollection.super.remove(e); }
/**
* A Type-Specific implementation of remove. This implementation iterates over the elements until it finds the element that is searched for or it runs out of elements.
* It stops after finding the first element
* @param e the element that is searched for
* @return true if the element was found and removed.
*/
@Override
public boolean remBoolean(boolean e) {
for(BooleanIterator iter = iterator();iter.hasNext();) {
if(iter.nextBoolean() == e) {
iter.remove();
return true;
}
}
return false;
}
/**
* A Type-Specific implementation of removeAll. This Implementation iterates over all elements and removes them as they were found in the other collection.
* @param c the elements that should be deleted
* @return true if the collection was modified.
* @throws java.lang.NullPointerException if the collection is null
*/
@Override
public boolean removeAll(BooleanCollection c) {
Objects.requireNonNull(c);
if(c.isEmpty()) return false;
boolean modified = false;
for(BooleanIterator iter = iterator();iter.hasNext();) {
if(c.contains(iter.nextBoolean())) {
iter.remove();
modified = true;
}
}
return modified;
}
@Override
public boolean removeAll(BooleanCollection c, BooleanConsumer r) {
Objects.requireNonNull(c);
if(c.isEmpty()) return false;
Objects.requireNonNull(r);
boolean modified = false;
for(BooleanIterator iter = iterator();iter.hasNext();) {
boolean e = iter.nextBoolean();
if(c.contains(e)) {
r.accept(e);
iter.remove();
modified = true;
}
}
return modified;
}
/**
* A Type-Specific implementation of retainAll. This Implementation iterates over all elements and removes them as they were not found in the other collection.
* @param c the elements that should be kept
* @return true if the collection was modified.
* @throws java.lang.NullPointerException if the collection is null
*/
@Override
public boolean retainAll(BooleanCollection c) {
Objects.requireNonNull(c);
if(c.isEmpty()) {
boolean modified = !isEmpty();
clear();
return modified;
}
boolean modified = false;
for(BooleanIterator iter = iterator();iter.hasNext();) {
if(!c.contains(iter.nextBoolean())) {
iter.remove();
modified = true;
}
}
return modified;
}
@Override
public boolean retainAll(BooleanCollection c, BooleanConsumer r) {
Objects.requireNonNull(c);
Objects.requireNonNull(r);
if(c.isEmpty()) {
boolean modified = !isEmpty();
forEach(r);
clear();
return modified;
}
boolean modified = false;
for(BooleanIterator iter = iterator();iter.hasNext();) {
boolean e = iter.nextBoolean();
if(!c.contains(e)) {
r.accept(e);
iter.remove();
modified = true;
}
}
return modified;
}
/**
* A Type-Specific implementation of toArray that links to {@link #toBooleanArray(boolean[])} with a newly created array.
* @return an array containing all of the elements in this collection
*/
@Override
public boolean[] toBooleanArray() {
if(isEmpty()) return BooleanArrays.EMPTY_ARRAY;
return toBooleanArray(new boolean[size()]);
}
/**
* A Type-Specific implementation of toArray. This implementation iterates over all elements and unwraps them into primitive type.
* @param a array that the elements should be injected to. If null or to small a new array with the right size is created
* @return an array containing all of the elements in this collection
*/
@Override
public boolean[] toBooleanArray(boolean[] a) {
if(a == null || a.length < size()) a = new boolean[size()];
BooleanIterators.unwrap(a, iterator());
if (a.length > size()) a[size()] = false;
return a;
}
public static class ReverseBooleanOrderedCollection extends AbstractBooleanCollection implements BooleanOrderedCollection {
BooleanOrderedCollection collection;
Supplier<BooleanIterator> reverseIterator;
public ReverseBooleanOrderedCollection(BooleanOrderedCollection collection, Supplier<BooleanIterator> reverseIterator) {
this.collection = collection;
this.reverseIterator = reverseIterator;
}
@Override
public boolean add(boolean o) { return collection.add(o); }
@Override
public BooleanOrderedCollection reversed() { return collection; }
@Override
public void addFirst(boolean e) { collection.addLast(e); }
@Override
public void addLast(boolean e) { collection.addFirst(e); }
@Override
public boolean contains(boolean e) { return collection.contains(e); }
@Override
public boolean remBoolean(boolean e) { return collection.remBoolean(e); }
@Override
public void clear() { collection.clear(); }
@Override
public boolean getFirstBoolean() { return collection.getLastBoolean(); }
@Override
public boolean removeFirstBoolean() { return collection.removeLastBoolean(); }
@Override
public boolean getLastBoolean() { return collection.getFirstBoolean(); }
@Override
public boolean removeLastBoolean() { return collection.removeFirstBoolean(); }
@Override
public BooleanIterator iterator() { return reverseIterator.get(); }
@Override
public int size() { return collection.size(); }
}
public static class ReverseBiIterator implements BooleanListIterator {
BooleanListIterator it;
public ReverseBiIterator(BooleanListIterator it) {
this.it = it;
}
@Override
public boolean nextBoolean() { return it.previousBoolean(); }
@Override
public boolean hasNext() { return it.hasPrevious(); }
@Override
public boolean hasPrevious() { return it.hasNext(); }
@Override
public boolean previousBoolean() { return it.nextBoolean(); }
@Override
public void remove() { it.remove(); }
@Override
public int nextIndex() { return it.previousIndex(); }
@Override
public int previousIndex() { return it.nextIndex(); }
@Override
public void set(boolean e) { it.set(e); }
@Override
public void add(boolean e) { it.add(e); }
}
}
@@ -0,0 +1,52 @@
package speiger.src.collections.booleans.collections;
/**
* This is a basically a {@link java.util.ListIterator} without the index functions.
* Allowing to have a simple Bidirectional Iterator without having to keep track of the Iteration index.
*/
public interface BooleanBidirectionalIterator extends BooleanIterator
{
/**
* Returns true if the Iterator has a Previous element
* @return true if the Iterator has a Previous element
*/
public boolean hasPrevious();
/**
* Returns the Previous element of the iterator.
* @return the Previous element of the iterator.
* @throws java.util.NoSuchElementException if the iteration has no more elements
*/
public boolean previousBoolean();
/**
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
* @return the Previous element of the iterator.+
*/
@Deprecated
public default Boolean previous() {
return Boolean.valueOf(previousBoolean());
}
/**
* {@inheritDoc}
*/
@Override
default int skip(int amount)
{
return BooleanIterator.super.skip(amount);
}
/**
* Reverses the Given amount of elements if possible. A Optimization function to reverse elements faster if the implementation allows it.
* @param amount the amount of elements that should be reversed
* @return the amount of elements that were reversed
*/
public default int back(int amount) {
if(amount < 0) throw new IllegalStateException("Can't go forward");
int i = 0;
for(;i<amount && hasPrevious();previousBoolean(),i++);
return i;
}
}
@@ -0,0 +1,231 @@
package speiger.src.collections.booleans.collections;
import java.util.Collection;
import speiger.src.collections.booleans.functions.BooleanConsumer;
import speiger.src.collections.booleans.utils.BooleanSplititerators;
import speiger.src.collections.booleans.utils.BooleanCollections;
import speiger.src.collections.utils.ISizeProvider;
import speiger.src.collections.utils.SanityChecks;
/**
* A Type-Specific {@link Collection} that reduces (un)boxing
*/
public interface BooleanCollection extends Collection<Boolean>, BooleanIterable, ISizeProvider
{
/**
* A Type-Specific add function to reduce (un)boxing
* @param o the element that should be added
* @return true if the element was added to the collection
*/
public boolean add(boolean o);
/**
* A Type-Specific addAll function to reduce (un)boxing
* @param c the collection of elements that should be added
* @return true if elements were added into the collection
*/
public boolean addAll(BooleanCollection c);
/**
* A Type-Specific Array based addAll method to reduce the amount of Wrapping
* @param e the elements that should be added
* @return if the collection was modified
*/
public default boolean addAll(boolean... e) { return addAll(e, 0, e.length); }
/**
* A Type-Specific Array based addAll method to reduce the amount of Wrapping
* @param e the elements that should be added
* @param length how many elements of the array should be added
* @return if the collection was modified
*/
public default boolean addAll(boolean[] e, int length) { return addAll(e, 0, length); }
/**
* A Type-Specific Array based addAll method to reduce the amount of Wrapping
* @param e the elements that should be added
* @param offset where to start within the array
* @param length how many elements of the array should be added
* @return if the collection was modified
*/
public default boolean addAll(boolean[] e, int offset, int length) {
if(length <= 0) return false;
SanityChecks.checkArrayCapacity(e.length, offset, length);
boolean added = false;
for(int i = 0;i<length;i++) {
if(add(e[offset+i])) added = true;
}
return added;
}
/**
* A Type-Specific contains function to reduce (un)boxing
* @param o the element that is checked for
* @return true if the element is found in the collection
*/
public boolean contains(boolean o);
/**
* A Type-Specific containsAll function to reduce (un)boxing
* @param c the collection of elements that should be tested for
* @return true if all the element is found in the collection
*/
public boolean containsAll(BooleanCollection c);
/**
* A Type-Specific containsAny function to reduce (un)boxing
* @param c the collection of elements that should be tested for
* @return true if any element was found
*/
public boolean containsAny(BooleanCollection c);
/**
* Returns true if any element of the Collection is found in the provided collection.
* A Small Optimization function to find out of any element is present when comparing collections and not all of them.
* @param c the collection of elements that should be tested for
* @return true if any element was found.
*/
@Deprecated
public boolean containsAny(Collection<?> c);
/**
* A Type-Specific remove function that reduces (un)boxing.
* @param o the element that should be removed
* @return true if the element was removed
* @see Collection#remove(Object)
*/
public boolean remBoolean(boolean o);
/**
* A Type-Specific removeAll function that reduces (un)boxing.
* @param c the collection of elements that should be removed
* @return true if any element was removed
* @see Collection#removeAll(Collection)
*/
public boolean removeAll(BooleanCollection c);
/**
* A Type-Specific removeAll function that reduces (un)boxing.
* It also notifies the remover of which exact element is going to be removed.
* @param c the collection of elements that should be removed
* @param r elements that got removed
* @return true if any element was removed
* @see Collection#removeAll(Collection)
*/
public boolean removeAll(BooleanCollection c, BooleanConsumer r);
/**
* A Type-Specific retainAll function that reduces (un)boxing.
* @param c the collection of elements that should be kept
* @return true if any element was removed
* @see Collection#retainAll(Collection)
*/
public boolean retainAll(BooleanCollection c);
/**
* A Type-Specific retainAll function that reduces (un)boxing.
* It also notifies the remover of which exact element is going to be removed.
* @param c the collection of elements that should be kept
* @param r elements that got removed
* @return true if any element was removed
* @see Collection#retainAll(Collection)
*/
public boolean retainAll(BooleanCollection c, BooleanConsumer r);
/**
* A Helper function to reduce the usage of Streams and allows to collect all elements
* @param collection that the elements should be inserted to
* @param <E> the collection type
* @return the input with the desired elements
*/
default <E extends BooleanCollection> E pour(E collection) {
collection.addAll(this);
return collection;
}
/**
* A Function that does a shallow clone of the Collection itself.
* This function is more optimized then a copy constructor since the Collection does not have to be unsorted/resorted.
* It can be compared to Cloneable but with less exception risk
* @return a Shallow Copy of the collection
* @note Wrappers and view collections will not support this feature
*/
public BooleanCollection copy();
/**
* A Type-Specific toArray function that delegates to {@link #toBooleanArray(boolean[])} with a newly created array.
* @return an array containing all of the elements in this collection
* @see Collection#toArray()
*/
public boolean[] toBooleanArray();
/**
* A Type-Specific toArray function that reduces (un)boxing.
* @param a array that the elements should be injected to. If null or to small a new array with the right size is created
* @return an array containing all of the elements in this collection
* @see Collection#toArray(Object[])
*/
public boolean[] toBooleanArray(boolean[] a);
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
public default boolean add(Boolean o) { return add(o.booleanValue()); }
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
public default boolean contains(Object o) { return o != null && contains(((Boolean)o).booleanValue()); }
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
public default boolean remove(Object o) { return o != null && remBoolean(((Boolean)o).booleanValue()); }
/**
* Returns a Type-Specific Iterator to reduce (un)boxing
* @return a iterator of the collection
* @see Collection#iterator()
*/
@Override
public BooleanIterator iterator();
/**
* Creates a Wrapped Collection that is Synchronized
* @return a new Collection that is synchronized
* @see BooleanCollections#synchronize
*/
public default BooleanCollection synchronize() { return BooleanCollections.synchronize(this); }
/**
* Creates a Wrapped Collection that is Synchronized
* @param mutex is the controller of the synchronization block
* @return a new Collection Wrapper that is synchronized
* @see BooleanCollections#synchronize
*/
public default BooleanCollection synchronize(Object mutex) { return BooleanCollections.synchronize(this, mutex); }
/**
* Creates a Wrapped Collection that is unmodifiable
* @return a new Collection Wrapper that is unmodifiable
* @see BooleanCollections#unmodifiable
*/
public default BooleanCollection unmodifiable() { return BooleanCollections.unmodifiable(this); }
/**
* A Type Specific Type Splititerator to reduce boxing/unboxing
* @return type specific splititerator
*/
@Override
default BooleanSplititerator spliterator() { return BooleanSplititerators.createSplititerator(this, 0); }
}
@@ -0,0 +1,334 @@
package speiger.src.collections.booleans.collections;
import java.util.Objects;
import java.util.function.Consumer;
import speiger.src.collections.booleans.functions.BooleanConsumer;
import speiger.src.collections.booleans.functions.BooleanComparator;
import speiger.src.collections.objects.collections.ObjectIterable;
import speiger.src.collections.booleans.functions.OptionalBoolean;
import speiger.src.collections.booleans.functions.function.BooleanFunction;
import speiger.src.collections.ints.functions.consumer.IntBooleanConsumer;
import speiger.src.collections.objects.functions.consumer.ObjectBooleanConsumer;
import speiger.src.collections.booleans.functions.function.BooleanPredicate;
import speiger.src.collections.booleans.functions.function.BooleanBooleanUnaryOperator;
import speiger.src.collections.booleans.lists.BooleanList;
import speiger.src.collections.booleans.lists.BooleanArrayList;
import speiger.src.collections.booleans.utils.BooleanArrays;
import speiger.src.collections.booleans.utils.BooleanAsyncBuilder;
import speiger.src.collections.booleans.utils.BooleanSplititerators;
import speiger.src.collections.booleans.utils.BooleanIterables;
import speiger.src.collections.booleans.utils.BooleanIterators;
import speiger.src.collections.utils.ISizeProvider;
/**
* A Type-Specific {@link Iterable} that reduces (un)boxing
*/
public interface BooleanIterable extends Iterable<Boolean>
{
/**
* Returns an iterator over elements of type {@code T}.
*
* @return an Iterator.
*/
@Override
BooleanIterator iterator();
/**
* A Type Specific foreach function that reduces (un)boxing
*
* @implSpec
* <p>The default implementation behaves as if:
* <pre>{@code
* iterator().forEachRemaining(action);
* }</pre>
*
* @param action The action to be performed for each element
* @throws NullPointerException if the specified action is null
* @see Iterable#forEach(Consumer)
*/
default void forEach(BooleanConsumer action) {
Objects.requireNonNull(action);
iterator().forEachRemaining(action);
}
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Deprecated
@Override
default void forEach(Consumer<? super Boolean> action) {
Objects.requireNonNull(action);
iterator().forEachRemaining(action);
}
/**
* A Indexed forEach implementation that allows you to keep track of how many elements were already iterated over.
* @param action The action to be performed for each element
* @throws java.lang.NullPointerException if the specified action is null
*/
public default void forEachIndexed(IntBooleanConsumer action) {
Objects.requireNonNull(action);
int index = 0;
for(BooleanIterator iter = iterator();iter.hasNext();action.accept(index++, iter.nextBoolean()));
}
/**
* Helper function to reduce Lambda usage and allow for more method references, since these are faster/cleaner.
* @param input the object that should be included
* @param action The action to be performed for each element
* @param <E> the generic type of the Object
* @throws java.lang.NullPointerException if the specified action is null
*/
default <E> void forEach(E input, ObjectBooleanConsumer<E> action) {
Objects.requireNonNull(action);
iterator().forEachRemaining(input, action);
}
/**
* A Type Specific Type Splititerator to reduce boxing/unboxing
* @return type specific splititerator
*/
@Override
default BooleanSplititerator spliterator() { return BooleanSplititerators.createUnknownSplititerator(iterator(), 0); }
/**
* Creates a Async Builder for moving work of the thread.
* It is not designed to split the work to multithreaded work, so using this keep it singlethreaded, but it allows to be moved to another thread.
* @see BooleanAsyncBuilder
* @return a AsyncBuilder
*/
default BooleanAsyncBuilder asAsync() {
return new BooleanAsyncBuilder(this);
}
/**
* A Helper function to reduce the usage of Streams and allows to convert a Iterable to something else.
* @param mapper the mapping function
* @param <E> The return type.
* @return a new Iterable that returns the desired result
*/
default <E> ObjectIterable<E> map(BooleanFunction<E> mapper) {
return BooleanIterables.map(this, mapper);
}
/**
* A Helper function to reduce the usage of Streams and allows to convert a Iterable to something else.
* @param mapper the flatMapping function
* @param <V> The return type supplier.
* @param <E> The return type.
* @return a new Iterable that returns the desired result
* @note does not support toBooleanArray optimizations.
*/
default <E, V extends Iterable<E>> ObjectIterable<E> flatMap(BooleanFunction<V> mapper) {
return BooleanIterables.flatMap(this, mapper);
}
/**
* A Helper function to reduce the usage of Streams and allows to convert a Iterable to something else.
* @param mapper the flatMapping function
* @param <E> The return type.
* @return a new Iterable that returns the desired result
* @note does not support toBooleanArray optimizations.
*/
default <E> ObjectIterable<E> arrayflatMap(BooleanFunction<E[]> mapper) {
return BooleanIterables.arrayFlatMap(this, mapper);
}
/**
* A Helper function to reduce the usage of Streams and allows to filter out unwanted elements
* @param filter the elements that should be kept.
* @return a Iterable that filtered out all unwanted elements
* @note does not support toBooleanArray optimizations.
*/
default BooleanIterable filter(BooleanPredicate filter) {
return BooleanIterables.filter(this, filter);
}
/**
* A Helper function to reduce the usage of Streams and allows to filter out duplicated elements
* @return a Iterable that filtered out all duplicated elements
* @note does not support toBooleanArray optimizations.
*/
default BooleanIterable distinct() {
return BooleanIterables.distinct(this);
}
/**
* A Helper function to reduce the usage of Streams and allows to repeat elements a desired amount of times
* @param repeats how many times the elements should be repeated
* @return a Iterable that is repeating multiple times
*/
default BooleanIterable repeat(int repeats) {
return BooleanIterables.repeat(this, repeats);
}
/**
* A Helper function to reduce the usage of Streams and allows to limit the amount of elements
* @param limit the amount of elements it should be limited to
* @return a Iterable that is limited in length
*/
default BooleanIterable limit(long limit) {
return BooleanIterables.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 BooleanIterable sorted(BooleanComparator sorter) {
return BooleanIterables.sorted(this, sorter);
}
/**
* A Helper function to reduce the usage of Streams and allows to preview elements before they are iterated through
* @param action the action that should be applied
* @return a Peeked Iterable
*/
default BooleanIterable peek(BooleanConsumer action) {
return BooleanIterables.peek(this, action);
}
/**
* A Helper function to reduce the usage of Streams and allows to collect all elements
* @param collection that the elements should be inserted to
* @param <E> the collection type
* @return the input with the desired elements
*/
default <E extends BooleanCollection> E pour(E collection) {
BooleanIterators.pour(iterator(), collection);
return collection;
}
/**
* A Helper function that reduces the usage of streams and allows to collect all elements as a ArrayList
* @return a new ArrayList of all elements
*/
default BooleanList pourAsList() {
return pour(new BooleanArrayList());
}
/**
* A Helper function that reduces the usage of streams and allows to collect all elements as a Array
* @return a new Array of all elements
*/
default boolean[] toBooleanArray() {
ISizeProvider prov = ISizeProvider.of(this);
if(prov != null) {
int size = prov.size();
if(size >= 0) {
boolean[] array = new boolean[size];
BooleanIterators.unwrap(array, iterator());
return array;
}
}
return BooleanArrays.pour(iterator());
}
/**
* Helper function to reduce stream usage that allows to filter for any matches.
* @param filter that should be applied
* @return true if any matches were found
*/
default boolean matchesAny(BooleanPredicate filter) {
Objects.requireNonNull(filter);
for(BooleanIterator iter = iterator();iter.hasNext();) {
if(filter.test(iter.nextBoolean())) return true;
}
return false;
}
/**
* Helper function to reduce stream usage that allows to filter for no matches.
* @param filter that should be applied
* @return true if no matches were found
*/
default boolean matchesNone(BooleanPredicate filter) {
Objects.requireNonNull(filter);
for(BooleanIterator iter = iterator();iter.hasNext();) {
if(filter.test(iter.nextBoolean())) return false;
}
return true;
}
/**
* Helper function to reduce stream usage that allows to filter for all matches.
* @param filter that should be applied
* @return true if all matches.
*/
default boolean matchesAll(BooleanPredicate filter) {
Objects.requireNonNull(filter);
for(BooleanIterator iter = iterator();iter.hasNext();) {
if(!filter.test(iter.nextBoolean())) return false;
}
return true;
}
/**
* Helper function to reduce stream usage that allows to filter for the first match.
* @param filter that should be applied
* @return the found value or the null equivalent variant.
*/
default OptionalBoolean findFirst(BooleanPredicate filter) {
Objects.requireNonNull(filter);
for(BooleanIterator iter = iterator();iter.hasNext();) {
boolean entry = iter.nextBoolean();
if(filter.test(entry)) return OptionalBoolean.of(entry);
}
return OptionalBoolean.empty();
}
/**
* Performs a <a href="package-summary.html#Reduction">reduction</a> on the
* elements of this Iterable
* @param operator the operation that should be applied
* @param identity the start value
* @return the reduction result, returns identity if nothing was found
*/
default boolean reduce(boolean identity, BooleanBooleanUnaryOperator operator) {
Objects.requireNonNull(operator);
boolean state = identity;
for(BooleanIterator iter = iterator();iter.hasNext();) {
state = operator.applyAsBoolean(state, iter.nextBoolean());
}
return state;
}
/**
* Performs a <a href="package-summary.html#Reduction">reduction</a> on the
* elements of this Iterable
* @param operator the operation that should be applied
* @return the reduction result, returns null value if nothing was found
*/
default OptionalBoolean reduce(BooleanBooleanUnaryOperator operator) {
Objects.requireNonNull(operator);
boolean state = false;
boolean empty = true;
for(BooleanIterator iter = iterator();iter.hasNext();) {
if(empty) {
empty = false;
state = iter.nextBoolean();
continue;
}
state = operator.applyAsBoolean(state, iter.nextBoolean());
}
return empty ? OptionalBoolean.empty() : OptionalBoolean.of(state);
}
/**
* Helper function to reduce stream usage that allows to count the valid elements.
* @param filter that should be applied
* @return the amount of Valid Elements
*/
default int count(BooleanPredicate filter) {
Objects.requireNonNull(filter);
int result = 0;
for(BooleanIterator iter = iterator();iter.hasNext();) {
if(filter.test(iter.nextBoolean())) result++;
}
return result;
}
}
@@ -0,0 +1,88 @@
package speiger.src.collections.booleans.collections;
import java.util.Iterator;
import java.util.Objects;
import java.util.function.Consumer;
import speiger.src.collections.booleans.functions.BooleanConsumer;
import speiger.src.collections.objects.functions.consumer.ObjectBooleanConsumer;
/**
* A Type-Specific {@link Iterator} that reduces (un)boxing
*/
public interface BooleanIterator extends Iterator<Boolean>
{
/**
* Returns the next element in the iteration.
*
* @return the next element in the iteration
* @throws java.util.NoSuchElementException if the iteration has no more elements
* @see Iterator#next()
*/
public boolean nextBoolean();
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
public default Boolean next() { return Boolean.valueOf(nextBoolean()); }
/**
* Performs the given action for each remaining element until all elements
* have been processed or the action throws an exception. Actions are
* performed in the order of iteration, if that order is specified.
* Exceptions thrown by the action are relayed to the caller.
*
* @implSpec
* <p>The default implementation behaves as if:
* <pre>{@code
* while (hasNext()) action.accept(nextBoolean());
* }</pre>
*
* @param action The action to be performed for each element
* @throws java.lang.NullPointerException if the specified action is null
* @see Iterator#forEachRemaining(Consumer)
*/
public default void forEachRemaining(BooleanConsumer action) {
Objects.requireNonNull(action);
while(hasNext()) { action.accept(nextBoolean()); }
}
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Deprecated
@Override
default void forEachRemaining(Consumer<? super Boolean> action) {
Objects.requireNonNull(action);
forEachRemaining(action::accept);
}
/**
* Helper function to reduce Lambda usage and allow for more method references, since these are faster/cleaner.
* @param input the object that should be included
* @param action The action to be performed for each element
* @param <E> the generic type of the Object
* @throws java.lang.NullPointerException if the specified action is null
*/
default <E> void forEachRemaining(E input, ObjectBooleanConsumer<E> action) {
Objects.requireNonNull(action);
while(hasNext()) { action.accept(input, nextBoolean()); }
}
/**
* Skips the Given amount of elements if possible. A Optimization function to skip elements faster if the implementation allows it.
* @param amount the amount of elements that should be skipped
* @return the amount of elements that were skipped
*/
default int skip(int amount) {
if(amount < 0) throw new IllegalStateException("Negative Numbers are not allowed");
int i = 0;
for(;i<amount && hasNext();nextBoolean(), i++);
return i;
}
}
@@ -0,0 +1,40 @@
package speiger.src.collections.booleans.collections;
public interface BooleanOrderedCollection extends BooleanCollection {
BooleanOrderedCollection reversed();
/**
* A method to add an element to the start of a collection
* @param e that should be added at the start.
*/
public void addFirst(boolean e);
/**
* A method to add an element to the end of a collection
* @param e that should be added at the end.
*/
public void addLast(boolean e);
/**
* A method to get the first element in the collection
* @return first element in the collection
*/
public boolean getFirstBoolean();
/**
* A method to get and remove the first element in the collection
* @return first element in the collection
*/
public boolean removeFirstBoolean();
/**
* A method to get the last element in the collection
* @return last element in the collection
*/
public boolean getLastBoolean();
/**
* A method to get and remove the last element in the collection
* @return last element in the collection
*/
public boolean removeLastBoolean();
}
@@ -0,0 +1,19 @@
package speiger.src.collections.booleans.collections;
import java.util.Spliterator.OfPrimitive;
import java.util.function.Consumer;
import speiger.src.collections.booleans.functions.BooleanConsumer;
/**
* A Type Specific Split-Iterator that reduces boxing/unboxing
* It fills the gaps of the java and uses this collection interfaces
*/
public interface BooleanSplititerator extends OfPrimitive<Boolean, BooleanConsumer, BooleanSplititerator>, BooleanIterator
{
@Override
default void forEachRemaining(BooleanConsumer action) { BooleanIterator.super.forEachRemaining(action); }
@Override
@Deprecated
default void forEachRemaining(Consumer<? super Boolean> action) { BooleanIterator.super.forEachRemaining(action); }
}
@@ -0,0 +1,85 @@
package speiger.src.collections.booleans.collections;
import java.util.NoSuchElementException;
import speiger.src.collections.utils.Stack;
/**
* A Type-Specific {@link Stack} that reduces (un)boxing
*/
public interface BooleanStack
{
/**
* Inserts a given Object on top of the stack
* @param e the Object to insert
* @see Stack#push(Object)
*/
public void push(boolean e);
/**
* Helper function that pushes the top element on top of the stack again.
* @throws NoSuchElementException if the stack is empty
*/
public default void pushTop() {
push(top());
}
/**
* Removes the Object on top of the stack.
* @return the element that is on top of the stack
* @throws ArrayIndexOutOfBoundsException if the stack is empty
* @see Stack#pop()
*/
public boolean pop();
/**
* Provides the Object on top of the stack
* @return the element that is on top of the stack
* @throws ArrayIndexOutOfBoundsException if the stack is empty
* @see Stack#top()
*/
public default boolean top() {
return peek(0);
}
/**
* Provides the Selected Object from the stack.
* Top to bottom
* @param index of the element that should be provided
* @return the element that was requested
* @throws ArrayIndexOutOfBoundsException if the index is out of bounds
* @see Stack#peek(int)
*/
public boolean peek(int index);
/**
* Clears the stack
*/
public void clear();
/**
* Provides the amount of elements currently in the stack
* @return amount of elements in the list
*/
public int size();
/**
* @return if the stack is empty
*/
public default boolean isEmpty() {
return size() == 0;
}
/**
* A method to drop the contents of the Stack without clearing the stack
* @return the contents of the stack into a seperate array.
*/
public default boolean[] toBooleanArray() { return toBooleanArray(new boolean[size()]); }
/**
* A method to drop the contents of the Stack without clearing the stack
* @param input where the elements should be inserted to. If it does not fit then it creates a new appropiatly created array
* @return the contents of the stack into a seperate array.
* @note if the Type is generic then a Object Array is created instead of a Type Array
*/
public boolean[] toBooleanArray(boolean[] input);
}
@@ -0,0 +1,70 @@
package speiger.src.collections.booleans.functions;
import java.util.Comparator;
import java.util.Objects;
/**
* Type-Specific Class for Comparator to reduce (un)boxing
*/
public interface BooleanComparator extends Comparator<Boolean>
{
/**
* Type-Specific compare function to reduce (un)boxing
* @param o1 the first object to be compared.
* @param o2 the second object to be compared.
* @return a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
* @see Comparator#compare(Object, Object)
*/
int compare(boolean o1, boolean o2);
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
default int compare(Boolean o1, Boolean o2) {
return compare(o1.booleanValue(), o2.booleanValue());
}
/**
* A Wrapper function to convert a Non-Type-Specific Comparator to a Type-Specific-Comparator
* @param c comparator to convert
* @return the wrapper of the comparator
* @throws NullPointerException if the comparator is null
*/
public static BooleanComparator of(Comparator<Boolean> c) {
Objects.requireNonNull(c);
return (K, V) -> c.compare(Boolean.valueOf(K), Boolean.valueOf(V));
}
@Override
public default BooleanComparator reversed() {
return new Reversed(this);
}
/**
* A Type Specific Reversed Comparator to reduce boxing/unboxing
*/
static class Reversed implements BooleanComparator
{
BooleanComparator original;
/**
* default constructor
* @param original that is going to be reversed
*/
public Reversed(BooleanComparator original) {
this.original = original;
}
public int compare(boolean o1, boolean o2) {
return original.compare(o2, o1);
}
@Override
public BooleanComparator reversed() {
return original;
}
}
}
@@ -0,0 +1,48 @@
package speiger.src.collections.booleans.functions;
import java.util.Objects;
import java.util.function.Consumer;
/**
* Type-Specific Consumer interface that reduces (un)boxing and allows to merge other consumer types into this interface
*/
@FunctionalInterface
public interface BooleanConsumer extends Consumer<Boolean>
{
/**
* Type-Specific function to reduce (un)boxing.
* Performs this operation on the given argument.
*
* @param t the input argument
*/
void accept(boolean t);
/**
* Type Specific sequencing method to reduce boxing/unboxing.
* @param after a operation that should be performed afterwards
* @return a sequenced consumer that does 2 operations
* @throws NullPointerException if after is null
*/
public default BooleanConsumer andThen(BooleanConsumer after) {
Objects.requireNonNull(after);
return T -> {accept(T); after.accept(T);};
}
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
default void accept(Boolean t) { accept(t.booleanValue()); }
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
default BooleanConsumer andThen(Consumer<? super Boolean> after) {
Objects.requireNonNull(after);
return T -> {accept(T); after.accept(Boolean.valueOf(T));};
}
}
@@ -0,0 +1,12 @@
package speiger.src.collections.booleans.functions;
/**
* Type-Specific Supplier interface that reduces (un)boxing and allows to merge other consumer types into this interface
*/
public interface BooleanSupplier
{
/**
* @return the supplied value
*/
public boolean getAsBoolean();
}
@@ -0,0 +1,87 @@
package speiger.src.collections.booleans.functions;
import java.util.concurrent.RunnableFuture;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
*
* A Type Specific Task interface that allows you to keep track of the task that is currently running.<br>
* It extends Runnable future and supports said functions but also provides quality of life functions like:<br>
*
* - isSuccesfull: which allows to detect if the task was completed properly and not interrupted or crashed.
* - pause/resume: which allows to pause/resume the task at any moment, making it easier to create thread-safe actions.
*/
public interface BooleanTask extends RunnableFuture<Boolean> {
/**
* Helper function to detect if the task is currently paused.
* @return true if paused
*/
public boolean isPaused();
/**
* Pauses the task, which lets the thread finish without completing the task.
* Tasks are written in the way where they can pause without any issues.
* This won't be instant, as this function is applied asynchronous and doesn't check if the thread paused.
* So make sure it had the time to pause.
*/
public void pause();
/**
* Pauses the task, which lets the thread finish without completing the task.
* Tasks are written in the way where they can pause without any issues.
* This won't be instant, as this function is applied asynchronous.
* It will await the pausing of the task.
*/
public void awaitPausing();
/**
* Continues the task if it wasn't already completed.
* This is done by resubmitting the task to the executor provided.
*/
public void resume();
/**
* Quality of life function that allows to detect if no cancellation/exception was applied to this task and it completed on its own.
* @return true if it was properly completed
*/
public boolean isSuccessful();
/**
* A Type Specific get method that allows to reduce (un)boxing of primtives.
*
* Waits if necessary for the computation to complete, and then
* retrieves its result.
*
* @return the computed result as primitive
* @throws CancellationException if the computation was cancelled
* @throws ExecutionException if the computation threw an exception
* @throws InterruptedException if the current thread was interrupted
* while waiting
*/
public boolean getBoolean() throws InterruptedException, ExecutionException;
/**
* Waits if necessary for at most the given time for the computation
* to complete, and then retrieves its result, if available.
*
* @param timeout the maximum time to wait
* @param unit the time unit of the timeout argument
* @return the computed result as primitive
* @throws CancellationException if the computation was cancelled
* @throws ExecutionException if the computation threw an exception
* @throws InterruptedException if the current thread was interrupted while waiting
* @throws TimeoutException if the wait timed out
*/
public boolean getBoolean(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException;
@Override
@Deprecated
public default Boolean get() throws InterruptedException, ExecutionException { return Boolean.valueOf(getBoolean()); }
@Override
@Deprecated
public default Boolean get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return Boolean.valueOf(getBoolean(timeout, unit)); }
}
@@ -0,0 +1,89 @@
package speiger.src.collections.booleans.functions;
import java.util.NoSuchElementException;
import java.util.function.Supplier;
public final class OptionalBoolean {
private static final OptionalBoolean EMPTY = new OptionalBoolean();
private final boolean isPresent;
private final boolean value;
private OptionalBoolean() {
this.isPresent = false;
this.value = false;
}
private OptionalBoolean(boolean value) {
this.isPresent = true;
this.value = value;
}
public static OptionalBoolean empty() {
return EMPTY;
}
public static OptionalBoolean of(boolean value) {
return new OptionalBoolean(value);
}
public boolean getAsBoolean() {
if(!isPresent) throw new NoSuchElementException("No value present");
return value;
}
public boolean isPresent() {
return isPresent;
}
public boolean isEmpty() {
return !isPresent;
}
public void ifPresent(BooleanConsumer consumer) {
if(isPresent) consumer.accept(value);
}
public void ifPresentOrElse(BooleanConsumer action, Runnable emptyAction) {
if (isPresent) action.accept(value);
else emptyAction.run();
}
public boolean orElse(boolean other) {
return isPresent ? value : other;
}
public boolean orElseGet(BooleanSupplier other) {
return isPresent ? value : other.getAsBoolean();
}
public boolean orElseThrow() {
if (!isPresent) throw new NoSuchElementException("No value present");
return value;
}
public <X extends Throwable> boolean orElseThrow(Supplier<? extends X> exceptionSupplier) throws X {
if(isPresent) return value;
else throw exceptionSupplier.get();
}
@Override
public boolean equals(Object obj) {
if(obj == this) return true;
if(obj instanceof OptionalBoolean) {
OptionalBoolean other = (OptionalBoolean)obj;
return (isPresent && other.isPresent ? value == other.value : isPresent == other.isPresent);
}
return false;
}
@Override
public int hashCode() {
return isPresent ? Boolean.hashCode(value) : 0;
}
@Override
public String toString() {
return isPresent ? "OptionalBoolean["+value+"]" : "OptionalBoolean.empty";
}
}
@@ -0,0 +1,49 @@
package speiger.src.collections.booleans.functions.consumer;
import java.util.Objects;
import java.util.function.BiConsumer;
/**
* A Type Specific BiConsumer class to reduce boxing/unboxing and that fills the gaps that java has.
*/
public interface BooleanBooleanConsumer extends BiConsumer<Boolean, Boolean>
{
/**
* A Type Specific operation method to reduce boxing/unboxing
* Performs this operation on the given arguments.
*
* @param k the first input argument
* @param v the second input argument
*/
void accept(boolean k, boolean v);
/**
* Type Specific sequencing method to reduce boxing/unboxing.
* @param after a operation that should be performed afterwards
* @return a sequenced biconsumer that does 2 operations
* @throws NullPointerException if after is null
*/
public default BooleanBooleanConsumer andThen(BooleanBooleanConsumer after) {
Objects.requireNonNull(after);
return (K, V) -> {accept(K, V); after.accept(K, V);};
}
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
default void accept(Boolean k, Boolean v) { accept(k.booleanValue(), v.booleanValue()); }
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
default BooleanBooleanConsumer andThen(BiConsumer<? super Boolean, ? super Boolean> after) {
Objects.requireNonNull(after);
return (K, V) -> {accept(K, V); after.accept(Boolean.valueOf(K), Boolean.valueOf(V));};
}
}
@@ -0,0 +1,49 @@
package speiger.src.collections.booleans.functions.consumer;
import java.util.Objects;
import java.util.function.BiConsumer;
/**
* A Type Specific BiConsumer class to reduce boxing/unboxing and that fills the gaps that java has.
*/
public interface BooleanByteConsumer extends BiConsumer<Boolean, Byte>
{
/**
* A Type Specific operation method to reduce boxing/unboxing
* Performs this operation on the given arguments.
*
* @param k the first input argument
* @param v the second input argument
*/
void accept(boolean k, byte v);
/**
* Type Specific sequencing method to reduce boxing/unboxing.
* @param after a operation that should be performed afterwards
* @return a sequenced biconsumer that does 2 operations
* @throws NullPointerException if after is null
*/
public default BooleanByteConsumer andThen(BooleanByteConsumer after) {
Objects.requireNonNull(after);
return (K, V) -> {accept(K, V); after.accept(K, V);};
}
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
default void accept(Boolean k, Byte v) { accept(k.booleanValue(), v.byteValue()); }
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
default BooleanByteConsumer andThen(BiConsumer<? super Boolean, ? super Byte> after) {
Objects.requireNonNull(after);
return (K, V) -> {accept(K, V); after.accept(Boolean.valueOf(K), Byte.valueOf(V));};
}
}
@@ -0,0 +1,49 @@
package speiger.src.collections.booleans.functions.consumer;
import java.util.Objects;
import java.util.function.BiConsumer;
/**
* A Type Specific BiConsumer class to reduce boxing/unboxing and that fills the gaps that java has.
*/
public interface BooleanCharConsumer extends BiConsumer<Boolean, Character>
{
/**
* A Type Specific operation method to reduce boxing/unboxing
* Performs this operation on the given arguments.
*
* @param k the first input argument
* @param v the second input argument
*/
void accept(boolean k, char v);
/**
* Type Specific sequencing method to reduce boxing/unboxing.
* @param after a operation that should be performed afterwards
* @return a sequenced biconsumer that does 2 operations
* @throws NullPointerException if after is null
*/
public default BooleanCharConsumer andThen(BooleanCharConsumer after) {
Objects.requireNonNull(after);
return (K, V) -> {accept(K, V); after.accept(K, V);};
}
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
default void accept(Boolean k, Character v) { accept(k.booleanValue(), v.charValue()); }
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
default BooleanCharConsumer andThen(BiConsumer<? super Boolean, ? super Character> after) {
Objects.requireNonNull(after);
return (K, V) -> {accept(K, V); after.accept(Boolean.valueOf(K), Character.valueOf(V));};
}
}
@@ -0,0 +1,49 @@
package speiger.src.collections.booleans.functions.consumer;
import java.util.Objects;
import java.util.function.BiConsumer;
/**
* A Type Specific BiConsumer class to reduce boxing/unboxing and that fills the gaps that java has.
*/
public interface BooleanDoubleConsumer extends BiConsumer<Boolean, Double>
{
/**
* A Type Specific operation method to reduce boxing/unboxing
* Performs this operation on the given arguments.
*
* @param k the first input argument
* @param v the second input argument
*/
void accept(boolean k, double v);
/**
* Type Specific sequencing method to reduce boxing/unboxing.
* @param after a operation that should be performed afterwards
* @return a sequenced biconsumer that does 2 operations
* @throws NullPointerException if after is null
*/
public default BooleanDoubleConsumer andThen(BooleanDoubleConsumer after) {
Objects.requireNonNull(after);
return (K, V) -> {accept(K, V); after.accept(K, V);};
}
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
default void accept(Boolean k, Double v) { accept(k.booleanValue(), v.doubleValue()); }
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
default BooleanDoubleConsumer andThen(BiConsumer<? super Boolean, ? super Double> after) {
Objects.requireNonNull(after);
return (K, V) -> {accept(K, V); after.accept(Boolean.valueOf(K), Double.valueOf(V));};
}
}
@@ -0,0 +1,49 @@
package speiger.src.collections.booleans.functions.consumer;
import java.util.Objects;
import java.util.function.BiConsumer;
/**
* A Type Specific BiConsumer class to reduce boxing/unboxing and that fills the gaps that java has.
*/
public interface BooleanFloatConsumer extends BiConsumer<Boolean, Float>
{
/**
* A Type Specific operation method to reduce boxing/unboxing
* Performs this operation on the given arguments.
*
* @param k the first input argument
* @param v the second input argument
*/
void accept(boolean k, float v);
/**
* Type Specific sequencing method to reduce boxing/unboxing.
* @param after a operation that should be performed afterwards
* @return a sequenced biconsumer that does 2 operations
* @throws NullPointerException if after is null
*/
public default BooleanFloatConsumer andThen(BooleanFloatConsumer after) {
Objects.requireNonNull(after);
return (K, V) -> {accept(K, V); after.accept(K, V);};
}
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
default void accept(Boolean k, Float v) { accept(k.booleanValue(), v.floatValue()); }
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
default BooleanFloatConsumer andThen(BiConsumer<? super Boolean, ? super Float> after) {
Objects.requireNonNull(after);
return (K, V) -> {accept(K, V); after.accept(Boolean.valueOf(K), Float.valueOf(V));};
}
}
@@ -0,0 +1,49 @@
package speiger.src.collections.booleans.functions.consumer;
import java.util.Objects;
import java.util.function.BiConsumer;
/**
* A Type Specific BiConsumer class to reduce boxing/unboxing and that fills the gaps that java has.
*/
public interface BooleanIntConsumer extends BiConsumer<Boolean, Integer>
{
/**
* A Type Specific operation method to reduce boxing/unboxing
* Performs this operation on the given arguments.
*
* @param k the first input argument
* @param v the second input argument
*/
void accept(boolean k, int v);
/**
* Type Specific sequencing method to reduce boxing/unboxing.
* @param after a operation that should be performed afterwards
* @return a sequenced biconsumer that does 2 operations
* @throws NullPointerException if after is null
*/
public default BooleanIntConsumer andThen(BooleanIntConsumer after) {
Objects.requireNonNull(after);
return (K, V) -> {accept(K, V); after.accept(K, V);};
}
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
default void accept(Boolean k, Integer v) { accept(k.booleanValue(), v.intValue()); }
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
default BooleanIntConsumer andThen(BiConsumer<? super Boolean, ? super Integer> after) {
Objects.requireNonNull(after);
return (K, V) -> {accept(K, V); after.accept(Boolean.valueOf(K), Integer.valueOf(V));};
}
}
@@ -0,0 +1,49 @@
package speiger.src.collections.booleans.functions.consumer;
import java.util.Objects;
import java.util.function.BiConsumer;
/**
* A Type Specific BiConsumer class to reduce boxing/unboxing and that fills the gaps that java has.
*/
public interface BooleanLongConsumer extends BiConsumer<Boolean, Long>
{
/**
* A Type Specific operation method to reduce boxing/unboxing
* Performs this operation on the given arguments.
*
* @param k the first input argument
* @param v the second input argument
*/
void accept(boolean k, long v);
/**
* Type Specific sequencing method to reduce boxing/unboxing.
* @param after a operation that should be performed afterwards
* @return a sequenced biconsumer that does 2 operations
* @throws NullPointerException if after is null
*/
public default BooleanLongConsumer andThen(BooleanLongConsumer after) {
Objects.requireNonNull(after);
return (K, V) -> {accept(K, V); after.accept(K, V);};
}
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
default void accept(Boolean k, Long v) { accept(k.booleanValue(), v.longValue()); }
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
default BooleanLongConsumer andThen(BiConsumer<? super Boolean, ? super Long> after) {
Objects.requireNonNull(after);
return (K, V) -> {accept(K, V); after.accept(Boolean.valueOf(K), Long.valueOf(V));};
}
}
@@ -0,0 +1,50 @@
package speiger.src.collections.booleans.functions.consumer;
import java.util.Objects;
import java.util.function.BiConsumer;
/**
* A Type Specific BiConsumer class to reduce boxing/unboxing and that fills the gaps that java has.
* @param <V> the keyType of elements maintained by this Collection
*/
public interface BooleanObjectConsumer<V> extends BiConsumer<Boolean, V>
{
/**
* A Type Specific operation method to reduce boxing/unboxing
* Performs this operation on the given arguments.
*
* @param k the first input argument
* @param v the second input argument
*/
void accept(boolean k, V v);
/**
* Type Specific sequencing method to reduce boxing/unboxing.
* @param after a operation that should be performed afterwards
* @return a sequenced biconsumer that does 2 operations
* @throws NullPointerException if after is null
*/
public default BooleanObjectConsumer<V> andThen(BooleanObjectConsumer<V> after) {
Objects.requireNonNull(after);
return (K, V) -> {accept(K, V); after.accept(K, V);};
}
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
default void accept(Boolean k, V v) { accept(k.booleanValue(), v); }
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
default BooleanObjectConsumer<V> andThen(BiConsumer<? super Boolean, ? super V> after) {
Objects.requireNonNull(after);
return (K, V) -> {accept(K, V); after.accept(Boolean.valueOf(K), V);};
}
}
@@ -0,0 +1,49 @@
package speiger.src.collections.booleans.functions.consumer;
import java.util.Objects;
import java.util.function.BiConsumer;
/**
* A Type Specific BiConsumer class to reduce boxing/unboxing and that fills the gaps that java has.
*/
public interface BooleanShortConsumer extends BiConsumer<Boolean, Short>
{
/**
* A Type Specific operation method to reduce boxing/unboxing
* Performs this operation on the given arguments.
*
* @param k the first input argument
* @param v the second input argument
*/
void accept(boolean k, short v);
/**
* Type Specific sequencing method to reduce boxing/unboxing.
* @param after a operation that should be performed afterwards
* @return a sequenced biconsumer that does 2 operations
* @throws NullPointerException if after is null
*/
public default BooleanShortConsumer andThen(BooleanShortConsumer after) {
Objects.requireNonNull(after);
return (K, V) -> {accept(K, V); after.accept(K, V);};
}
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
default void accept(Boolean k, Short v) { accept(k.booleanValue(), v.shortValue()); }
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
default BooleanShortConsumer andThen(BiConsumer<? super Boolean, ? super Short> after) {
Objects.requireNonNull(after);
return (K, V) -> {accept(K, V); after.accept(Boolean.valueOf(K), Short.valueOf(V));};
}
}
@@ -0,0 +1,17 @@
package speiger.src.collections.booleans.functions.function;
/**
* A Type Specific Function interface that reduces boxing/unboxing and fills the gaps of interfaces that are missing.
*/
@FunctionalInterface
public interface Boolean2BooleanFunction
{
/**
* Type Specific get function to reduce boxing/unboxing
* @param k the value that should be processed
* @return the result of the function
*/
public boolean test(boolean k);
}
@@ -0,0 +1,17 @@
package speiger.src.collections.booleans.functions.function;
/**
* A Type Specific Function interface that reduces boxing/unboxing and fills the gaps of interfaces that are missing.
*/
@FunctionalInterface
public interface Boolean2ByteFunction
{
/**
* Type Specific get function to reduce boxing/unboxing
* @param k the value that should be processed
* @return the result of the function
*/
public byte applyAsByte(boolean k);
}
@@ -0,0 +1,17 @@
package speiger.src.collections.booleans.functions.function;
/**
* A Type Specific Function interface that reduces boxing/unboxing and fills the gaps of interfaces that are missing.
*/
@FunctionalInterface
public interface Boolean2CharFunction
{
/**
* Type Specific get function to reduce boxing/unboxing
* @param k the value that should be processed
* @return the result of the function
*/
public char applyAsChar(boolean k);
}
@@ -0,0 +1,17 @@
package speiger.src.collections.booleans.functions.function;
/**
* A Type Specific Function interface that reduces boxing/unboxing and fills the gaps of interfaces that are missing.
*/
@FunctionalInterface
public interface Boolean2DoubleFunction
{
/**
* Type Specific get function to reduce boxing/unboxing
* @param k the value that should be processed
* @return the result of the function
*/
public double applyAsDouble(boolean k);
}
@@ -0,0 +1,17 @@
package speiger.src.collections.booleans.functions.function;
/**
* A Type Specific Function interface that reduces boxing/unboxing and fills the gaps of interfaces that are missing.
*/
@FunctionalInterface
public interface Boolean2FloatFunction
{
/**
* Type Specific get function to reduce boxing/unboxing
* @param k the value that should be processed
* @return the result of the function
*/
public float applyAsFloat(boolean k);
}
@@ -0,0 +1,17 @@
package speiger.src.collections.booleans.functions.function;
/**
* A Type Specific Function interface that reduces boxing/unboxing and fills the gaps of interfaces that are missing.
*/
@FunctionalInterface
public interface Boolean2IntFunction
{
/**
* Type Specific get function to reduce boxing/unboxing
* @param k the value that should be processed
* @return the result of the function
*/
public int applyAsInt(boolean k);
}
@@ -0,0 +1,17 @@
package speiger.src.collections.booleans.functions.function;
/**
* A Type Specific Function interface that reduces boxing/unboxing and fills the gaps of interfaces that are missing.
*/
@FunctionalInterface
public interface Boolean2LongFunction
{
/**
* Type Specific get function to reduce boxing/unboxing
* @param k the value that should be processed
* @return the result of the function
*/
public long applyAsLong(boolean k);
}
@@ -0,0 +1,18 @@
package speiger.src.collections.booleans.functions.function;
/**
* A Type Specific Function interface that reduces boxing/unboxing and fills the gaps of interfaces that are missing.
* @param <V> the keyType of elements maintained by this Collection
*/
@FunctionalInterface
public interface Boolean2ObjectFunction<V>
{
/**
* Type Specific get function to reduce boxing/unboxing
* @param k the value that should be processed
* @return the result of the function
*/
public V apply(boolean k);
}
@@ -0,0 +1,17 @@
package speiger.src.collections.booleans.functions.function;
/**
* A Type Specific Function interface that reduces boxing/unboxing and fills the gaps of interfaces that are missing.
*/
@FunctionalInterface
public interface Boolean2ShortFunction
{
/**
* Type Specific get function to reduce boxing/unboxing
* @param k the value that should be processed
* @return the result of the function
*/
public short applyAsShort(boolean k);
}
@@ -0,0 +1,22 @@
package speiger.src.collections.booleans.functions.function;
import java.util.function.BiFunction;
/**
* A Type Specific Unary Operator to support Compute/Merge functions with type specific methods to reduce boxing/unboxing
*/
public interface BooleanBooleanUnaryOperator extends BiFunction<Boolean, Boolean, Boolean>
{
/**
* A Type Specifc apply method to reduce boxing/unboxing.
* Applies this function to the given arguments.
*
* @param k the first function argument
* @param v the second function argument
* @return the function result
*/
public boolean applyAsBoolean(boolean k, boolean v);
@Override
public default Boolean apply(Boolean k, Boolean v) { return Boolean.valueOf(applyAsBoolean(k.booleanValue(), v.booleanValue())); }
}
@@ -0,0 +1,22 @@
package speiger.src.collections.booleans.functions.function;
import java.util.function.BiFunction;
/**
* A Type Specific Unary Operator to support Compute/Merge functions with type specific methods to reduce boxing/unboxing
*/
public interface BooleanByteUnaryOperator extends BiFunction<Boolean, Byte, Byte>
{
/**
* A Type Specifc apply method to reduce boxing/unboxing.
* Applies this function to the given arguments.
*
* @param k the first function argument
* @param v the second function argument
* @return the function result
*/
public byte applyAsByte(boolean k, byte v);
@Override
public default Byte apply(Boolean k, Byte v) { return Byte.valueOf(applyAsByte(k.booleanValue(), v.byteValue())); }
}
@@ -0,0 +1,22 @@
package speiger.src.collections.booleans.functions.function;
import java.util.function.BiFunction;
/**
* A Type Specific Unary Operator to support Compute/Merge functions with type specific methods to reduce boxing/unboxing
*/
public interface BooleanCharUnaryOperator extends BiFunction<Boolean, Character, Character>
{
/**
* A Type Specifc apply method to reduce boxing/unboxing.
* Applies this function to the given arguments.
*
* @param k the first function argument
* @param v the second function argument
* @return the function result
*/
public char applyAsChar(boolean k, char v);
@Override
public default Character apply(Boolean k, Character v) { return Character.valueOf(applyAsChar(k.booleanValue(), v.charValue())); }
}
@@ -0,0 +1,22 @@
package speiger.src.collections.booleans.functions.function;
import java.util.function.BiFunction;
/**
* A Type Specific Unary Operator to support Compute/Merge functions with type specific methods to reduce boxing/unboxing
*/
public interface BooleanDoubleUnaryOperator extends BiFunction<Boolean, Double, Double>
{
/**
* A Type Specifc apply method to reduce boxing/unboxing.
* Applies this function to the given arguments.
*
* @param k the first function argument
* @param v the second function argument
* @return the function result
*/
public double applyAsDouble(boolean k, double v);
@Override
public default Double apply(Boolean k, Double v) { return Double.valueOf(applyAsDouble(k.booleanValue(), v.doubleValue())); }
}
@@ -0,0 +1,22 @@
package speiger.src.collections.booleans.functions.function;
import java.util.function.BiFunction;
/**
* A Type Specific Unary Operator to support Compute/Merge functions with type specific methods to reduce boxing/unboxing
*/
public interface BooleanFloatUnaryOperator extends BiFunction<Boolean, Float, Float>
{
/**
* A Type Specifc apply method to reduce boxing/unboxing.
* Applies this function to the given arguments.
*
* @param k the first function argument
* @param v the second function argument
* @return the function result
*/
public float applyAsFloat(boolean k, float v);
@Override
public default Float apply(Boolean k, Float v) { return Float.valueOf(applyAsFloat(k.booleanValue(), v.floatValue())); }
}
@@ -0,0 +1,18 @@
package speiger.src.collections.booleans.functions.function;
/**
* A Type Specific Function interface that reduces boxing/unboxing and fills the gaps of interfaces that are missing.
* @param <V> the keyType of elements maintained by this Collection
*/
@FunctionalInterface
public interface BooleanFunction<V>
{
/**
* Type Specific get function to reduce boxing/unboxing
* @param k the value that should be processed
* @return the result of the function
*/
public V apply(boolean k);
}
@@ -0,0 +1,22 @@
package speiger.src.collections.booleans.functions.function;
import java.util.function.BiFunction;
/**
* A Type Specific Unary Operator to support Compute/Merge functions with type specific methods to reduce boxing/unboxing
*/
public interface BooleanIntUnaryOperator extends BiFunction<Boolean, Integer, Integer>
{
/**
* A Type Specifc apply method to reduce boxing/unboxing.
* Applies this function to the given arguments.
*
* @param k the first function argument
* @param v the second function argument
* @return the function result
*/
public int applyAsInt(boolean k, int v);
@Override
public default Integer apply(Boolean k, Integer v) { return Integer.valueOf(applyAsInt(k.booleanValue(), v.intValue())); }
}
@@ -0,0 +1,22 @@
package speiger.src.collections.booleans.functions.function;
import java.util.function.BiFunction;
/**
* A Type Specific Unary Operator to support Compute/Merge functions with type specific methods to reduce boxing/unboxing
*/
public interface BooleanLongUnaryOperator extends BiFunction<Boolean, Long, Long>
{
/**
* A Type Specifc apply method to reduce boxing/unboxing.
* Applies this function to the given arguments.
*
* @param k the first function argument
* @param v the second function argument
* @return the function result
*/
public long applyAsLong(boolean k, long v);
@Override
public default Long apply(Boolean k, Long v) { return Long.valueOf(applyAsLong(k.booleanValue(), v.longValue())); }
}
@@ -0,0 +1,23 @@
package speiger.src.collections.booleans.functions.function;
import java.util.function.BiFunction;
/**
* A Type Specific Unary Operator to support Compute/Merge functions with type specific methods to reduce boxing/unboxing
* @param <V> the keyType of elements maintained by this Collection
*/
public interface BooleanObjectUnaryOperator<V> extends BiFunction<Boolean, V, V>
{
/**
* A Type Specifc apply method to reduce boxing/unboxing.
* Applies this function to the given arguments.
*
* @param k the first function argument
* @param v the second function argument
* @return the function result
*/
public V apply(boolean k, V v);
@Override
public default V apply(Boolean k, V v) { return apply(k.booleanValue(), v); }
}
@@ -0,0 +1,98 @@
package speiger.src.collections.booleans.functions.function;
import java.util.Objects;
/**
* A Type Specific Function interface that reduces boxing/unboxing and fills the gaps of interfaces that are missing.
*/
@FunctionalInterface
public interface BooleanPredicate
{
/**
* Type Specific get function to reduce boxing/unboxing
* @param k the value that should be processed
* @return the result of the function
*/
public boolean test(boolean k);
/**
* Creates a Default function that returns the input provided.
* @return a input returning function
*/
public static BooleanPredicate identity() {
return T -> T;
}
/**
* Returns a composed function that first applies the {@code before}
* function to its input, and then applies this function to the result.
* If evaluation of either function throws an exception, it is relayed to
* the caller of the composed function.
*
* @param before the function that should be used first
* @return a composed function with a different starting function.
*/
public default BooleanPredicate compose(BooleanPredicate before) {
Objects.requireNonNull(before);
return T -> test(before.test(T));
}
/**
* Returns a composed function that first applies this function to
* its input, and then applies the {@code after} function to the result.
* If evaluation of either function throws an exception, it is relayed to
* the caller of the composed function.
*
* @param after the function that should be used last
* @return a composed function with a different starting function.
*/
public default BooleanPredicate andThen(BooleanPredicate after) {
Objects.requireNonNull(after);
return T -> after.test(test(T));
}
/**
* Creates a Always true function that may be useful if you don't need to process information or just want a default.
* @return a default returning function
*/
public static BooleanPredicate alwaysTrue() {
return T -> true;
}
/**
* Creates a Always false function that may be useful if you don't need to process information or just want a default.
* @return a default returning function
*/
public static BooleanPredicate alwaysFalse() {
return T -> false;
}
/**
* A Type specific and-function helper function that reduces boxing/unboxing
* @param other the other function that should be merged with.
* @return a function that compares values in a and comparason
*/
public default BooleanPredicate andType(BooleanPredicate other) {
Objects.requireNonNull(other);
return T -> test(T) && other.test(T);
}
/**
* A type specific inverter function
* @return the same function but inverts the result
*/
public default BooleanPredicate negate() {
return T -> !test(T);
}
/**
* A Type specific or-function helper function that reduces boxing/unboxing
* @param other the other function that should be merged with.
* @return a function that compares values in a or comparason
*/
public default BooleanPredicate orType(BooleanPredicate other) {
Objects.requireNonNull(other);
return T -> test(T) || other.test(T);
}
}
@@ -0,0 +1,22 @@
package speiger.src.collections.booleans.functions.function;
import java.util.function.BiFunction;
/**
* A Type Specific Unary Operator to support Compute/Merge functions with type specific methods to reduce boxing/unboxing
*/
public interface BooleanShortUnaryOperator extends BiFunction<Boolean, Short, Short>
{
/**
* A Type Specifc apply method to reduce boxing/unboxing.
* Applies this function to the given arguments.
*
* @param k the first function argument
* @param v the second function argument
* @return the function result
*/
public short applyAsShort(boolean k, short v);
@Override
public default Short apply(Boolean k, Short v) { return Short.valueOf(applyAsShort(k.booleanValue(), v.shortValue())); }
}
@@ -0,0 +1,807 @@
package speiger.src.collections.booleans.lists;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.RandomAccess;
import speiger.src.collections.booleans.collections.AbstractBooleanCollection;
import speiger.src.collections.booleans.collections.BooleanCollection;
import speiger.src.collections.booleans.collections.BooleanIterator;
import speiger.src.collections.booleans.collections.BooleanSplititerator;
import speiger.src.collections.ints.lists.IntList;
import speiger.src.collections.booleans.utils.BooleanSplititerators;
import speiger.src.collections.utils.SanityChecks;
/**
* Abstract implementation of the {@link BooleanList} interface.
*/
public abstract class AbstractBooleanList extends AbstractBooleanCollection implements BooleanList
{
/**
* A Type-Specific implementation of add function that delegates to {@link List#add(int, Object)}
*/
@Override
public boolean add(boolean e) {
add(size(), e);
return true;
}
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
public void add(int index, Boolean element) {
add(index, element.booleanValue());
}
/**
* A Type-Specific implementation that iterates over the elements and adds them.
* @param c the elements that wants to be added
* @return true if the list was modified
*/
@Override
public boolean addAll(BooleanCollection c) {
return addAll(size(), c);
}
/**
* A Type-Specific implementation that iterates over the elements and adds them.
* @param c the elements that wants to be added
* @return true if the list was modified
*/
@Override
public boolean addAll(BooleanList c) {
return addAll(size(), c);
}
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
public boolean addAll(Collection<? extends Boolean> c) {
return c instanceof BooleanCollection ? addAll((BooleanCollection)c) : addAll(size(), c);
}
/**
* The IndexOf implementation iterates over all elements and compares them to the search value.
* @param o the value that the index is searched for.
* @return index of the value that was searched for. -1 if not found
* @note it is highly suggested not to use this with Primitives because of boxing. But it is still supported because of ObjectComparason that are custom objects and allow to find the contents.
*/
@Override
@Deprecated
public int indexOf(Object o) {
BooleanListIterator iter = listIterator();
if(o == null) return -1;
while(iter.hasNext()) {
if(Objects.equals(o, Boolean.valueOf(iter.nextBoolean())))
return iter.previousIndex();
}
return -1;
}
/**
* The lastIndexOf implementation iterates over all elements and compares them to the search value.
* @param o the value that the index is searched for.
* @return the last index of the value that was searched for. -1 if not found
* @note it is highly suggested not to use this with Primitives because of boxing. But it is still supported because of ObjectComparason that are custom objects and allow to find the contents.
*/
@Override
@Deprecated
public int lastIndexOf(Object o) {
BooleanListIterator iter = listIterator(size());
if(o == null) return -1;
while(iter.hasPrevious()) {
if(Objects.equals(o, Boolean.valueOf(iter.previousBoolean())))
return iter.nextIndex();
}
return -1;
}
/**
* The indexOf implementation iterates over all elements and compares them to the search value.
* @param e the value that the index is searched for.
* @return index of the value that was searched for. -1 if not found
*/
@Override
public int indexOf(boolean e) {
BooleanListIterator iter = listIterator();
while(iter.hasNext()) {
if(iter.nextBoolean() == e)
return iter.previousIndex();
}
return -1;
}
/**
* The lastIndexOf implementation iterates over all elements and compares them to the search value.
* @param e the value that the index is searched for.
* @return the last index of the value that was searched for. -1 if not found
*/
@Override
public int lastIndexOf(boolean e) {
BooleanListIterator iter = listIterator(size());
while(iter.hasPrevious()) {
if(iter.previousBoolean() == e)
return iter.nextIndex();
}
return -1;
}
@Override
public boolean swapRemoveBoolean(boolean e) {
int index = indexOf(e);
if(index == -1) return false;
swapRemove(index);
return true;
}
/**
* Compares if the list are the same.
*/
@Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof List))
return false;
List<?> l = (List<?>)o;
if(l.size() != size()) return false;
if(l instanceof BooleanList)
{
BooleanListIterator e1 = listIterator();
BooleanListIterator e2 = ((BooleanList)l).listIterator();
while (e1.hasNext() && e2.hasNext()) {
if(!(e1.nextBoolean() == e2.nextBoolean()))
return false;
}
return !(e1.hasNext() || e2.hasNext());
}
ListIterator<Boolean> e1 = listIterator();
ListIterator<?> e2 = l.listIterator();
while (e1.hasNext() && e2.hasNext()) {
if(!Objects.equals(e1.next(), e2.next()))
return false;
}
return !(e1.hasNext() || e2.hasNext());
}
/**
* Generates the hashcode based on the values stored in the list.
*/
@Override
public int hashCode() {
int hashCode = 1;
BooleanListIterator i = listIterator();
while(i.hasNext())
hashCode = 31 * hashCode + Boolean.hashCode(i.nextBoolean());
return hashCode;
}
@Override
public BooleanList subList(int fromIndex, int toIndex) {
SanityChecks.checkArrayCapacity(size(), fromIndex, toIndex-fromIndex);
return new SubList(this, 0, fromIndex, toIndex);
}
@Override
public BooleanList reversed() {
return new ReversedList(this);
}
@Override
public BooleanIterator iterator() {
return listIterator(0);
}
@Override
public BooleanListIterator listIterator() {
return listIterator(0);
}
@Override
public BooleanListIterator listIterator(int index) {
if(index < 0 || index > size()) throw new IndexOutOfBoundsException();
return new BooleanListIter(index);
}
@Override
public BooleanListIterator indexedIterator(int...indecies) {
return new IndexedIterator(indecies);
}
@Override
public BooleanListIterator indexedIterator(IntList indecies) {
return new ListIndexedIterator(indecies);
}
@Override
public void size(int size) {
while(size > size()) add(false);
while(size < size()) removeBoolean(size() - 1);
}
public AbstractBooleanList copy() { throw new UnsupportedOperationException(); }
private class ReversedList extends AbstractBooleanList
{
final AbstractBooleanList list;
public ReversedList(AbstractBooleanList list) {
this.list = list;
}
@Override
public void add(int index, boolean e) {
list.add(list.size() - index - 1, e);
}
@Override
public boolean addAll(int index, BooleanCollection c) {
return addCollection(index, c);
}
@Override
public boolean addAll(int index, BooleanList c) {
if(c instanceof RandomAccess) {
for(int i = 0,m=c.size();i<m;i++) {
list.add(list.size() - index - i - 1, c.getBoolean(i));
}
return true;
}
return addCollection(index, c);
}
private boolean addCollection(int index, BooleanCollection c) {
int i = 0;
for(BooleanIterator iter = c.iterator();iter.hasNext();i++) {
list.add(list.size() - index - i - 1, iter.nextBoolean());
}
return true;
}
@Override
public boolean addAll(int index, Collection<? extends Boolean> c) {
int i = 0;
for(Iterator<? extends Boolean> iter = c.iterator();iter.hasNext();i++) {
list.add(list.size() - index - i - 1, iter.next());
}
return true;
}
@Override
public boolean getBoolean(int index) {
return list.getBoolean(list.size() - index - 1);
}
@Override
public boolean set(int index, boolean e) {
return list.set(list.size() - index - 1, e);
}
@Override
public boolean removeBoolean(int index) {
return list.removeBoolean(list.size() - index - 1);
}
@Override
public void addElements(int from, boolean[] a, int offset, int length) {
for(int i = 0,m=length;i<m;i++) {
list.add(list.size() - from - i - 1, a[i+offset]);
}
}
@Override
public boolean[] getElements(int from, boolean[] a, int offset, int length) {
return reverse(list.getElements(list.size() - from - 1, a, offset, length));
}
@Override
public void removeElements(int from, int to) {
list.removeElements(list.size() - to - 1, list.size() - from - 1);
}
@Override
public boolean swapRemove(int index) {
return list.swapRemove(list.size() - index - 1);
}
@Override
public boolean[] extractElements(int from, int to) {
return reverse(list.extractElements(list.size() - to - 1, list.size() - from - 1));
}
@Override
public int size() {
return list.size();
}
@Override
public void clear() {
list.clear();
}
@Override
public BooleanList reversed() {
return list;
}
private boolean[] reverse(boolean[] data) {
for (int i = 0, mid = data.length >> 1, j = data.length - 1; i < mid; i++, j--) {
boolean t = data[i];
data[i] = data[j];
data[j] = t;
}
return data;
}
}
private class SubList extends AbstractBooleanList
{
final AbstractBooleanList list;
final int parentOffset;
final int offset;
int size;
public SubList(AbstractBooleanList list, int offset, int from, int to) {
this.list = list;
this.parentOffset = from;
this.offset = offset + from;
this.size = to - from;
}
@Override
public void add(int index, boolean element) {
checkAddSubRange(index);
list.add(parentOffset+index, element);
size++;
}
@Override
public boolean addAll(int index, Collection<? extends Boolean> c) {
checkAddSubRange(index);
int add = c.size();
if(add <= 0) return false;
list.addAll(parentOffset+index, c);
this.size += add;
return true;
}
@Override
public boolean addAll(int index, BooleanCollection c) {
checkAddSubRange(index);
int add = c.size();
if(add <= 0) return false;
list.addAll(parentOffset+index, c);
this.size += add;
return true;
}
@Override
public boolean addAll(int index, BooleanList c) {
checkAddSubRange(index);
int add = c.size();
if(add <= 0) return false;
list.addAll(parentOffset+index, c);
this.size += add;
return true;
}
@Override
public void addElements(int from, boolean[] a, int offset, int length) {
checkAddSubRange(from);
if(length <= 0) return;
list.addElements(parentOffset+from, a, offset, length);
this.size += length;
}
@Override
public boolean[] getElements(int from, boolean[] a, int offset, int length) {
SanityChecks.checkArrayCapacity(size, from, length);
SanityChecks.checkArrayCapacity(a.length, offset, length);
return list.getElements(from+parentOffset, a, offset, length);
}
@Override
public void removeElements(int from, int to) {
if(to-from <= 0) return;
checkSubRange(from);
checkAddSubRange(to);
list.removeElements(from+parentOffset, to+parentOffset);
size -= to - from;
}
@Override
public boolean[] extractElements(int from, int to) {
checkSubRange(from);
checkAddSubRange(to);
boolean[] result = list.extractElements(from+parentOffset, to+parentOffset);
size -= result.length;
return result;
}
@Override
public boolean getBoolean(int index) {
checkSubRange(index);
return list.getBoolean(parentOffset+index);
}
@Override
public boolean set(int index, boolean element) {
checkSubRange(index);
return list.set(parentOffset+index, element);
}
@Override
public boolean swapRemove(int index) {
checkSubRange(index);
if(index == size-1) {
boolean result = list.removeBoolean(parentOffset+size-1);
size--;
return result;
}
boolean result = list.set(index+parentOffset, list.getBoolean(parentOffset+size-1));
list.removeBoolean(parentOffset+size-1);
size--;
return result;
}
@Override
public boolean removeBoolean(int index) {
checkSubRange(index);
boolean result = list.removeBoolean(index+parentOffset);
size--;
return result;
}
@Override
public int size() {
return size;
}
@Override
public BooleanSplititerator spliterator() { return BooleanSplititerators.createSplititerator(this, 16464); }
@Override
public BooleanListIterator listIterator(int index) {
if(index < 0 || index > size()) throw new IndexOutOfBoundsException();
return new SubListIterator(this, index);
}
@Override
public BooleanList subList(int fromIndex, int toIndex) {
SanityChecks.checkArrayCapacity(size, fromIndex, toIndex-fromIndex);
return new SubList(this, offset, fromIndex, toIndex);
}
protected void checkSubRange(int index) {
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
}
protected void checkAddSubRange(int index) {
if (index < 0 || index > size)
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
}
private class SubListIterator implements BooleanListIterator
{
AbstractBooleanList list;
int index;
int lastReturned = -1;
SubListIterator(AbstractBooleanList list, int index) {
this.list = list;
this.index = index;
}
@Override
public boolean hasNext() {
return index < list.size();
}
@Override
public boolean nextBoolean() {
if(!hasNext()) throw new NoSuchElementException();
int i = index++;
return list.getBoolean((lastReturned = i));
}
@Override
public boolean hasPrevious() {
return index > 0;
}
@Override
public boolean previousBoolean() {
if(!hasPrevious()) throw new NoSuchElementException();
index--;
return list.getBoolean((lastReturned = index));
}
@Override
public int nextIndex() {
return index;
}
@Override
public int previousIndex() {
return index-1;
}
@Override
public void remove() {
if(lastReturned == -1) throw new IllegalStateException();
list.removeBoolean(lastReturned);
index = lastReturned;
lastReturned = -1;
}
@Override
public void set(boolean e) {
if(lastReturned == -1) throw new IllegalStateException();
list.set(lastReturned, e);
}
@Override
public void add(boolean e) {
list.add(index, e);
index++;
lastReturned = -1;
}
@Override
public int skip(int amount) {
if(amount < 0) throw new IllegalStateException("Negative Numbers are not allowed");
int steps = Math.min(amount, size() - index);
index += steps;
if(steps > 0) lastReturned = Math.min(index-1, size()-1);
return steps;
}
@Override
public int back(int amount) {
if(amount < 0) throw new IllegalStateException("Negative Numbers are not allowed");
int steps = Math.min(amount, index);
index -= steps;
if(steps > 0) lastReturned = Math.min(index, size()-1);
return steps;
}
}
}
private class ListIndexedIterator implements BooleanListIterator {
IntList indecies;
int index;
int lastReturned = -1;
ListIndexedIterator(IntList indecies) {
this.indecies = indecies;
}
@Override
public boolean hasNext() {
return index < indecies.size();
}
@Override
public boolean nextBoolean() {
if(!hasNext()) throw new NoSuchElementException();
int i = index++;
return getBoolean((lastReturned = indecies.getInt(i)));
}
@Override
public boolean hasPrevious() {
return index > 0;
}
@Override
public boolean previousBoolean() {
if(!hasPrevious()) throw new NoSuchElementException();
index--;
return getBoolean((lastReturned = indecies.getInt(index)));
}
@Override
public int nextIndex() {
return index;
}
@Override
public int previousIndex() {
return index-1;
}
@Override
public void remove() { throw new UnsupportedOperationException(); }
@Override
public void add(boolean e) { throw new UnsupportedOperationException(); }
@Override
public void set(boolean e) {
if(lastReturned == -1) throw new IllegalStateException();
AbstractBooleanList.this.set(lastReturned, e);
}
@Override
public int skip(int amount) {
if(amount < 0) throw new IllegalStateException("Negative Numbers are not allowed");
int steps = Math.min(amount, indecies.size() - index);
index += steps;
if(steps > 0) lastReturned = Math.min(index-1, indecies.size()-1);
return steps;
}
@Override
public int back(int amount) {
if(amount < 0) throw new IllegalStateException("Negative Numbers are not allowed");
int steps = Math.min(amount, index);
index -= steps;
if(steps > 0) lastReturned = Math.max(index, 0);
return steps;
}
}
private class IndexedIterator implements BooleanListIterator {
int[] indecies;
int index;
int lastReturned = -1;
IndexedIterator(int[] indecies) {
this.indecies = indecies;
}
@Override
public boolean hasNext() {
return index < indecies.length;
}
@Override
public boolean nextBoolean() {
if(!hasNext()) throw new NoSuchElementException();
int i = index++;
return getBoolean((lastReturned = indecies[i]));
}
@Override
public boolean hasPrevious() {
return index > 0;
}
@Override
public boolean previousBoolean() {
if(!hasPrevious()) throw new NoSuchElementException();
index--;
return getBoolean((lastReturned = indecies[index]));
}
@Override
public int nextIndex() {
return index;
}
@Override
public int previousIndex() {
return index-1;
}
@Override
public void remove() { throw new UnsupportedOperationException(); }
@Override
public void add(boolean e) { throw new UnsupportedOperationException(); }
@Override
public void set(boolean e) {
if(lastReturned == -1) throw new IllegalStateException();
AbstractBooleanList.this.set(lastReturned, e);
}
@Override
public int skip(int amount) {
if(amount < 0) throw new IllegalStateException("Negative Numbers are not allowed");
int steps = Math.min(amount, indecies.length - index);
index += steps;
if(steps > 0) lastReturned = Math.min(index-1, indecies.length-1);
return steps;
}
@Override
public int back(int amount) {
if(amount < 0) throw new IllegalStateException("Negative Numbers are not allowed");
int steps = Math.min(amount, index);
index -= steps;
if(steps > 0) lastReturned = Math.max(index, 0);
return steps;
}
}
private class BooleanListIter implements BooleanListIterator {
int index;
int lastReturned = -1;
BooleanListIter(int index) {
this.index = index;
}
@Override
public boolean hasNext() {
return index < size();
}
@Override
public boolean nextBoolean() {
if(!hasNext()) throw new NoSuchElementException();
int i = index++;
return getBoolean((lastReturned = i));
}
@Override
public boolean hasPrevious() {
return index > 0;
}
@Override
public boolean previousBoolean() {
if(!hasPrevious()) throw new NoSuchElementException();
index--;
return getBoolean((lastReturned = index));
}
@Override
public int nextIndex() {
return index;
}
@Override
public int previousIndex() {
return index-1;
}
@Override
public void remove() {
if(lastReturned == -1) throw new IllegalStateException();
AbstractBooleanList.this.removeBoolean(lastReturned);
index = lastReturned;
lastReturned = -1;
}
@Override
public void set(boolean e) {
if(lastReturned == -1) throw new IllegalStateException();
AbstractBooleanList.this.set(lastReturned, e);
}
@Override
public void add(boolean e) {
AbstractBooleanList.this.add(index, e);
index++;
lastReturned = -1;
}
@Override
public int skip(int amount) {
if(amount < 0) throw new IllegalStateException("Negative Numbers are not allowed");
int steps = Math.min(amount, size() - index);
index += steps;
if(steps > 0) lastReturned = Math.min(index-1, size()-1);
return steps;
}
@Override
public int back(int amount) {
if(amount < 0) throw new IllegalStateException("Negative Numbers are not allowed");
int steps = Math.min(amount, index);
index -= steps;
if(steps > 0) lastReturned = Math.max(index, 0);
return steps;
}
}
}
@@ -0,0 +1,911 @@
package speiger.src.collections.booleans.lists;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.Objects;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;
import speiger.src.collections.booleans.collections.BooleanCollection;
import speiger.src.collections.booleans.collections.BooleanStack;
import speiger.src.collections.booleans.collections.BooleanIterator;
import speiger.src.collections.booleans.functions.OptionalBoolean;
import speiger.src.collections.booleans.functions.BooleanComparator;
import speiger.src.collections.booleans.functions.BooleanConsumer;
import speiger.src.collections.objects.functions.consumer.ObjectBooleanConsumer;
import speiger.src.collections.booleans.functions.function.BooleanPredicate;
import speiger.src.collections.booleans.functions.function.BooleanBooleanUnaryOperator;
import speiger.src.collections.booleans.utils.BooleanArrays;
import speiger.src.collections.objects.utils.ObjectArrays;
import speiger.src.collections.booleans.utils.BooleanIterators;
import speiger.src.collections.booleans.utils.IBooleanArray;
import speiger.src.collections.booleans.collections.BooleanSplititerator;
import speiger.src.collections.booleans.utils.BooleanSplititerators;
import speiger.src.collections.utils.SanityChecks;
/**
* A Type-Specific Array-based implementation of list that is written to reduce (un)boxing
*
* <p>This implementation is optimized to improve how data is processed with interfaces like {@link IBooleanArray}, {@link BooleanStack}
* and with optimized functions that use type-specific implementations for primitives and optimized logic for bulkactions.
*
*/
public class BooleanArrayList extends AbstractBooleanList implements IBooleanArray, BooleanStack
{
static final int DEFAULT_ARRAY_SIZE = 10;
/** The backing array */
protected transient boolean[] data;
/** The current size of the elements stored in the backing array */
protected int size = 0;
/**
* Creates a new ArrayList with a Empty array.
*/
public BooleanArrayList() {
data = BooleanArrays.EMPTY_ARRAY;
}
/**
* Creates a new ArrayList with the specific requested size
* @param size the minimum initial size of the Backing array
*/
public BooleanArrayList(int size) {
if(size < 0) throw new IllegalStateException("Size has to be 0 or greater");
data = new boolean[size];
}
/**
* Creates a new ArrayList a copy with the contents of the Collection.
* @param c the elements that should be added into the list
*/
@Deprecated
public BooleanArrayList(Collection<? extends Boolean> c) {
this(c.size());
size = BooleanIterators.unwrap(data, c.iterator());
}
/**
* Creates a new ArrayList a copy with the contents of the Collection.
* @param c the elements that should be added into the list
*/
public BooleanArrayList(BooleanCollection c) {
this(c.size());
size = BooleanIterators.unwrap(data, c.iterator());
}
/**
* Creates a new ArrayList a copy with the contents of the List.
* @param l the elements that should be added into the list
*/
public BooleanArrayList(BooleanList l) {
this(l.size());
size = l.size();
l.getElements(0, data, 0, size);
}
/**
* Creates a new ArrayList with a Copy of the array
* @param a the array that should be copied
*/
public BooleanArrayList(boolean... a) {
this(a, 0, a.length);
}
/**
* Creates a new ArrayList with a Copy of the array with a custom length
* @param a the array that should be copied
* @param length the desired length that should be copied
*/
public BooleanArrayList(boolean[] a, int length) {
this(a, 0, length);
}
/**
* Creates a new ArrayList with a Copy of the array with in the custom range.
* @param a the array that should be copied
* @param offset the starting offset of where the array should be copied from
* @param length the desired length that should be copied
* @throws IllegalStateException if offset is smaller then 0
* @throws IllegalStateException if the offset + length exceeds the array length
*/
public BooleanArrayList(boolean[] a, int offset, int length) {
this(length);
SanityChecks.checkArrayCapacity(a.length, offset, length);
System.arraycopy(a, offset, data, 0, length);
size = length;
}
/**
* Creates a wrapped arraylist that uses the array as backing array
* @param a elements that should be wrapped
* @return a Wrapped list using the input array
*/
public static BooleanArrayList wrap(boolean... a) {
return wrap(a, a.length);
}
/**
* Creates a wrapped arraylist that uses the array as backing array and a custom fill size
* @param a elements that should be wrapped
* @param length the size of the elements within the array
* @return a Wrapped list using the input array
*/
public static BooleanArrayList wrap(boolean[] a, int length) {
SanityChecks.checkArrayCapacity(a.length, 0, length);
BooleanArrayList list = new BooleanArrayList();
list.data = a;
list.size = length;
return list;
}
/**
* Appends the specified element to the end of this list.
*
* @param e element to be appended to this list
* @return true (as specified by {@link Collection#add})
*/
@Override
public boolean add(boolean e) {
grow(size + 1);
data[size++] = e;
return true;
}
/**
* Appends the specified element to the end of this Stack.
* @param e element to be appended to this Stack
*/
@Override
public void push(boolean e) {
add(e);
}
/**
* Appends the specified element to the index of the list
* @param index the index where to append the element to
* @param e the element to append to the list
* @throws IndexOutOfBoundsException if index is outside of the lists range
*/
@Override
public void add(int index, boolean e) {
checkAddRange(index);
grow(size + 1);
if(index != size) System.arraycopy(data, index, data, index+1, size - index);
data[index] = e;
size++;
}
/**
* Appends the specified elements to the index of the list.
* This function may delegate to more appropriate function if necessary
* @param index the index where to append the elements to
* @param c the elements to append to the list
* @throws IndexOutOfBoundsException if index is outside of the lists range
* @throws NullPointerException if collection contains a null element
*/
@Override
@Deprecated
public boolean addAll(int index, Collection<? extends Boolean> c) {
if(c instanceof BooleanCollection) return addAll(index, (BooleanCollection)c);
int add = c.size();
if(add <= 0) return false;
if(c.contains(null)) throw new NullPointerException();
grow(size + add);
if(index != size) System.arraycopy(data, index, data, index+add, size - index);
size+=add;
Iterator<? extends Boolean> iter = c.iterator();
while(add-- != 0) data[index++] = iter.next().booleanValue();
return true;
}
/**
* Appends the specified elements to the index of the list.
* This function may delegate to more appropriate function if necessary
* @param index the index where to append the elements to
* @param c the elements to append to the list
* @throws IndexOutOfBoundsException if index is outside of the lists range
*/
@Override
public boolean addAll(int index, BooleanCollection c) {
if(c instanceof BooleanList) return addAll(index, (BooleanList)c);
int add = c.size();
if(add <= 0) return false;
grow(size + add);
if(index != size) System.arraycopy(data, index, data, index+add, size - index);
size+=add;
BooleanIterator iter = c.iterator();
while(add-- != 0) data[index++] = iter.nextBoolean();
return true;
}
/**
* Appends the specified elements to the index of the list.
* @param index the index where to append the elements to
* @param c the elements to append to the list
* @throws IndexOutOfBoundsException if index is outside of the lists range
*/
@Override
public boolean addAll(int index, BooleanList c) {
int add = c.size();
if(add <= 0) return false;
checkAddRange(index);
grow(size + add);
if(index != size) System.arraycopy(data, index, data, index+add, size - index);
size+=add;
c.getElements(0, data, index, c.size());
return true;
}
@Override
public boolean addAll(boolean[] e, int offset, int length) {
if(length <= 0) return false;
SanityChecks.checkArrayCapacity(e.length, offset, length);
grow(size + length);
System.arraycopy(e, offset, data, size, length);
size+=length;
return true;
}
/**
* Appends the specified array elements to the index of the list.
* @param from the index where to append the elements to
* @param a the elements to append to the list
* @param offset where to start ino the array
* @param length the amount of elements to insert
* @throws IndexOutOfBoundsException if index is outside of the lists range
*/
@Override
public void addElements(int from, boolean[] a, int offset, int length) {
if(length <= 0) return;
checkAddRange(from);
SanityChecks.checkArrayCapacity(a.length, offset, length);
grow(size + length);
if(from != size) System.arraycopy(data, from, data, from+length, size - from);
size+=length;
System.arraycopy(a, offset, data, from, length);
}
/**
* A function to fast fetch elements from the list
* @param from index where the list should be fetching elements from
* @param a the array where the values should be inserted to
* @param offset the startIndex of where the array should be written to
* @param length the number of elements the values should be fetched from
* @return the inputArray
* @throws NullPointerException if the array is null
* @throws IndexOutOfBoundsException if from is outside of the lists range
* @throws IllegalStateException if offset or length are smaller then 0 or exceed the array length
*/
@Override
public boolean[] getElements(int from, boolean[] a, int offset, int length) {
SanityChecks.checkArrayCapacity(size, from, length);
SanityChecks.checkArrayCapacity(a.length, offset, length);
System.arraycopy(data, from, a, offset, length);
return a;
}
/**
* a function to fast remove elements from the list.
* @param from the start index of where the elements should be removed from (inclusive)
* @param to the end index of where the elements should be removed to (exclusive)
*/
@Override
public void removeElements(int from, int to) {
checkRange(from);
checkAddRange(to);
int length = to - from;
if(length <= 0) return;
if(to != size) System.arraycopy(data, to, data, from, size - to);
size -= length;
}
/**
* A function to fast extract elements out of the list, this removes the elements that were fetched.
* @param from the start index of where the elements should be fetched from (inclusive)
* @param to the end index of where the elements should be fetched to (exclusive)
* @return a array of the elements that were fetched
*/
@Override
public boolean[] extractElements(int from, int to) {
int length = to - from;
if(length <= 0) return BooleanArrays.EMPTY_ARRAY;
boolean[] a = new boolean[length];
System.arraycopy(data, from, a, 0, length);
if(to != size) System.arraycopy(data, to, data, from, size - to);
size -= length;
return a;
}
/**
* A function to find if the Element is present in this list.
* @param o the element that is searched for
* @return if the element was found.
*/
@Override
@Deprecated
public boolean contains(Object o) {
return indexOf(o) != -1;
}
/**
* A function to find the index of a given element
* @param o the element that is searched for
* @return the index of the element if found. (if not found then -1)
*/
@Override
@Deprecated
public int indexOf(Object o) {
if(o == null) return -1;
for(int i = 0;i<size;i++) {
if(Objects.equals(o, Boolean.valueOf(data[i]))) return i;
}
return -1;
}
/**
* A function to find the last index of a given element
* @param o the element that is searched for
* @return the last index of the element if found. (if not found then -1)
*/
@Override
@Deprecated
public int lastIndexOf(Object o) {
if(o == null) return -1;
for(int i = size - 1;i>=0;i--) {
if(Objects.equals(o, Boolean.valueOf(data[i]))) return i;
}
return -1;
}
/**
* A Type Specific implementation of the Collection#contains function.
* @param e the element that is searched for.
* @return if the element was found
*/
@Override
public boolean contains(boolean e) {
return indexOf(e) != -1;
}
/**
* A Type-Specific function to find the index of a given element
* @param e the element that is searched for
* @return the index of the element if found. (if not found then -1)
*/
@Override
public int indexOf(boolean e) {
for(int i = 0;i<size;i++) {
if(data[i] == e) return i;
}
return -1;
}
/**
* A Type-Specific function to find the last index of a given element
* @param e the element that is searched for
* @return the last index of the element if found. (if not found then -1)
*/
@Override
public int lastIndexOf(boolean e) {
for(int i = size - 1;i>=0;i--) {
if(data[i] == e) return i;
}
return -1;
}
/**
* Sorts the elements specified by the Natural order either by using the Comparator or the elements
* @param c the sorter of the elements, can be null
* @see java.util.List#sort(java.util.Comparator)
* @see BooleanArrays#stableSort(boolean[], BooleanComparator)
*/
@Override
public void sort(BooleanComparator c) {
if(c != null) BooleanArrays.stableSort(data, size, c);
else BooleanArrays.stableSort(data, size);
}
/**
* Sorts the elements specified by the Natural order either by using the Comparator or the elements using a unstable sort
* @param c the sorter of the elements, can be null
* @see java.util.List#sort(java.util.Comparator)
* @see BooleanArrays#unstableSort(boolean[], BooleanComparator)
*/
@Override
public void unstableSort(BooleanComparator c) {
if(c != null) BooleanArrays.unstableSort(data, size, c);
else BooleanArrays.unstableSort(data, size);
}
/**
* A Type-Specific get function to reduce (un)boxing
* @param index the index of the element to fetch
* @return the value of the requested index
* @throws IndexOutOfBoundsException if the index is out of range
*/
@Override
public boolean getBoolean(int index) {
checkRange(index);
return data[index];
}
/**
* Provides the Selected Object from the stack.
* Top to bottom
* @param index of the element that should be provided
* @return the element that was requested
* @throws ArrayIndexOutOfBoundsException if the index is out of bounds
* @see speiger.src.collections.utils.Stack#peek(int)
*/
@Override
public boolean peek(int index) {
checkRange((size() - 1) - index);
return data[(size() - 1) - index];
}
/**
* Provides the Underlying Array in the Implementation
* @return underlying Array
* @throws ClassCastException if the return type does not match the underlying array. (Only for Object Implementations)
*/
@Override
public boolean[] elements() {
return data;
}
/**
* A Type Specific foreach function that reduces (un)boxing
*
* @implSpec
* <p>The default implementation behaves as if:
* <pre>{@code
* for(int i = 0;i<size;i++)
* action.accept(data[i]);
* }</pre>
*
* @param action The action to be performed for each element
* @throws NullPointerException if the specified action is null
* @see Iterable#forEach(java.util.function.Consumer)
*/
@Override
public void forEach(BooleanConsumer action) {
Objects.requireNonNull(action);
for(int i = 0;i<size;i++)
action.accept(data[i]);
}
@Override
public <E> void forEach(E input, ObjectBooleanConsumer<E> action) {
Objects.requireNonNull(action);
for(int i = 0;i<size;i++)
action.accept(input, data[i]);
}
@Override
public boolean matchesAny(BooleanPredicate filter) {
Objects.requireNonNull(filter);
for(int i = 0;i<size;i++) {
if(filter.test(data[i])) return true;
}
return false;
}
@Override
public boolean matchesNone(BooleanPredicate filter) {
Objects.requireNonNull(filter);
for(int i = 0;i<size;i++) {
if(filter.test(data[i])) return false;
}
return true;
}
@Override
public boolean matchesAll(BooleanPredicate filter) {
Objects.requireNonNull(filter);
for(int i = 0;i<size;i++) {
if(!filter.test(data[i])) return false;
}
return true;
}
@Override
public OptionalBoolean findFirst(BooleanPredicate filter) {
Objects.requireNonNull(filter);
for(int i = 0;i<size;i++) {
if(filter.test(data[i])) return OptionalBoolean.of(data[i]);
}
return OptionalBoolean.empty();
}
@Override
public boolean reduce(boolean identity, BooleanBooleanUnaryOperator operator) {
Objects.requireNonNull(operator);
boolean state = identity;
for(int i = 0;i<size;i++) {
state = operator.applyAsBoolean(state, data[i]);
}
return state;
}
@Override
public OptionalBoolean reduce(BooleanBooleanUnaryOperator operator) {
Objects.requireNonNull(operator);
boolean state = false;
boolean empty = true;
for(int i = 0;i<size;i++) {
if(empty) {
empty = false;
state = data[i];
continue;
}
state = operator.applyAsBoolean(state, data[i]);
}
return empty ? OptionalBoolean.empty() : OptionalBoolean.of(state);
}
@Override
public int count(BooleanPredicate filter) {
Objects.requireNonNull(filter);
int result = 0;
for(int i = 0;i<size;i++) {
if(filter.test(data[i])) result++;
}
return result;
}
/**
* A Type-Specific set function to reduce (un)boxing
* @param index the index of the element to set
* @param e the value that should be set
* @return the previous element
* @throws IndexOutOfBoundsException if the index is out of range
*/
@Override
public boolean set(int index, boolean e) {
checkRange(index);
boolean old = data[index];
data[index] = e;
return old;
}
/**
* A function to replace all values in the list
* @param o the action to replace the values
* @throws NullPointerException if o is null
*/
@Override
@Deprecated
public void replaceAll(UnaryOperator<Boolean> o) {
Objects.requireNonNull(o);
for(int i = 0;i<size;i++)
data[i] = o.apply(Boolean.valueOf(data[i])).booleanValue();
}
/**
* A Type-Specific remove function to reduce (un)boxing
* @param index the index of the element to fetch
* @return the value of the requested index
* @throws IndexOutOfBoundsException if the index is out of range
*/
@Override
public boolean removeBoolean(int index) {
checkRange(index);
boolean old = data[index];
size--;
if(index != size) System.arraycopy(data, index+1, data, index, size - index);
return old;
}
public boolean swapRemove(int index) {
checkRange(index);
boolean old = data[index];
size--;
data[index] = data[size];
return old;
}
/**
* A Type-Specific implementation of remove. This implementation iterates over the elements until it finds the element that is searched for or it runs out of elements.
* It stops after finding the first element
* @param type the element that is searched for
* @return true if the element was found and removed.
*/
@Override
public boolean remBoolean(boolean type) {
int index = indexOf(type);
if(index == -1) return false;
removeBoolean(index);
return true;
}
/**
* A Type-Specific pop function to reduce (un)boxing
* @return the value of the requested index
* @throws IndexOutOfBoundsException if the index is out of range
*/
@Override
public boolean pop() {
return removeBoolean(size() - 1);
}
/**
* A function to remove all elements that were provided in the other collection
* This function might delegate to a more appropriate function if necessary
* @param c the elements that should be removed
* @return true if the collection was modified
* @throws NullPointerException if the collection is null
*/
@Override
@Deprecated
public boolean removeAll(Collection<?> c) {
if(c.isEmpty()) return false;
boolean modified = false;
int j = 0;
for(int i = 0;i<size;i++) {
if(!c.contains(Boolean.valueOf(data[i]))) data[j++] = data[i];
else modified = true;
}
size = j;
return modified;
}
/**
* A function to retain all elements that were provided in the other collection
* This function might delegate to a more appropriate function if necessary
* @param c the elements that should be kept. If empty, BooleanArrayList#clear is called.
* @return true if the collection was modified
* @throws NullPointerException if the collection is null
*/
@Override
@Deprecated
public boolean retainAll(Collection<?> c) {
if(c.isEmpty()) {
boolean modifed = size > 0;
clear();
return modifed;
}
boolean modified = false;
int j = 0;
for(int i = 0;i<size;i++) {
if(c.contains(Boolean.valueOf(data[i]))) data[j++] = data[i];
else modified = true;
}
size = j;
return modified;
}
/**
* A optimized List#removeIf(Predicate) that more quickly removes elements from the list then the ArrayList implementation
* @param filter the filter to remove elements
* @return true if the list was modified
*/
@Override
@Deprecated
public boolean removeIf(Predicate<? super Boolean> filter) {
Objects.requireNonNull(filter);
boolean modified = false;
int j = 0;
for(int i = 0;i<size;i++) {
if(!filter.test(Boolean.valueOf(data[i]))) data[j++] = data[i];
else modified = true;
}
size = j;
return modified;
}
/**
* A function to remove all elements that were provided in the other collection
* @param c the elements that should be removed
* @return true if the collection was modified
* @throws NullPointerException if the collection is null
*/
@Override
public boolean removeAll(BooleanCollection c) {
if(c.isEmpty()) return false;
boolean modified = false;
int j = 0;
for(int i = 0;i<size;i++) {
if(!c.contains(data[i])) data[j++] = data[i];
else modified = true;
}
size = j;
return modified;
}
@Override
public boolean removeAll(BooleanCollection c, BooleanConsumer r) {
if(c.isEmpty()) return false;
int j = 0;
for(int i = 0;i<size;i++) {
if(!c.contains(data[i])) data[j++] = data[i];
else r.accept(data[i]);
}
boolean modified = j != size;
size = j;
return modified;
}
/**
* A function to retain all elements that were provided in the other collection
* This function might delegate to a more appropriate function if necessary
* @param c the elements that should be kept. If empty, BooleanArrayList#clear is called.
* @return true if the collection was modified
* @throws NullPointerException if the collection is null
*/
@Override
public boolean retainAll(BooleanCollection c) {
if(c.isEmpty()) {
boolean modifed = size > 0;
clear();
return modifed;
}
boolean modified = false;
int j = 0;
for(int i = 0;i<size;i++) {
if(c.contains(data[i])) data[j++] = data[i];
else modified = true;
}
size = j;
return modified;
}
@Override
public boolean retainAll(BooleanCollection c, BooleanConsumer r) {
if(c.isEmpty()) {
boolean modifed = size > 0;
forEach(r);
clear();
return modifed;
}
int j = 0;
for(int i = 0;i<size;i++) {
if(c.contains(data[i])) data[j++] = data[i];
else r.accept(data[i]);
}
boolean modified = j != size;
size = j;
return modified;
}
/**
* A toArray implementation that ensures the Array itself is a Object.
* @return a Array of the elements in the list
*/
@Override
@Deprecated
public Object[] toArray() {
if(size == 0) return ObjectArrays.EMPTY_ARRAY;
Object[] obj = new Object[size];
for(int i = 0;i<size;i++)
obj[i] = Boolean.valueOf(data[i]);
return obj;
}
/**
* A toArray implementation that ensures the Array itself is a Object.
* @param a original array. If null a Object array with the right size is created. If to small the Array of the same type is created with the right size
* @return a Array of the elements in the list
*/
@Override
@Deprecated
public <E> E[] toArray(E[] a) {
if(a == null) a = (E[])new Object[size];
else if(a.length < size) a = (E[])ObjectArrays.newArray(a.getClass().getComponentType(), size);
for(int i = 0;i<size;i++)
a[i] = (E)Boolean.valueOf(data[i]);
if (a.length > size) a[size] = null;
return a;
}
@Override
public boolean[] toBooleanArray(boolean[] a) {
if(a.length < size) a = new boolean[size];
System.arraycopy(data, 0, a, 0, size);
if (a.length > size) a[size] = false;
return a;
}
/**
* A function to return the size of the list
* @return the size of elements in the list
*/
@Override
public int size() {
return size;
}
/**
* A function to ensure the elements are within the requested size.
* If smaller then the stored elements they get removed as needed.
* If bigger it is ensured that enough room is provided depending on the implementation
* @param size the requested amount of elements/room for elements
*/
@Override
public void size(int size) {
if(size > data.length)
data = Arrays.copyOf(data, size);
else if(size < size() && size >= 0)
Arrays.fill(data, size, size(), false);
this.size = size;
}
/**
* A function to clear all elements in the list.
*/
@Override
public void clear() {
size = 0;
}
/**
* Trims the original collection down to the size of the current elements or the requested size depending which is bigger
* @param size the requested trim size.
*/
@Override
public boolean trim(int size) {
if(size > size() || size() == data.length) return false;
int value = Math.max(size, size());
data = value == 0 ? BooleanArrays.EMPTY_ARRAY : Arrays.copyOf(data, value);
return true;
}
/**
* Trims the collection down to the requested size and clears all elements while doing so
* @param size the amount of elements that should be allowed
* @note this will enforce minimum size of the collection itself
*/
@Override
public void clearAndTrim(int size) {
if(data.length <= size) {
clear();
return;
}
data = size == 0 ? BooleanArrays.EMPTY_ARRAY : new boolean[size];
this.size = size;
}
/**
* Increases the capacity of this implementation instance, if necessary,
* to ensure that it can hold at least the number of elements specified by
* the minimum capacity argument.
*
* @param size the desired minimum capacity
*/
@Override
public void ensureCapacity(int size) {
grow(size);
}
@Override
public BooleanArrayList copy() {
BooleanArrayList list = new BooleanArrayList();
list.data = Arrays.copyOf(data, data.length);
list.size = size;
return list;
}
protected void grow(int capacity) {
if(capacity <= data.length) return;
data = Arrays.copyOf(data, data == BooleanArrays.EMPTY_ARRAY ? Math.max(DEFAULT_ARRAY_SIZE, capacity) : (int)Math.max(Math.min((long)data.length + (data.length >> 1), SanityChecks.MAX_ARRAY_SIZE), capacity));
}
protected void checkRange(int index) {
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
}
protected void checkAddRange(int index) {
if (index < 0 || index > size)
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
}
/**
* A Type Specific Type Splititerator to reduce boxing/unboxing
* @return type specific splititerator
* @note characteristics are ordered, sized, subsized
*/
@Override
public BooleanSplititerator spliterator() { return BooleanSplititerators.createArraySplititerator(data, size, 16464); }
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,493 @@
package speiger.src.collections.booleans.lists;
import java.util.List;
import java.util.Objects;
import java.util.Comparator;
import speiger.src.collections.booleans.collections.BooleanCollection;
import speiger.src.collections.booleans.collections.BooleanOrderedCollection;
import speiger.src.collections.booleans.collections.BooleanSplititerator;
import speiger.src.collections.ints.functions.consumer.IntBooleanConsumer;
import speiger.src.collections.booleans.functions.BooleanComparator;
import speiger.src.collections.booleans.utils.BooleanArrays;
import speiger.src.collections.booleans.utils.BooleanLists;
import speiger.src.collections.ints.lists.IntList;
import speiger.src.collections.booleans.utils.BooleanSplititerators;
/**
* A Type Specific List interface that reduces boxing/unboxing and adds a couple extra quality of life features
*/
public interface BooleanList extends BooleanOrderedCollection, List<Boolean>
{
/**
* A Type-Specific add Function to reduce (un)boxing
* @param e the element to add
* @return true if the list was modified
* @see List#add(Object)
*/
@Override
public boolean add(boolean e);
/**
* A Type-Specific add Function to reduce (un)boxing
* @param e the element to add
* @param index index at which the specified element is to be inserted
* @see List#add(int, Object)
*/
public void add(int index, boolean e);
/**
* A Helper function that will only add elements if it is not present.
* @param e the element to add
* @return true if the list was modified
*/
public default boolean addIfAbsent(boolean e) {
if(indexOf(e) == -1) return add(e);
return false;
}
/**
* A Helper function that will only add elements if it is present.
* @param e the element to add
* @return true if the list was modified
*/
public default boolean addIfPresent(boolean e) {
if(indexOf(e) != -1) return add(e);
return false;
}
/**
* A Type-Specific addAll Function to reduce (un)boxing
* @param c the elements that need to be added
* @param index index at which the specified elements is to be inserted
* @return true if the list was modified
* @see java.util.List#addAll(int, java.util.Collection)
*/
public boolean addAll(int index, BooleanCollection c);
/**
* A Type-Specific and optimized addAll function that allows a faster transfer of elements
* @param c the elements that need to be added
* @return true if the list was modified
*/
public boolean addAll(BooleanList c);
/**
* A Type-Specific and optimized addAll function that allows a faster transfer of elements
* @param c the elements that need to be added
* @param index index at which the specified elements is to be inserted
* @return true if the list was modified
*/
public boolean addAll(int index, BooleanList c);
/**
* A method to add an element to the start of a list
* @param e that should be added at the start.
*/
@Override
public default void addFirst(boolean e) {
add(0, e);
}
/**
* A method to add an element to the end of a list
* @param e that should be added at the end.
*/
@Override
public default void addLast(boolean e) {
add(e);
}
/**
* Helper method that returns the first element of a List.
* This function was introduced due to how annoying it is to get/remove the last element of a list.
* This simplifies this process a bit.
* @return first element of the list
*/
public default boolean getFirstBoolean() {
return getBoolean(0);
}
/**
* Helper method that returns the last element of a List.
* This function was introduced due to how annoying it is to get/remove the last element of a list.
* This simplifies this process a bit.
* @return last element of the list
*/
public default boolean getLastBoolean() {
return getBoolean(size() - 1);
}
/**
* Helper method that removes and returns the first element of a List.
* This function was introduced due to how annoying it is to get/remove the last element of a list.
* This simplifies this process a bit.
* @return first element of the list and removes it
*/
public default boolean removeFirstBoolean() {
return removeBoolean(0);
}
/**
* Helper method that removes and returns the last element of a List.
* This function was introduced due to how annoying it is to get/remove the last element of a list.
* This simplifies this process a bit.
* @return last element of the list and removes it
*/
public default boolean removeLastBoolean() {
return removeBoolean(size() - 1);
}
/**
* A Type-Specific get function to reduce (un)boxing
* @param index the index of the value that is requested
* @return the value at the given index
* @throws IndexOutOfBoundsException if the index is not within the list range
* @see List#get(int)
*/
public boolean getBoolean(int index);
/**
* A Type-Specific set function to reduce (un)boxing
* @param index index of the element to replace
* @param e element to be stored at the specified position
* @return the element previously at the specified position
* @throws IndexOutOfBoundsException if the index is not within the list range
* @see List#set(int, Object)
*/
public boolean set(int index, boolean e);
/**
* A Type-Specific remove function to reduce (un)boxing
* @param index the index of the element to be removed
* @return the element previously at the specified position
* @see List#remove(int)
*/
public boolean removeBoolean(int index);
/**
* A Type-Specific indexOf function to reduce (un)boxing
* @param e the element that is searched for
* @return the index of the element if found. (if not found then -1)
* @note does not support null values
*/
public int indexOf(boolean e);
/**
* A Type-Specific lastIndexOf function to reduce (un)boxing
* @param e the element that is searched for
* @return the lastIndex of the element if found. (if not found then -1)
* @note does not support null values
*/
public int lastIndexOf(boolean e);
/**
* A function to fast add elements to the list
* @param a the elements that should be added
* @throws IndexOutOfBoundsException if from is outside of the lists range
*/
public default void addElements(boolean... a) { addElements(size(), a, 0, a.length); }
/**
* A function to fast add elements to the list
* @param from the index where the elements should be added into the list
* @param a the elements that should be added
* @throws IndexOutOfBoundsException if from is outside of the lists range
*/
public default void addElements(int from, boolean... a) { addElements(from, a, 0, a.length); }
/**
* A function to fast add elements to the list
* @param from the index where the elements should be added into the list
* @param a the elements that should be added
* @param offset the start index of the array should be read from
* @param length how many elements should be read from
* @throws IndexOutOfBoundsException if from is outside of the lists range
*/
public void addElements(int from, boolean[] a, int offset, int length);
/**
* A function to fast fetch elements from the list
* @param from index where the list should be fetching elements from
* @param a the array where the values should be inserted to
* @return the inputArray
* @throws NullPointerException if the array is null
* @throws IndexOutOfBoundsException if from is outside of the lists range
* @throws IllegalStateException if offset or length are smaller then 0 or exceed the array length
*/
public default boolean[] getElements(int from, boolean[] a) { return getElements(from, a, 0, a.length); }
/**
* A function to fast fetch elements from the list
* @param from index where the list should be fetching elements from
* @param a the array where the values should be inserted to
* @param offset the startIndex of where the array should be written to
* @param length the number of elements the values should be fetched from
* @return the inputArray
* @throws NullPointerException if the array is null
* @throws IndexOutOfBoundsException if from is outside of the lists range
* @throws IllegalStateException if offset or length are smaller then 0 or exceed the array length
*/
public boolean[] getElements(int from, boolean[] a, int offset, int length);
/**
* a function to fast remove elements from the list.
* @param from the start index of where the elements should be removed from (inclusive)
* @param to the end index of where the elements should be removed to (exclusive)
*/
public void removeElements(int from, int to);
/**
* A Highly Optimized remove function that removes the desired element.
* But instead of shifting the elements to the left it moves the last element to the removed space.
* @param index the index of the element to be removed
* @return the element previously at the specified position
*/
public boolean swapRemove(int index);
/**
* A Highly Optimized remove function that removes the desired element.
* But instead of shifting the elements to the left it moves the last element to the removed space.
* @param e the element that should be removed
* @return true if the element was removed
*/
public boolean swapRemoveBoolean(boolean e);
/**
* A function to fast extract elements out of the list, this removes the elements that were fetched.
* @param from the start index of where the elements should be fetched from (inclusive)
* @param to the end index of where the elements should be fetched to (exclusive)
* @return a array of the elements that were fetched
*/
public boolean[] extractElements(int from, int to);
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
default void sort(Comparator<? super Boolean> c) {
sort((K, V) -> c.compare(Boolean.valueOf(K), Boolean.valueOf(V)));
}
/**
* Sorts the elements specified by the Natural order either by using the Comparator or the elements
* @param c the sorter of the elements, can be null
* @see java.util.List#sort(Comparator)
* @see BooleanArrays#stableSort(boolean[], BooleanComparator)
*/
public default void sort(BooleanComparator c) {
boolean[] array = toBooleanArray();
if(c != null) BooleanArrays.stableSort(array, c);
else BooleanArrays.stableSort(array);
BooleanListIterator iter = listIterator();
for (int i = 0,m=size();i<m && iter.hasNext();i++) {
iter.nextBoolean();
iter.set(array[i]);
}
}
/**
* <p>This default implementation delegates to the corresponding type-specific function.
* @param c the sorter of the elements, can be null
* @deprecated Please use the corresponding type-specific function instead.
*/
@Deprecated
public default void unstableSort(Comparator<? super Boolean> c) {
unstableSort((K, V) -> c.compare(Boolean.valueOf(K), Boolean.valueOf(V)));
}
/**
* Sorts the elements specified by the Natural order either by using the Comparator or the elements using a unstable sort
* @param c the sorter of the elements, can be null
* @see java.util.List#sort(Comparator)
* @see BooleanArrays#unstableSort(boolean[], BooleanComparator)
*/
public default void unstableSort(BooleanComparator c) {
boolean[] array = toBooleanArray();
if(c != null) BooleanArrays.unstableSort(array, c);
else BooleanArrays.unstableSort(array);
BooleanListIterator iter = listIterator();
for (int i = 0,m=size();i<m && iter.hasNext();i++) {
iter.nextBoolean();
iter.set(array[i]);
}
}
/**
* A Indexed forEach implementation that allows you to keep track of how many elements were already iterated over.
* @param action The action to be performed for each element
* @throws java.lang.NullPointerException if the specified action is null
*/
@Override
public default void forEachIndexed(IntBooleanConsumer action) {
Objects.requireNonNull(action);
for(int i = 0,m=size();i<m;action.accept(i, getBoolean(i++)));
}
/**
* A Type-Specific Iterator of listIterator
* @see java.util.List#listIterator
*/
@Override
public BooleanListIterator listIterator();
/**
* A Type-Specific Iterator of listIterator
* @see java.util.List#listIterator(int)
*/
@Override
public BooleanListIterator listIterator(int index);
/**
* Creates a Iterator that follows the indecies provided.<br>
* For example if the Lists Contents is:<br> -1, 0 1 <br>and the indecies are: <br>0, 1, 2, 2, 1, 0<br>
* then the iterator will return the following values: <br>-1, 0, 1, 1, 0, -1
* @param indecies that should be used for the iteration.
* @return a custom indexed iterator
*/
public BooleanListIterator indexedIterator(int...indecies);
/**
* Creates a Iterator that follows the indecies provided.<br>
* For example if the Lists Contents is:<br> -1, 0 1 <br>and the indecies are: <br>0, 1, 2, 2, 1, 0<br>
* then the iterator will return the following values: <br>-1, 0, 1, 1, 0, -1
* @param indecies that should be used for the iteration.
* @return a custom indexed iterator
*/
public BooleanListIterator indexedIterator(IntList indecies);
/**
* A Type-Specific List of subList
* @see java.util.List#subList(int, int)
*/
@Override
public BooleanList subList(int from, int to);
/**
* A Type-Specific List Helper that shows all elements in reverse.
* @return a list wrapper that has all elements reversed!
*/
public BooleanList reversed();
/**
* Creates a Wrapped List that is Synchronized
* @return a new List that is synchronized
* @see BooleanLists#synchronize
*/
public default BooleanList synchronize() { return BooleanLists.synchronize(this); }
/**
* Creates a Wrapped List that is Synchronized
* @param mutex is the controller of the synchronization block
* @return a new List Wrapper that is synchronized
* @see BooleanLists#synchronize
*/
public default BooleanList synchronize(Object mutex) { return BooleanLists.synchronize(this, mutex); }
/**
* Creates a Wrapped List that is unmodifiable
* @return a new List Wrapper that is unmodifiable
* @see BooleanLists#unmodifiable
*/
public default BooleanList unmodifiable() { return BooleanLists.unmodifiable(this); }
/**
* A function to ensure the elements are within the requested size.
* If smaller then the stored elements they get removed as needed.
* If bigger it is ensured that enough room is provided depending on the implementation
* @param size the requested amount of elements/room for elements
*/
public void size(int size);
@Override
public BooleanList copy();
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
public default boolean add(Boolean e) {
return BooleanOrderedCollection.super.add(e);
}
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
public default Boolean get(int index) {
return Boolean.valueOf(getBoolean(index));
}
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
public default Boolean set(int index, Boolean e) {
return Boolean.valueOf(set(index, e.booleanValue()));
}
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
public default int indexOf(Object o) {
return indexOf(((Boolean)o).booleanValue());
}
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
public default int lastIndexOf(Object o) {
return lastIndexOf(((Boolean)o).booleanValue());
}
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
public default boolean contains(Object o) {
return BooleanOrderedCollection.super.contains(o);
}
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
public default boolean remove(Object o) {
return BooleanOrderedCollection.super.remove(o);
}
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
public default Boolean remove(int index) {
return Boolean.valueOf(removeBoolean(index));
}
/**
* A Type Specific Type Splititerator to reduce boxing/unboxing
* @return type specific splititerator
*/
@Override
default BooleanSplititerator spliterator() { return BooleanSplititerators.createSplititerator(this, 0); }
}
@@ -0,0 +1,65 @@
package speiger.src.collections.booleans.lists;
import java.util.ListIterator;
import speiger.src.collections.booleans.collections.BooleanBidirectionalIterator;
/**
* A Type Specific ListIterator that reduces boxing/unboxing
*/
public interface BooleanListIterator extends ListIterator<Boolean>, BooleanBidirectionalIterator
{
/**
* A Primitive set function to reduce (un)boxing
* @param e the element that should replace the last returned value
* @see ListIterator#set(Object)
*/
public void set(boolean e);
/**
* A Primitive set function to reduce (un)boxing
* @param e the element that should be inserted before the last returned value
* @see ListIterator#set(Object)
*/
public void add(boolean e);
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
public default Boolean previous() {
return BooleanBidirectionalIterator.super.previous();
}
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
public default Boolean next() {
return BooleanBidirectionalIterator.super.next();
}
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
public default void set(Boolean e) {
set(e.booleanValue());
}
/** {@inheritDoc}
* <p>This default implementation delegates to the corresponding type-specific function.
* @deprecated Please use the corresponding type-specific function instead.
*/
@Override
@Deprecated
public default void add(Boolean e) {
add(e.booleanValue());
}
}

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