문제

템플릿 유형 <T extends Comparable<? super T>>가있는 메소드 파라미터 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);
.

Collections.sort()로 캐스팅하면이 작업을 수행 할 수 있지만 이는이 경우 템플릿 유형없이 비교할 수있는 원시 유형을 사용하는 경고를 생성합니다. 원시 유형을 사용하지 않거나 (List<? extends Comparable>) (예 : 역 호환성을 유지하고 원시 유형을 피하기 위해)를 사용하지 않으려고합니다.

은 CASTING으로 원시 유형을 사용할 수 없으며 "무언가"(선택되지 않은 캐스트가 허용되지 않음)는 무엇입니까?

편집 :이 예제는 지점을 설명하는 것입니다. 실제로 나는 비교할 수 없으며 아무것도 정리하고 싶지도 않지만, instanceOf를 통해 어떤 유형 (이 예에서 비교할 수있는 것)의 어떤 유형 (비교 가능)의 어떤 유형인지를 동적으로 확인해야합니다. @SuppressWarnings("rawtypes") 메소드와 유사합니다.

도움이 되었습니까?

해결책

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