Reputation: 20526
I'm trying to create a simple generic method that swaps two entries in an array but when I call the method it gives the the following error. What am I missing? I'm sure it's an easy fix I just can't see it.
Sorting.java
package testing;
import java.util.Comparator;
public class Sorting {
public static <T> void swap(T[] array, int left, int right){
T temp = array[right];
array[right] = array[left];
array[left] = temp;
}
}
SortTest.java
package testing;
import static testing.Sorting.*;
public class SortTest {
public static void main(String[] args){
int[] nums = {5, 12, 3, 7, 2};
swap(nums, 0, 1);
}
}
Upvotes: 0
Views: 5250
Reputation: 23329
The method signature is a generic Object[]
which you can't assign an int[]
int[] nums = {1};
Object[] o = nums; // doesn't compile
And hence the method won't allow it.
You can use Integer[]
instead.
Integer[] nums = {5, 12, 3, 7, 2};
Note that auto-boxing doesn't work with arrays, when generics methods allow primitives, there is auto-boxing behind the scenes.
Generics and primitives types don't play well together. (Things might get better in Java 10)
Upvotes: 2
Reputation: 58
className.method
or instanceOfClass.method
(this will be translated at compile time in class.method
)Upvotes: 0
Reputation: 198033
There is no way in Java to make a generic method that allows primitives to be accepted. You cannot pass an int[]
to a method that expects a T[]
, nor can you make any method generic over different kinds of primitives. You could use a boxed array like Integer[]
, or you could custom-write an overload that accepted an int[]
.
You also have the problem that you would need to write Sorting.swap(nums, 0, 1)
instead of just swap(nums, 0, 1)
, or you would need to write import static testing.Sorting.swap;
as an import statement.
Upvotes: 2