我在玩一些代码katas,并试图在同一时间更好地理解java泛型。我有这样一个打印数组的方法,就像我喜欢看到它们一样,并且我有几个帮助器方法,它们接受'东西'和索引的数组,并返回索引上方或下方'东西'的数组这是一个二进制搜索算法)。你可以传递一个int数组到Java中的泛型方法吗?
两个问题,
#1我能避免在splitBottom和splitTop投至T?它感觉不对,或者我以错误的方式去做(不要告诉我使用python或其他东西..))
#2我是否必须编写单独的方法来处理原语数组还是有更好的解决方案?
public class Util {
public static <T> void print(T[] array) {
System.out.print("{");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i]);
if (i < array.length - 1) {
System.out.print(", ");
}
}
System.out.println("}");
}
public static <T> T[] splitTop(T[] array, int index) {
Object[] result = new Object[array.length - index - 1];
System.arraycopy(array, index + 1, result, 0, result.length);
return (T[]) result;
}
public static <T> T[] splitBottom(T[] array, int index) {
Object[] result = new Object[index];
System.arraycopy(array, 0, result, 0, index);
return (T[]) result;
}
public static void main(String[] args) {
Integer[] integerArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
print(integerArray);
print(splitBottom(integerArray, 3));
print(splitTop(integerArray, 3));
String[] stringArray = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"};
print(stringArray);
print(splitBottom(stringArray, 3));
print(splitTop(stringArray, 3));
int[] intArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// ???
}
}
你不能这样做泛型 - 这会导致不兼容的类型错误。 – hbw 2009-04-25 07:27:52