문제
누구든지 제네릭을 사용하여 아래 코드를 작성하고 컴파일러 경고를 피하는 방법을 알고 있습니까? (@suppresswarnings ( "확인되지 않은")는 부정 행위로 간주됩니다).
그리고 아마도 "왼쪽"유형이 "오른쪽"유형과 동일했는지에 대해 제네릭을 통해 확인할 수 있습니까?
public void assertLessOrEqual(Comparable left, Comparable right) {
if (left == null || right == null || (left.compareTo(right) > 0)) {
String msg = "["+left+"] is not less than ["+right+"]";
throw new RuntimeException("assertLessOrEqual: " + msg);
}
}
해결책
이것은 비슷한 유형의 서브 클래스와 함께 작동합니다.
public <T extends Comparable<? super T>> void assertLessOrEqual(T left, T right) {
if (left == null || right == null || left.compareTo(right) > 0) {
String msg = "["+left+"] is not less than ["+right+"]";
throw new RuntimeException("assertLessOrEqual: " + msg);
}
}
다른 팁
이건 어때:
public <T extends Comparable<T>> void assertLessOrEqual(T left, T right) {
if (left == null || right == null || (left.compareTo(right) > 0)) {
String msg = "["+left+"] is not less than ["+right+"]";
throw new RuntimeException("assertLessOrEqual: " + msg);
}
}
아마도 만들 수 있습니다 작은 조금 더 일반적이지만 더 복잡하게 만들어야합니다. :)
제네릭을 통해 '왼쪽'유형이 런타임에서 '오른쪽'유형과 동일했는지 확인할 수 없습니다. Java Generics는 구현됩니다 삭제를 입력하십시오, 런타임에서 일반 유형 매개 변수에 대한 정보가 손실되도록합니다.
public <T extends Comparable<T>> void assertLessOrEqual(T left, T right) {
if (left == null || right == null || (left.compareTo(right) > 0)) {
String msg = "["+left+"] is not less than ["+right+"]";
throw new RuntimeException("assertLessOrEqual: " + msg);
}
}
제휴하지 않습니다 StackOverflow