class Pair<K, V>{
private K key;
private V value;
//생성자 선언
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
//getter & setter
public K getKey() {
return key;
}
public void setKey(K key) {
this.key = key;
}
public V getValue() {
return value;
}
public void setValue(V value) {
this.value = value;
}
//키와 값을 모두 출력
public <K,V> void displayKeyValue(K key, V value) {
System.out.println(key.toString() + " : " + value.toString());
}
}
Utill 클래스 생성
//리턴타입 앞에 제너릭 선언
public static<K, V> boolean compare(Pair<K,V> p1, Pair<K,V> p2) {
//p1 Key , p2 key 비교해서 같으면 true 틀리면 false 출력
boolean keyCompare = p1.getKey().equals(p2.getKey());
//p1 Key , p2 key 비교해서 같으면 true 틀리면 false 출력
boolean valueCompare = p1.getValue().equals(p2.getValue());
//둘 다 true 이면 return true
//둘 중 하나 flase 이라면 return false
return keyCompare && valueCompare;
}
}
Main
public class T03GenericMethodTest {
public static void main(String[] args) {
//객체선언
//클래스명 <타입 선언> 변수명 = new Piar<타입선언>(,);
Pair<Integer,String> p1 = new Pair<Integer,String>(1, "홍길동");
Pair<Integer,String> p2 = new Pair<Integer,String>(1, "홍길동");
boolean result = Utill.<Integer,String>compare(p1, p2); //true
if(result){
System.out.println("두 객체는 논리적으로 동일한 객체임");
}else {
System.out.println("두 객체는 논리적으로 동일한 객체가 아님");
}
System.out.println("--------------------------------------------------------");
Pair<String, String> p3 = new Pair<String, String>("001", "홍길동");
Pair<String, String> p4 = new Pair<String, String>("002", "홍길동");
result = Utill.<String, String>compare(p3, p4);
if(result){
System.out.println("두 객체는 논리적으로 동일한 객체임");
}else {
System.out.println("두 객체는 논리적으로 동일한 객체가 아님");
}
//에러가 남 : p1.객체 선언할때 new Pair<Integer,String>했기 때문에
// displayKeyValue 파라미터에 KEY 올 수 있는것은 integer
// p1.displayKeyValue("키", 180);
p1.displayKeyValue(100, "키");
//key파라미터를 String으로 만드는 방법 : 리턴타입 앞에 제너릭만들어주면된다.
// p1.<String,Integer>displayKeyValue("키", 180);
// 제너릭 생략해도됨 : 이미 제너릭 선언해줘서 가능
//displayKeyValue(K key, V value) 메소드에서 리턴타입 앞에 <K, V> 선언해줌
p1.displayKeyValue("키", 180);
}
}