Generic collection as a Java method argument
Is there any way to make this work in Java?
public static void change(List<? extends Object> list, int pos1, int pos2) {
Object obj = list.get(pos1);
list.set(pos1, list.get(pos2));
list.set(pos2, obj);
}
The only way I've successfully avoided warnings and errors is this:
public static <T> T 开发者_Python百科change(List<T> list, int pos1, int pos2) {
T obj = list.get(pos1);
list.set(pos1, list.get(pos2));
list.set(pos2, obj);
return obj;
}
but I don't like to be forced to return a value.
Make a generic method
public static <T> void change( List<T> list, int position1, int position2) {
T obj = list.get(position1);
list.set(position1, list.get(position2));
list.set(position2, obj);
}
In java.util.Collections
, there's already a swap(List<?> list, int i, int j)
.
This is how it's implemented in OpenJDK source code:
public static void swap(List<?> list, int i, int j) {
final List l = list;
l.set(i, l.set(j, l.get(i)));
}
Interestingly, it uses a raw List
type to do the job. The code generates warnings at compile time, but presumably @author
Josh Bloch and Neal Gafter think this is tolerable.
Use a capture helper:
public static void change(List<?> list, int pos1, int pos2) {
changePrivate(list, pos1, pos2);
}
public static <T> void change(List<T> list, int pos1, int pos2) {
T obj = list.get(pos1);
list.set(pos1, list.get(pos2));
list.set(pos2, obj);
}
精彩评论