공부기록/Java

제네릭(1)

jhs0129 2021. 8. 7. 18:49
320x100
반응형

제네릭을 사용하는 이유

  • 잘못된 타입이 사용될 수 있는 문제를 컴파일 과정에서 제거할 수 있음
  • 타입변환을 제거할 수 있음
List list = new ArrayList();
list.add("hello");
Strign str = (String) list.get(0);

//List에 저장되는 요소를 String타입으로 변환하지 않아도 된다.
List<String> list = new ArrayList<String>();
list.add("hello");
String str = list.get(0);
  • 하나의 메소드로 여러 타입을 다룰 수 있음
public class Box<T>{
	private T t;
    public T get() { return t; }
    public void set(T t) { this.t = t; }
}​

<T> 에서 T에 wrapper class로 변경해서 작성

기본형 wrapper class
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
  • 파라미터를 두 개 이상 사용할수 있음, 객체로도 사용 가능

제네릭 메소드

리턴타입 앞에 <>기호를 추가하고 안에 타입 파라미터를 기술 매개변수의 타입을 타입 파라미터로 사용

  • [접근 제어자] <제네릭타입, ...> [반환타입] 메소드명 ([제네릭타입] 파라미터, ...)

ex)

제네릭 타입

public class Pair<K, V>{
	private K key;
    private V value;
    
    public Pair(K key, V value){
    	this.key = key;
        this.value = value;
    }
    
    public void setKey(K key) { this.key = key;}
    public void setValue(V value) { this.value = value;}
    public K getKey() { return key;}
    public V getValue() { return value;}
}

제네릭 메소드

public class Util{
	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());
        return keyCompare && valueCompare;
}

호출

public class ex{
	public static void main(String[] args){
    	Pair<Integer, String>p1 = new Pair<Integer, String>(1,"사과");
        Pair<Integer, String>p2 = new Pair<Integer, String>(1,"사과");
        boolean result = Util.<Integer, String>compare(p1, p2);
        
        if(result)
        	System.out.println("true");
        else
        	System.out.println("false");
}
320x100
반응형