나는 katas 코드를 가지고 놀고 있으며 동시에 java generics에 대해 더 잘 이해하려고 노력 중이다. 나는이 배열을 출력하는 작은 메서드를 가지고 있는데, 배열을 출력하고 싶습니다. 배열을 받아들이고 인덱스 위 또는 아래에있는 'things'의 배열을 반환하는 몇 가지 도우미 메서드가 있습니다 (이진 검색 알고리즘입니다.)int 배열을 java의 제네릭 메소드에 전달할 수 있습니까?
두 질문에,
# 1 난 splitBottom 및 splitTop에서 T로 번지는 현상을 방지 할 수 있습니까? 그것은 기분이 좋지 않거나 잘못된 길로 가고 있습니다. (파이썬이나 무언가를 사용하라고 말하지 마십시오.))
# 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
@htw 자세히 설명해 주시겠습니까? – blank