[fillEnumInList] Filling a List with All Enum Values in Java (#13005)

* [fillEnumInList] Filling a List with All Enum Values in Java

* [fillEnumInList] change the return type in the util method
This commit is contained in:
Kai Yuan 2022-11-15 03:03:18 +01:00 committed by GitHub
parent f250a5c104
commit b52f7ef200
1 changed files with 53 additions and 0 deletions

View File

@ -0,0 +1,53 @@
package com.baeldung.enums.fillinlist;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import static com.baeldung.enums.fillinlist.MagicNumber.*;
import static org.junit.jupiter.api.Assertions.*;
enum MagicNumber {
ONE, TWO, THREE, FOUR, FIVE
}
public class FillEnumsInListUnitTest {
private static final List<MagicNumber> EXPECTED_LIST = Arrays.asList(ONE, TWO, THREE, FOUR, FIVE);
static <T> List<T> enumValuesInList(Class<T> enumCls) {
T[] arr = enumCls.getEnumConstants();
return arr == null ? Collections.emptyList() : Arrays.asList(arr);
}
@Test
void givenEnum_whenUsingArraysAsList_shouldGetExpectedResult() {
List<MagicNumber> result = Arrays.asList(MagicNumber.values());
assertEquals(EXPECTED_LIST, result);
}
@Test
void givenEnum_whenUsingGetEnumConstants_shouldGetExpectedResult() {
List<MagicNumber> result = Arrays.asList(MagicNumber.class.getEnumConstants());
assertEquals(EXPECTED_LIST, result);
}
@Test
void givenEnum_whenUsingenumValuesInList_shouldGetExpectedResult() {
List<MagicNumber> result1 = enumValuesInList(MagicNumber.class);
assertEquals(EXPECTED_LIST, result1);
List<Integer> result2 = enumValuesInList(Integer.class);
assertTrue(result2.isEmpty());
}
@Test
void givenEnum_whenUsingEnumSet_shouldGetExpectedResult() {
List<MagicNumber> result = new ArrayList<>(EnumSet.allOf(MagicNumber.class));
assertEquals(EXPECTED_LIST, result);
}
}