我正在玩一些代码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};
// ???
}
}
Run Code Online (Sandbox Code Playgroud)
泛型不以一致的方式处理基元.这是因为泛型不像C++中的模板,它只是单个类的编译时添加.
编译泛型时,最终会将上面示例中的Object []作为实现类型.作为int []和byte []等,不要扩展Object [],即使所涉及的代码相同(再次泛型不是模板),也不能互换使用它们
唯一的类int []和Object []共享是Object.您可以将上述方法Object作为类型编写(请参阅System.arraycopy,Array.getLength,Array.get,Array.set)
| 归档时间: |
|
| 查看次数: |
14308 次 |
| 最近记录: |