Skip to content

Commit

Permalink
Allow copy-constructors applied to Collections
Browse files Browse the repository at this point in the history
Instead of requiring a List, which is unnecessary strict. This aligns
with the JDK copy constructors for lists:

public ArrayList(Collection<? extends E> c)
https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#ArrayList-java.util.Collection-

List.copyOf
https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/List.html#copyOf(java.util.Collection)
  • Loading branch information
runeflobakk committed Feb 20, 2024
1 parent d6c3f99 commit 40ed4f4
Showing 1 changed file with 4 additions and 3 deletions.
7 changes: 4 additions & 3 deletions src/main/java/no/digipost/collection/NonEmptyList.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import no.digipost.stream.NonEmptyStream;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Optional;

Expand Down Expand Up @@ -189,8 +190,8 @@ static <E> NonEmptyList<E> ofUnsafe(E[] nonEmptyArray) {
* @return the resulting non-empty list,
* or {@link Optional#empty()} if the given list is empty
*/
static <E> Optional<NonEmptyList<E>> copyOf(List<E> list) {
return firstOf(list).map(first -> NonEmptyList.of(first, new ArrayList<>(list.subList(1, list.size()))));
static <E> Optional<NonEmptyList<E>> copyOf(Collection<E> collection) {
return of(new ArrayList<>(collection));
}


Expand Down Expand Up @@ -227,7 +228,7 @@ static <E> Optional<NonEmptyList<E>> copyOf(E[] array) {
*
* @see #copyOf(List)
*/
static <E> NonEmptyList<E> copyOfUnsafe(List<E> nonEmptyList) {
static <E> NonEmptyList<E> copyOfUnsafe(Collection<E> nonEmptyList) {
return copyOf(nonEmptyList).orElseThrow(() -> new IllegalArgumentException("empty list"));
}

Expand Down

0 comments on commit 40ed4f4

Please sign in to comment.