2012-04-20 8 views
0

私はジェネリックメソッドを使用する私の最初のプログラムに取り組んでいます。メソッドが任意のオブジェクトの配列を受け取れるように、パラメータをselectionSort(T[] a)に設定することによって正しく行っていると思いました。一般的な方法 - 特定の種類に適用することはできません

public class SelectionSort { 
protected int[] arrayOne = {1,2,3,4,5,6,7,8}; 
protected double[] arrayTwo = {1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0}; 
public static <T extends Comparable<T>> void selectionSort(T[] a) 
{ 
for (int index =0; index < a.length; index++) 
{ 
    int minElementIndex = index; 
    T minElementValue = a[index]; 
    for (int i = index + 1; i < a.length; i++) 
    { 
     if (a[i].compareTo(minElementValue) < 0) 
     { 
      minElementIndex = i; 
      minElementValue = a[i]; 
     } 
    }//end of inner for loop 
    a[minElementIndex] = a[index]; 
    a[index] = minElementValue; 
}//end of outer for loop 
for(int indexb = 0; indexb<a.length; indexb++) 
{ 
    System.out.printf("%d ", a[indexb]); 
    if(indexb == a.length) 
     System.out.println(""); 
} 
} 
public static void main(String[] args) 
{ 
selectionSort(arrayOne); 
selectionSort(arrayTwo); 

}}//end of main and SelectionSort 

おそらく私を助けることができます。もしそうなら、私はそれを高く評価します。

答えて

4

ジェネリックスは、オブジェクトまたはクラスではないintまたはdoubleのようなプリミティブ型では使用できません。ボックス版のInteger[]Double[]を使用する必要があります。

特に、プリミティブint[]double[]配列を受け入れることをサポートする場合は、コードを2回書く必要があります。 =((私は1つの半回避策を考えることができますが、外部ライブラリを使わないではいけません)

+0

変数をint [] double []の代わりにInteger []とDouble []に​​変更しましたが、 –

+0

どのエラーがあなたに与えられているのですか?(あなたのコードを読み返して、あなたは 'arrayOne'と' arrayTwo' static ...を作る必要があると思っています) –

+0

これは静的に変更されました。 –

関連する問題