質問

<T extends Comparable<? super T>>メソッドのように、テンプレートタイプCollections.sort()を持つメソッドパラメータTと一致するように、不満の方に並べ替えるかどうかは不思議です。

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

どこかに比較例のリストへの参照を持っているとし、このようなキャスティングによってその方法を呼び出したいとします。

List<E> foo = new List<E>(a);
Collections.sort( /* magic cast */ foo);
.

(List<? extends Comparable>)にキャストした場合、これを行うことができますが、これによりRAW-Typeを使用している(この場合はテンプレートタイプなしで比較可能)という警告が発生します。 RAW型の使用を避けたい、あるいは@SuppressWarnings("rawtypes")(例えば、後方互換性を維持し、生の種類の回避)を介してそれらを抑制したいとしましょう。

は、(List<? extends Comparable</*something*/>>)にキャスティングすることで生の種類を使用することを回避することができ、それが「何か」であるのでしょうか。

edit :この例は、ポイントを説明するためだけです。実際には並べ替えもしません。 Collections.sort()メソッドと同様です。

役に立ちましたか?

解決

Cast it to

Collections.sort((List<Comparable<Object>>) list);

This will not give "rawtype" warnings. Just one "unchecked cast" warning (which you will get anyway.)

Judging from what you mentioned in the EDIT, ultimately you want to do something like this?

if(!list.isEmpty() && list.get(0) instanceof Comparable){
    List<Comparable<Object>> cmprList = (List<Comparable<Object>>)list;
    Collections.sort(cmprList);
}

他のヒント

This is certainly not possible. Collections.sort requires the Comparable in order to call the compareTo() method. So in your oppinion, what should happen when sort get's a collection of non-comparable objects?

It might be that you want to use something like a default ordering, based on the references for example. But such a thing does not exist implicitly. Though, it can be implemented. But I doubt that this is what you want? So why do you want to sort the list in the first place? And how should these elements be sorted?

This will compile in Eclipse:

List<?> foo = new ArrayList<Object>();
Collections.sort((List<Comparable>) foo);

You will get a "Type Safety: Unchecked" warning that you can suppress with this:

@SuppressWarnings("unchecked")

That will let you call sort. Is that what you're looking for? No guarantees it will be safe at run time, of course.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top