2017-03-29 23 views
0

与えられた型のオブジェクトの配列をとり、最小の配列アイテムと最大の配列を含むペアオブジェクトを返すようにソートします。項目。Javaの汎用メソッド: "オブジェクトはパラメータを受け取りません"

  • Object型のパラメータを取りません:public <FirstType> Pair sortMinMax(Object<FirstType>[] array)
  • Object型のパラメータを取りません。Object<FirstType> minimum = array[0]
  • Object型のパラメータを取りません。Object<FirstType> maximum = array[0]
  • 私は3つのコンパイルエラーを取得する瞬間

ここは私のクラスです

public class MinMaxArray { 

    // takes an array of a given object and returns a pair 
    // of the min and max array elements 
    public <FirstType> Pair sortMinMax(Object<FirstType>[] array) { 
    Object<FirstType> minimum = array[0]; 
    Object<FirstType> maximum = array[0]; 

    // loop through all array items and perform sort 
    for (int counter = 1; counter < array.length; counter++) { 
     // if this element is less than current min, set as min 
     // else if this element is greater than current max, set as max 
     if (array[counter].compareTo(minimum) < 0) { 
     minimum = array[counter]; 
     } else if (array[counter].comparTo(maximum) > 0) { 
     maximum = array[counter]; 
     } // end if else new min, max 
    } // end for (all array items) 

    return new Pair<FirstType, FirstType>(minimum, maximum); 
    } // end compare() 

} // end MinMaxArray 
+1

'java.lang.Object'がジェネリックではありません –

答えて

1
type Object does not take parameters 

これが最もよくわかります。単に、Object<T>のようなものを書くことができます。クラスObjectはパラメータ化されていません。たとえば、Listはです。参照配列を避けるため、まず

public <FirstType extends Comparable> Pair sortMinMax(FirstType[] array) 
+1

' Comparable'と 'Pair'は一般的なものですので、引数が必要になります。アレイは物事を厄介なものにしようとしています。 –

+0

確かに真です。 –

3

はまた、compareTo()メソッドを使用するために、あなたはこのような何かを持っている必要があります。彼らはジェネリック薬でうまくいっていません。代わりにListを使用してください。

FirstTypeをタイプパラメータまたは一般的なパラメータ(通常は1文字の名前)にするつもりであるかどうかはわかりません。

FirstTypeもしあなたが一般的なパラメータを意味する場合は、java.util.Collections.sortを見てタイプ

public static Pair<FirstType,FirstType> sortMinMax(List<FirstType> things) { 

です。

public static <T extends Comparable<? super T>> void sort(List<T> list) { 

ので

public static <T extends Comparable<? super T>> Pair<T,T> sortMinMax(List<T> list) { 
関連する問題