제네릭(Generic) 메소드
매개변수타입과 리턴타입 으로 타입파라미터를 갖는 메소드를 말한다.
제네릭 메소드 선언방법
제네릭 메소드를 호출하는 두가지 방법
public class GenericMethod {
static class Box<T> { //box 클래스
private T t;
public T getT() { return t; }
public void setT(T t) { this.t = t; }
}
static class Util { // 박스를 이용해 제네릭 메소드가 있는 Util클래스
public static <T> Box<T> boxing(T t) {
Box<T> box = new Box<T>();
box.setT(t);
return box;
}
}
public static void main(String[] args) {
//1번 구체적 타입 명시 <Integer>boxing(100) 구체적타입 Integer 명시
Box<Integer> box1 = Util.<Integer>boxing(100);
int intValue = box1.getT();
System.out.println(intValue);
//2번 매개값을 보고 구체적 타입 추정. 홍길동 = String 타입
Box<String> box2 = Util.boxing("홍길동");
String strValue = box2.getT();
System.out.println("strValue = " + strValue);
}
}
exam2
public class Pair<K, V> {
private K key;
private V value;
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
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 class Util {
//두개의 Pair객체를 받아서 페어 객체의 K,V값을 비교 K와 V가 같다면 true or false
public static <K,V> boolean compare(Pair<K,V> p1, Pair<K,V> p2) {
boolean keyCompare = p1.getKey().equals(p2.getKey());
boolean valueCompare = p1.getValue().equals(p2.getValue());
// keyCompare 그리고 valueCompare 가 같으면 true
return keyCompare && valueCompare;
}
}
public class CompareMethodExample {
public static void main(String[] args) {
//두개의 Pair객체 생성
Pair<Integer, String> p1 = new Pair<>(1, "사과");
Pair<Integer, String> p2 = new Pair<>(1, "사과");
// 구체적 타입 명시.. 두개의 페어 객체를 비교
Util.<Integer,String>compare(p1, p2);
//매개값을 보고 구체적 타입 추정, new Pair<>(1, "사과") 1 =Integer 타입 , "사과" = String 타입
boolean result1 = Util.compare(p1, p2);
if (result1) {
System.out.println("논리적으로 동등합니다.");
} else {
System.out.println("논리적으로 동등하지 않습니다.");
}
}
}
'JAVA > JAVA' 카테고리의 다른 글
제네릭(Generic) 타입의 상속과 구현 (0) | 2018.06.09 |
---|---|
제네릭(Generic) 와일드카드 타입 (0) | 2018.06.09 |
제네릭(Generic)이란 ? 제네릭 타입이란? (0) | 2018.06.08 |
Thread 정리..?? (0) | 2018.06.08 |
자바 기본 변수 (0) | 2018.05.08 |