tags:

views:

137

answers:

2

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 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.

+6  A: 

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);
}
krosenvold
+1 But like poly suggested, I would use a wildcard (?)
Helper Method
@Helper Method I believe the set method wont work with a wildcard, as both type of the list and type of the object inserted would be unknown
josefx
+1 Oh sry, you're right.
Helper Method
+5  A: 

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.

polygenelubricants
Thank you, I've marked @krosenvold answer as accepted, because it answer the question, but I'm going to use Collections#swap, because it is already implemented.
Guido
Interesting implementation... also strange that they marked the list as final.
Helper Method
@Helper Method - You should try to mark everything as final. Less bugs that way. If you do it "right" you will find that about 90-95% of your variables can be made final. Checkstyle and/or PMD have a check to tell you when you have something that could be marked final but is not.
TofuBeer
I always mark member variables final but never local variables. I just try to keep my methods very short :-).
Helper Method