How to write a Java method that returns a generic type (syntax)

As a quick note, if you need some examples of the syntax of how to write a Java method that returns a generic type, I hope these are helpful:

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

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

I hadn’t written a Java generic method in a while, and I forgot you need to declare the generic type (<T>) early in the method declaration.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.