본문 바로가기
자바

제네릭

by 멋진 개구리 2021. 4. 7.
반응형

제네릭

  1. 의미
  • 일반화된 클래스나 메소드

  • 자료형 검사가능

  • 제네릭은 다양한 타입의 객체들을 다루는 메서드나 컬렉션 클래스에 컴파일 시의 타입체크를 해주는 기능이다. – 자바의 정석

  • 제네릭 예제

  1. 사용하지 않을때

    ArrayList list = new ArrayList(); //제네릭을 사용하지 않을경우
    list.add("test");
    String temp = (String) list.get(0); //타입변환이 필요함
    ArrayList list2 = new ArrayList(); //제네릭을 사용할 경우  
    list2.add("test");  
    temp = list2.get(0); //타입변환이 필요없음
    

위는 제네릭을 사용하지 않았을때이다. 안쓸때는 형변환이 필요하다,

  1. 사용할때
    public class TestGeneric  
    {  
    public T sample;
    public void showYourType()
    {
     if(sample instanceof Integer)
         System.out.println("Integer 타입이군요!!");
        else if(sample instanceof String)
         System.out.println("String 타입이군요!!");
    }
    }
    

public class Main{
public static void main(String[] args)
{
TestGeneric stringType = new TestGeneric();
TestGeneric integerType = new TestGeneric();

stringType.sample = "Hello";
integerType.sample = 1;

stringType.showYourType();
integerType.showYourType();

}

}

- 위와같이 사용할수있다.
반응형

댓글