Mijn vraag
Is het mogelijk om verschillende soorten collecties (HashSet, ArrayList, LinkedList, TreeSet) toe te voegen aan een HashMap als value?
Wat ik probeer, maar wat niet werkt:
Relevante software en hardware die ik gebruik
IntelliJ IDEA, Gradle 7.2, Java 11, Spring Boot
Wat ik al gevonden of geprobeerd heb
Heel veel Google search, maar uiteindelijk kon ik het niet gevonden krijgen. Of ik snap gewoonweg niet hoe 'generics' werken in Java.
Is het mogelijk om verschillende soorten collecties (HashSet, ArrayList, LinkedList, TreeSet) toe te voegen aan een HashMap als value?
Wat ik probeer, maar wat niet werkt:
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
| public enum CollectionType { ArrayList, HashSet, Undefined } public enum MyEnum { One, Two, Three, Four } public class myExampleClass { public void myTestMethod() { CollectionBuilder collectionBuilder= new CollectionBuilder(CollectionType.HashSet); collectionBuilder.addValues(MyEnum.values()).build(); } } public class CollectionBuilder { List<?> arrayList = Collections.EMPTY_LIST; Set<?> hashSet = Collections.EMPTY_SET; CollectionType collectionState = CollectionType.Undefined; HashMap<CollectionType, Collection<?>> collections; public CollectionBuilder(CollectionType type) { newCollection(type); } private void newCollection(CollectionType type) { switch(type) { case ArrayList: arrayList = new ArrayList<>(); collectionState = CollectionType.ArrayList; addCollection(arrayList); break; case HashSet: hashSet = new HashSet<>(); collectionState = CollectionType.HashSet; addCollection(hashSet); break; } } @SuppressWarnings (value="unchecked") public <T extends Enum<T>> CollectionBuilder addValues(T[] values) { Collection<T> collection = (Collection<T>) collections.get(collectionState); collection.addAll(List.of(values)); return this; } @SuppressWarnings (value="unchecked") public <T> Collection<T> build() { return (Collection<T>) collections.get(collectionState); } private <T> void addCollection(Collection<T> collection) { collections.put(collectionState, collection); } } |
Relevante software en hardware die ik gebruik
IntelliJ IDEA, Gradle 7.2, Java 11, Spring Boot
Wat ik al gevonden of geprobeerd heb
Heel veel Google search, maar uiteindelijk kon ik het niet gevonden krijgen. Of ik snap gewoonweg niet hoe 'generics' werken in Java.