CH12-7,8 Iterator, HashMap과 지네릭스

[자바의 정석 - 기초편] ch12-7,8 Iterator, HashMap과 지네릭스

오늘은 지네릭 클래스들의 예를 몇개 살펴보자.

  1. Iterator<E>

Iterator도 예전엔 일반 클래스였다. 지금은 지네릭 클래스로 바뀜

Untitled

예제를 보자.

import java.util.ArrayList;
import java.util.Iterator;

public class EX12_2 {

	public static void main(String[] args) {
		ArrayList<Student> list = new ArrayList<Student>();
		list.add(new Student("조현진", 1, 1));
		list.add(new Student("이종인", 1, 2));
		list.add(new Student("문병국", 2, 2));
		
		Iterator<Student> it = list.iterator();
		while(it.hasNext()) {
			System.out.println(it.next()); //지네릭스 덕분에 형변환 없이 바로 출력 가능
		}		
	}
}

class Student {
	String name = "";
	int ban;
	int no;
	
	Student(String name, int ban, int no) {
		this.name = name;
		this.ban = ban;
	}
	
	public String toString() {
		return "이름 :" + this.name + " 반 : " + this.ban + 
				" 번호 : "+this.no;
	}
}

iterator가 형변환 없이 Student타입을 출력하는걸 확인할 수 있다.

HashMap같은경우에는 key와 value 두가지 타입변수를 받는 지네릭 클래스이다.

key와 value라는 의미를 보존하기 위해 타입변수가 <K, V>로 선언되어 있다.

이역시 지네릭스로 선언되어있기 때문에 출력시 형변환이 필요없다.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

public class EX12_2 {

	public static void main(String[] args) {
		HashMap<String, Student> map = new HashMap<>(); //JDE1.7부터 생략 가능
		map.put("조현진", new Student("조현진",1,1,100,100,100));
		
		Student s = map.get("조현진");
		System.out.println(s);
		
		}		
	}
class Student {
	String name = "";
	int ban;
	int no;
	int kor;
	int eng;
	int math;
	
	Student(String name, int ban, int no, int kor, int eng, int math) {
		this.name = name;
		this.ban = ban;
		this.kor = kor;
		this.eng = eng;
		this.math = math;
	}
	
	public String toString() {
		return  "이름 : "+this.name+"\\n반 : " + this.ban + 
				"\\n번호 : "+this.no+"\\n국어점수 : "+this.kor+" 영어점수 : "+this.eng+
				" 수학점수 : "+this.math+"\\n";

	}
}

추가로.. HashMap클래스 내부를 보면

Untitled

get()함수가 타입변수 K를 파라미터로 설정했을거 같은데, Object로 되어있다. 왜? 이걸 타입변수로 교체한게 제네릭 클래스 아닌가?