【发布时间】:2014-05-24 09:10:35
【问题描述】:
我对 Java 很陌生,我已经阅读了一些关于类型转换的一般信息,这可能是我的问题的解决方案。 而且我认为我确实掌握了这个概念 - 就像一个人想要使用的一种方法是为不同的班级制作的。但是我无法将它应用到我自己的带有泛型数组的代码中,因为我不知道在哪个点进行转换以及使用哪种方法,或者我是否必须创建一个循环来发送整个数组?
这是我的归并排序算法,如果不是泛型类型,它应该可以正常工作......
package src;
import java.util.Arrays;
public class MergeSort {
// sort array of type T using the Mergesort algorithm
public static <T extends Comparable<T>> T[] sort(T[] arr) {
@SuppressWarnings("unchecked")
T[] leftArray = (T[]) new Comparable[12]; // ERROR: Type safety: Unchecked cast from
// Object[] to T[]
@SuppressWarnings("unchecked")
T[] rightArray =(T[]) new Comparable[12]; // ERROR: Type safety: Unchecked cast from
// Object[] to T[]
if (arr.length > 1) {
int half = arr.length / 2;
leftArray = Arrays.copyOfRange(arr, 0, half);
rightArray = Arrays.copyOfRange(arr, half + 1, arr.length);
}
return merge( sort(leftArray), sort(rightArray));
}
private static <T extends Comparable<T>> T[] merge(T[] leftArray, T[] rightArray) {
@SuppressWarnings("unchecked")
T[] tempArray = (T[]) new Comparable[12]; // ERROR: Type safety: Unchecked cast from
// Object[] to T[]
int i = 0;
int leftIndex = 0;
int rightIndex = 0;
while ( leftIndex < leftArray.length || rightIndex < rightArray.length ) {
if ( leftIndex < leftArray.length && rightIndex < rightArray.length ) {
if (leftArray[leftIndex].compareTo(rightArray[rightIndex]) < 0 ) {
tempArray[i] = leftArray[leftIndex] ;
leftIndex++;
}
else {
tempArray[i] = rightArray[rightIndex] ;
rightIndex++;
}
}
else if ( leftIndex < leftArray.length ) {
tempArray[i] = leftArray[leftIndex] ;
leftIndex++;
}
else if ( rightIndex < rightArray.length ) {
tempArray[i] = rightArray[rightIndex] ;
rightIndex++;
}
} // end while
return tempArray;
}
public static void main(String[] args) {
// Edit this line to check with different values for the array
// or add more unit tests to test/MergeSortTest.java
// // sort list of Characters
Character[] charArr = { 'H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r',
'l', 'd', '!' };
charArr = MergeSort.<Character> sort(charArr);
System.out.println(Arrays.toString(charArr));
// sort list of Integers
Integer[] intArr = { 23, 4, 15, 8, 42, 16 };
intArr = MergeSort.<Integer> sort(intArr);
System.out.println(Arrays.toString(intArr));
}
}
非常感谢任何建议!
【问题讨论】:
标签: java arrays generics casting