James Raitsev
James Raitsev

Reputation: 96581

Java generics: syntax clarification needed

Suppose i have a

List<Integer> l = new ArrayList<Integer>();

and would like to have this list reversed with the help of

public static List<Object> reverseList(List<Object> o);

Thought process here is that one day i may be dealing with Integers and another with Doubles. Would be nice to have a generic method that is able to reverse my Lists

How should reverseList be declared for this to work? Please advise

Upvotes: 0

Views: 75

Answers (3)

NPE
NPE

Reputation: 500933

One way to declare it is

public static <T> List<T> reverseList(List<T> o) {
  ...
}

You might also want to take a look at Collections.reverse.

Upvotes: 3

Kal
Kal

Reputation: 24910

You can do

public static <T extends Number> List<T> reverseList(List<T> o) {

Upvotes: 2

Matthew Gilliard
Matthew Gilliard

Reputation: 9498

You can use this:

public static <T> List<T> reverse(List<T> in);

Upvotes: 1

Related Questions