Created
January 18, 2023 20:59
-
-
Save stefanofago73/d99b68e5b66ca97de664eb8043b9b434 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
import java.util.LinkedList; | |
import java.util.List; | |
import java.util.function.Supplier; | |
interface ListDefinition<R> extends Supplier<List<R>>{ | |
default boolean canMutate() { | |
return false; | |
} | |
interface Mutable<R> extends ListDefinition<R> { | |
default boolean canMutate() { | |
return true; | |
} | |
} | |
static <T> ListDefinition<T> immutable(T... values) { | |
return () -> List.of(values); | |
} | |
static <T> ListDefinition<T> mutable(ArrayList<T> values) { | |
return (ListDefinition.Mutable<T>) () -> values; | |
} | |
static <T> ListDefinition<T> mutable(LinkedList<T> values) { | |
return (ListDefinition.Mutable<T>) () -> values; | |
} | |
public static void main(String[] args) { | |
ListDefinition<String> immutable = ListDefinition.immutable("1","3","4"); | |
ListDefinition<String> mutable = ListDefinition.mutable(new ArrayList<>()); | |
ListDefinition<String> mutable2 = ListDefinition.mutable(new LinkedList<>()); | |
System.out.printf("immutable-list: %s is immutable: %s\n",immutable.get(),(!immutable.canMutate())); | |
System.out.printf("immutable-list: %s is mutable: %s\n",immutable.get(),(immutable.canMutate())); | |
System.out.printf("mutable-list: %s is mutable: %s\n",mutable.get(),(mutable.canMutate())); | |
System.out.printf("mutable-list2: %s is mutable: %s\n",mutable2.get(),(mutable2.canMutate())); | |
} | |
}//END |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment