java
Generic, 제네릭
1+1은?
2013. 7. 25. 16:49
Generic, 제네릭
: 내부구조와 알고리즘을 동일하게 구현하되 취급되는 데이터의 자료형만 다른 메서드, 그러한 클래스를 구현하는 기술
: 타입변수 사용하며 자료형은 컴파일 시 결정된다.
기본적인 구성
1 2 3 4 | class Generic<T> { public T num; public T num2; } |
여기서 T란 타입변수를 의미하며(예약어 아님) 참조형만 저장할 수 있다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | //유형-1 class Gen1<Type> { public Type a; } // 유형-2 class Gen2<Type> { public Type a; public Type b; public Type c; } //유형-3 class Gen3<Type1, Type2> { public Type1 a; public Type2 b; } |
인스턴스 생성시엔 반드시 자료형을 명시해야 한다.
1 2 | Generic<Integer> intGen = new Generic<Integer>(); Generic<Object> obGen = new Generic<Object>(); |
이 후 intGen 인스턴스의 타입변수는 Integer 형 값을 처리하며
obGen은 마찬가지로 Object 형의 값만 처리할 수 있다.
타입변수는 오직 멤버 변수만 가능하며 스태틱이나 파이널 키워드는 사용할 수 없다.
(타입변수의 자료형이 객체생성 시 결정되기 때문)
1 2 3 4 5 6 | public static T num; //Cannot make a static reference to the non-static type T public final T num = 0 ; //Type mismatch: cannot convert from int to T public final static T num = 0 ; //Cannot make a static reference to the non-static type T //당연히 초기화도 불가능 |
다음은 생성자로 참조값을 전달하고 그 값을 다시 가져오는 클래스를 구현한 예제다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | class Generic<T> { public T parameter; public Generic() { //제네릭 클래스의 기본생성자 } public Generic(T parameter) { this .parameter = parameter; } public T getParameter() { return parameter; } } Generic<String> strGen = new Generic<String>( "ㅎㅇ" ); System.out.println(strGen.getParameter()); → ㅎㅇ Generic<Integer> intGen = new Generic<Integer>( 12 ); System.out.println(intGen.getParameter()); → 12 |
하지만 이런 제네릭 클래스의 경우엔 타입변수의 자료형을 알 수 없기 때문에 연산자를 사용할 수 없다.
다음은 타입변수를 연산해서 컴파일 에러가 발생하는 경우다.
1 2 3 4 | public T getData() { return parameter + parameter; //The operator + is undefined for the argument type(s) T, T } |
List, Map은 대표적인 제네릭 클래스로 List처럼 자료형을 하나만 결정하는 유형과
Map과 같이 자료형을 각각 따로 지정하는 유형도 설계가 가능하다.
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 Generic<Key, Value> { private Key key; private Value value; public void put(Key key, Value value) { this .key = key; this .value = value; } public Value get(Key key) { if (key.equals( this .key)) { return this .value; } return null ; } } Generic<String, Object> map = new Generic<String, Object>(); map.put( "한국의수도" , "서울" ); System.out.println(map.get( "한국의수도" )); → "서울" System.out.println(map.get( "서울의수도" )); → null
|