[英]Generic swap method for int array
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 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 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);
}
}
There is no way in Java to make a generic method that allows primitives to be accepted. 在Java中,没有一种方法可以使泛型方法被接受。 You cannot pass an int[]
to a method that expects a T[]
, nor can you make any method generic over different kinds of primitives. 您不能将int[]
传递给需要T[]
,也不能使任何方法在不同类型的基元上通用。 You could use a boxed array like Integer[]
, or you could custom-write an overload that accepted an int[]
. 您可以使用类似Integer[]
的盒装数组,也可以自定义编写接受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;
你也有你需要编写问题Sorting.swap(nums, 0, 1)
而不是仅仅swap(nums, 0, 1)
或者你需要写import static testing.Sorting.swap;
as an import statement. 作为导入语句。
The method signature is a generic Object[]
which you can't assign an int[]
方法签名是一个通用的Object[]
,您不能为其分配一个int[]
int[] nums = {1};
Object[] o = nums; // doesn't compile
And hence the method won't allow it. 因此该方法不允许这样做。 You can use Integer[]
instead. 您可以改用Integer[]
。
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) (在Java 10中情况可能会变得更好)
className.method
or instanceOfClass.method
(this will be translated at compile time in class.method
) 为了调用它,您需要className.method
或instanceOfClass.method
(这将在编译时在class.method
进行翻译)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.