开发者

Java generics: syntax clarification needed

开发者 https://www.devze.com 2023-03-19 05:03 出处:网络
Suppose i have a List<Integer> l = new ArrayList<Integer>(); and would like to have this list reversed with the help of

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 wi开发者_开发知识库th 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


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.


You can do

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


You can use this:

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

精彩评论

暂无评论...
验证码 换一张
取 消