Java/객체지향

[객체지향][제네릭스] - Iterator, HashMap과 제네릭스

얄루몬 2022. 2. 16. 19:32

📖본 포스팅은 '자바의 정석 - 남궁성 저자' 님의 책과 유튜브 강의를 보고 작성되었습니다.

https://youtu.be/Ys6rCjVVmGo?list=PLW2UjW795-f6xWA2_MUhEVgPauhGl3xIp 


[Iterator와 제네릭스]

[형변환이 필요 없는 경우의 코드 1]

package javajungsuk;

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

public class Java12_2 {
	public static void main(String[] args) {
		ArrayList<Student> list = new ArrayList<Student>();
		list.add(new Student("자바왕",1,1));
		list.add(new Student("자바짱",1,1));
		list.add(new Student("홍길동",1,1));

		Iterator<Student> it = list.iterator();
		while (it.hasNext()) {
		//  Student s = (Student)it.next(); //제네릭스 사용하지 않았다면 형변환이 필요하다.
			Student s = it.next();
			System.out.println(s.name);
		}
		
	}
}

class Student{
	String name = "";
	int ban;
	int no;
	
	Student(String name, int ban, int no) {
		super();
		this.name = name;
		this.ban = ban;
		this.no = no;
	}
	
}

 

[형변환이 필요 없는 경우의 코드 보다 더 짧은 버전]

package javajungsuk;

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

public class Java12_2 {
	public static void main(String[] args) {
		ArrayList<Student> list = new ArrayList<Student>();
		list.add(new Student("자바왕",1,1));
		list.add(new Student("자바짱",1,1));
		list.add(new Student("홍길동",1,1));

		Iterator<Student> it = list.iterator();
		while (it.hasNext()) {
		//  Student s = (Student)it.next(); //제네릭스 사용하지 않았다면 형변환이 필요하다.
//			Student s = it.next();
//			System.out.println(s.name);
			System.out.println(it.next().name);
		}
		
	}
}

class Student{
	String name = "";
	int ban;
	int no;
	
	Student(String name, int ban, int no) {
		super();
		this.name = name;
		this.ban = ban;
		this.no = no;
	}
	
}

 

 

 

 

[HashMap과 제네릭스]

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

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

public class Java12_2_2 {
	public static void main(String[] args) {
		HashMap<String, Student2> map = new HashMap<>(); //JDK1.7 생성자 타입 지정 생략 가능
		map.put("자바왕", new Student2("자바왕",1,1,100,100,100));
		
		Student2 s2 = map.get("자바왕");
		System.out.println(map);
	}
		
}

class Student2{
	String name = "";
	int ban;
	int no;
	int kor;
	int eng; 
	int math;
	
	Student2(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;
	}
	
}