java method return generic type code example

Example 1: java return new instance of generic type

public static <E> void append(List<E> list, Class<E> cls) throws Exception {
    E elem = cls.newInstance();   // OK
    list.add(elem);
}
//You can invoke the append method as follows:
List<String> ls = new ArrayList<>();
append(ls, String.class);

Example 2: Java method that returns a generic type

public static <T> T getRandomValue(List<T> listOfPossibleOutcomes, int numPossibilities) {
    int r = RandomNumberGenerator.getRandIntBetween(0, numPossibilities);
    return listOfPossibleOutcomes.get(r);
}

public static <T> T getRandomValueFromGenericList(List<T> list) {
    Collections.shuffle(list);
    return list.get(0);
}

Tags:

Java Example