자바의 정석 - 제너릭 2

송용준·2023년 5월 9일

제너릭 용어

class Box<T> { } 		// 제너릭 클래스
Box<String> b = new Box<String> ( ) ;	// 앞 뒤 타입 맞추기

제너릭 타입과 다형성

  • 참조 변수와 생성자의 대입된 타입은 일치해야 한다.
ArrayList<Tv> list = new ArrayList<Tv> ( ) ;		// ok
ArrayList<Product> list = new ArrayList<Tv> ( ) ; 	// 오류.조상,자식관계도 불가
  • 제너릭 클래스간의 다형성은 성립(여전히 대입된 타입은 일치)
List<Tv> list = new ArrayList<Tv> ( ) ;		// ArrayList가 List를 구현
List<Tv> list = new LinkedList<Tv> ( ) ;	// LinkedList가 List를 구현
  • 매개변수의 다형성도 성립
ArrayList<Product> list = newArrayList<Product> ( ) ;
list.add(new Product());
list.add(new Tv());			// 자손도 ok, 대신 형변환 필요
list.add(new Audio());		// 자손도 ok, 대신 형변환 필요

Iterator

  • 클래스를 작성할 때, Object타입 대신 T와 같은 타입 변수를 사용

HashMap

  • 여러 개의 타입 변수가 필요한 경우, 콤마(,)를 구분자로 선언
import java.util.*;

class Java {
	public static void main(String[] args) {
		HashMap<String, Student> map = new HashMap<>();
		map.put("자바왕", new Student("자바왕", 1, 1, 100,100, 100));
		
		Student s = map.get("자바왕");
		
		System.out.println(s.name);
	}
}

class Student{
	String name = "";
	int ban;		
	int no;		
	int kor;
	int eng;
	int math;
	
	public Student(String name, int ban, int no, int kor, int eng, int math) {
		super();
		this.name = name;
		this.ban = ban;
		this.no = no;
		this.kor = kor;
		this.eng = eng;
		this.math = math;
	}
}
profile
용용

0개의 댓글