12-7~8 Iterator, HashMap과 지네릭스

oyeon·2020년 12월 28일
0

Java 개념

목록 보기
40/70

Iterator<'E'>

  • 클래스를 작성할 때, Object 타입 대신 T와 같은 타입 변수를 사용
public class practice {
	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, 1));

//		Iterator it = list.iterator(); 		// 지네릭스 사용 X
		Iterator<Student> it = list.iterator(); // 지네릭스 사용 O

		while(it.hasNext()) {
			// 지네릭스 사용 X
//			Student s = (Student)it.next();	// 형변환 필요
//			System.out.println(s.name);
// 			위와 같이 두 줄로 표현한 것을 아래와 같이 표현도 가능			
//			System.out.println(((Student)it.next()).name);	// 보기 안 좋음
			
			// 지네릭스 사용 O
			System.out.println(it.next().name);	// 깔끔
		}
	}
}

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

HashMap<K,V>

  • 여러 개의 타입 변수가 필요한 경우, 콤마(,)를 구분자로 선언
public class practice {
	public static void main(String[] args){
		HashMap<String, Student> map = new HashMap<>();	// JDK1.7부터 생성자에 타입지정 생략가능
		map.put("김철수", new Student("김철수", 1, 1, 100, 100, 100));
		
		// public V get(Object key) -> public Student get(Object key)
		Student s = map.get("김철수");		// 지네릭스 O. 형변환 불필요		
//		Student s = (Student)map.get("김철수");  // 지네릭스 X
	}
}

class Student {
	String name = "";
	int ban;
	int no;
	int kor, eng, math;
	
	Student(String name, int ban, int no, int kor, int eng, int math){
		this.name = name;
		this.ban = ban;
		this.no = no;
		this.kor = kor;
		this.eng = eng;
		this.math = math;
	}
}
profile
Enjoy to study

0개의 댓글