JAVA
제네릭 인터페이스 예시
Droomii
2020. 1. 6. 11:29
Comparable 인터페이스는 어떤 클래스 객체를 정렬할 때 구현하는 인퍼페이스이다.
코드는 다음과 같다.
public interface Comparable<T> {
int compareTo(T o);
}
여기서 T는 타입 파라미터를 의미하며, 공란으로 남겨두면 기본값인 Object 타입이 들어가게 된다.
공란으로 남겨둘 시 다음과 같이 특정 타입으로 캐스팅을 해주어야 한다.
public class NoTypeParameter implements Comparable{
private int value;
public NoTypeParameter(int pValue) {
this.value = pValue;
}
@Override
public int compareTo(Object arg0) { // 기본값인 Object를 받음
NoTypeParameter other = (NoTypeParameter)arg0; // NoTypeParameter로 형변환을 해주어야 함
return this.value - other.value;
}
}
이와 같이 제네릭 타입을 설정하지 않으면 생기는 문제점 두 가지가 있다.
1. compareTo의 파라미터가 Object, 즉 모든 객체를 받기 때문에 부적합한 객체가 들어갈 수 있다.
2. 형변환을 하는 라인이 추가로 필요하기 때문에 성능면에 있어서 비효율적이다.
제네릭 타입을 설정해주면, 위 두 문제를 해결할 수 있다.
public class TypeParameter implements Comparable<TypeParameter>{
private int value;
public TypeParameter(int pValue) {
this.value = pValue;
}
@Override
public int compareTo(TypeParameter arg0) { // 설정한 TypeParameter를 받음
// 형변환을 할 필요가 없어짐
// TypeParameter other = (TypeParameter)arg0;
return this.value - arg0.value;
}
}