Generic이란?

  • 제네릭의 직역은 '일반적인'이라는 뜻이다.
  • 데이터 형식에 의존하지 않고, 하나의 값이 여러 다른 데이터 타입들을 가질 수 있도록 하는 방법 이라고 정의
  • 클래스 내부에서 지정하는 것이 아닌 외부에서 사용자에 의해 지정되는 것을 말하며, 특정 타입을 미리 지정해주는 것이 아닌 필요에 의해 지정할 수 있도록 하는 타입이라는 것이다.

Generic(제네릭)의 장점

  • 제네릭을 사용하면 잘못된 타입이 들어올 수 있는 것을 컴파일 단계에서 방지할 수 있다.
  • 클래스 외부에서 타입을 지정해주기 때문에 따로 타입을 체크하고 변환해줄 필요가 없다. 즉, 관리하기가 편하다.
  • 비슷한 기능을 지원하는 경우 코드의 재사용성이 높아진다.

Generic(제네릭)의 종류

<T>	- Type 
<E>	- Element 
<K>	- Key
<V>	- Value
<N>	- Number

타입 파라미터는 제네릭 클래스/인터페이스에 사용되며 "타입이 정해지지 않은" 파라미터를 의미하는데 대부분 참조 타입의 경우 T, 요소의 경우 E(Element) , 키를 나타낼 경우 K(Key), 값을 나타낼 경우 V(Value) 등을 사용한다.


예제1

기본 제네릭

<> 안에 타입을 지정하게 되는데 이때 들어가는 타입이 멤버변수 sample의 타입으로 결정

public class ExGeneric<T> 
{
    public T sample;

    public void showType()
    {
        if(sample instanceof Integer)
            System.out.println("type::: Integer");
       	else if(sample instanceof String)
            System.out.println("type::: String");
    }
}
public class Main{
    public static void main(String[] args)
    {
        ExGeneric<String> stringType = new ExGeneric<String>();
        ExGeneric<Integer> integerType = new ExGeneric<Integer>();

		stringType.sample = "daeho";
		integerType.sample = 29;

        stringType.showType();
        integerType.showType();
    }
} 

예제2

복수 제네릭

제네릭의 구분은 쉼표(,)를 통해 하며 <T, K>와 같은 형식으로 사용하며 어떠한 문자도 사용 가능

public class ExGeneric<T, K>
{
    public T sample;
    public K sapmle2;
}
public class Main{
    public static void main(String[] args)
    {
       ExGeneric<String, Integer> generic = new ExGeneric<String, Integer>();
       ExGeneric<String, Object> generic = new ExGeneric<String, Object>();
    }
}

예제3

제네릭 생략표현

public class ExGenericSkip<T> {
    public T data;

    public ExGenericSkip(T data)
    {
        this.data = data;
    }
}
public class Main{
    public static void main(String[] args)
    {
        ExGenericSkip skip1 = new ExGenericSkip("test1");
        ExGenericSkip<String> data2 = new ExGenericSkip("test2");
    }
}

0개의 댓글

Powered by GraphCDN, the GraphQL CDN