1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// Class의 Object를 정의되지 않은 일반 자료형으로 받음
public class Generic<T> {
    private T t;
    
    public T get() {
        return this.t;
    }
    
    public void set(T o) {
        this.t = o;
    }
    
    public static void main(String[] args) {
        
        // T가 String으로 치환됨
        Generic<String> test1 = new Generic<String>();
        test1.set("AlYAC");
        
        // T가 Integer로 치환됨
        Generic<Integer> test2 = new Generic<Integer>();
        test2.set(3);
    }
}
 
// E - Element, K - Key (in map), V - Value (in map)
// N - Number, T- Type
cs

Java Generic 실습1
: class명에 <T>의 추가를 통해 generic 하게 자료형을 받겠다는 것을 명시한다. main method에서 보이는 것과 같이 내가 원하는 자료형에 따라 유동적으로 다른 자료형을 가지는 객체를 생성할 수 있게 된다. 즉, <String>으로 넣게 되면 String 자료형의 객체를 만들게 되며, <Integer>는 Integer 자료형의 객체를 만들어 주게 된다. 
Generic 부에 들어가는 기호로는 관습적으로 하단의 주석과 같은 것들이 사용된다. 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Generic2 {
 
    public static <E> void testArray(E[] array) {
        for(E e : array) {
            System.out.println(e);
        }
    }
    
    public static void main(String[] args) {
        Integer[] arr = {1,2,3,4,5};
        testArray(arr);
        
        String[] arr2 = {"Java""C""C++""JSP"};
        testArray(arr2);
    }    
}
cs

Java Generic 실습2
: 배열을 받아 출력하는 testArray method에 각각 Integer와 String으로 구성된 배열을 넘긴다. 넘겨준 배열의 자료형은 다르지만, 이상 없이 method의 출력 기능을 수행함을 알 수 있다.
cf. method에 인자를 넘겨줄 때는 항상 'Integer', 'Character'와 같은 Wrapper 클래스로 전달해주어야 한다.


+ Recent posts