Generic collection as a Java method argument

Posted by Guido on Stack Overflow See other posts from Stack Overflow or by Guido
Published on 2010-03-21T10:58:52Z Indexed on 2010/03/21 11:01 UTC
Read the original article Hit count: 461

Is there any way to make this work in Java?

public static void change(List<? extends Object> list, int position1, int position2) {
    Object obj = list.get(position1);
    list.set(position1, list.get(position2));
    list.set(position2, obj);
}

The only way I've successfully avoided warnings and errors is this:

public static <T> T change(List<T> list, int position1, int position2) {
    T obj = list.get(position1);
    list.set(position1, list.get(position2));
    list.set(position2, obj);
    return obj;
}

but I don't like to be forced to return a value.

© Stack Overflow or respective owner

Related posts about java

Related posts about generics