12-1~3 지네릭스(Generics)란?

oyeon·2020년 12월 27일
0

Java 개념

목록 보기
38/70
  • 컴파일시 타입을 체크해 주는 기능(compile-time type check) - JDK 1.5
  • 객체의 타입 안정성을 높이고 형변환의 번거로움을 줄여줌

예제 1

// Tv 객체만 저장할 수 있는 ArrayList를 생성
ArrayList<Tv> tvList = new ArrayList<Tv>();

tvList.add(new Tv());		// OK
tvList.add(new Audio());	// 컴파일 에러!! Tv 외에 다른 타입은 저장 불가

예제 2 - Generics 사용하지 않은 경우

ArrayList list = new ArrayList();	// JDK1.5 이전(지네릭스 도입 이전) 사용 방식
// ArrayList<Object> list = new ArrayList<Object>();	// 위와 동일. JDK1.5 이후 사용
list.add(10);	// list.add(new Integer(10));
list.add(20);
list.add("30");	// String을 추가

Integer i = (Integer)list.get(2); // 컴파일 OK -> 형변환 에러(ClassCastException) 발생
System.out.println(list);

예제 3 - Generics 사용한 경우

ArrayList<Integer> list = new ArrayList();
list.add(10);	// list.add(new Integer(10));
list.add(20);
list.add(30);	// list.add("30"); 작성 시 컴파일 에러(∵<Integer>)

Integer i = (Integer)list.get(2);
// Integer i = list.get(2); 위 결과와 동일. <Integer>선언 하였으므로 형변환 생략 가능
System.out.println(list);

지네릭스의 장점
1. 타입 안정성을 제공한다.
2. 타입체크와 형변환을 생략할 수 있으므로 코드가 간결해 진다.

예외의 상속 계층도

  • Exception : Runtime Error. 실행 중 발생하는 에러. Compile time Error 보다 좋지 않음
    (∵ Compile time Error : 프로그램 실행 전 프로그래머가 수정 가능)
  • RuntimeException : 프로그래머의 실수로 발생하는 에러
  • ClassCastException : 형변환 에러
  • 지네릭스를 통해 ClassCastException를 Compile time 에 타입 정보를 줘서 Error를 체크. Runtime Error를 Compile time Error로 처리.

타입 변수

  • 클래스를 작성할 때, Object 타입 대신 타입 변수(E)를 선언해서 사용.
  • 객체를 생성 시, 타입 변수(E) 대신 실제 타입(Tv)을 지정(대입)
profile
Enjoy to study

0개의 댓글