【发布时间】:2009-04-25 07:13:38
【问题描述】:
我正在玩一些代码 katas 并试图同时更好地理解 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};
// ???
}
}
【问题讨论】: