brunch

You can make anything
by writing

C.S.Lewis

by 김선우 May 01. 2016

제네릭 T의 활용

타입 파라미터

1. String 타입의 문자열을 랜덤으로 출력하기 위한 클래스

public class RandomList<T> {

    private ArrayList<String> storage = new ArrayList<String>();
    private Random random = new Random(47);
    public void add(String item) {
        storage.add(item);
    }

    public String select() {
        return storage.get(random.nextInt(storage.size()));
    }

    public static void main(String[] args) {
        RandomList<String> randomList = new RandomList<String>();
        for(String str : ("The quick brown fox jumped over "+ "the lazy brown dog").split(" "))
            randomList.add(str);
        for (int i=0 ; i<11; i++)
            System.out.println(randomList.select() + " ");
    }
}


2. 제네릭 T를 이용하면 타입에 상관없이 유연하게 대처 가능

public class RandomList<T> {

    private ArrayList<T> storage = new ArrayList<T>();
    private Random random = new Random(47);
    public void add(T item) {
        storage.add(item);
    }

    public T select() {
        return storage.get(random.nextInt(storage.size()));
    }

    public static void main(String[] args) {
        RandomList<String> randomList = new RandomList<String>();
        for(String str : ("The quick brown fox jumped over "+ "the lazy brown dog").split(" "))
            randomList.add(str);
        for (int i=0 ; i<11; i++)
            System.out.println(randomList.select() + " ");
    }
}


제네릭의 본래 취지는 클래스나 메서드를 작성할 때 타입의 제약을 완화함으로써 개발자에게 최대한의 표현을 허용하는 것이다. 때로는 인터페이스 조차 제한적으로 느낄때가 있다. 특정 인터페이스나 클래스가 아닌 '미지정 타입'과 동작할 수 있다면 더욱 일반화된 코드를 작성할 수 있고, 때문에 제네릭 파라미터화 타입 구현이 등장하였다.


T(type)나 E(element) 타입 인자의 경우 특정 타입으로 지정한 경우보다 직관성은 떨어지지만, 

확장성을 고려한다면 사용하는 것이 좋다.


* Thinking in java 를 참고하였습니다.


작가의 이전글 Spring Camp 2016

작품 선택

키워드 선택 0 / 3 0

댓글여부

afliean
브런치는 최신 브라우저에 최적화 되어있습니다. IE chrome safari