0

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

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Your first example does not work - you will lose the type information. The second is correct.
2

You can do

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

1 Comment

+1 for including a bound on the generic parameter - this seems like it might be relevant based on the question, and even if not it gives the syntax for later adaptation.
1

You can use this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.