Hello

Java Iterator, HashMap과 지네릭스

by 볼빵빵오춘기

Iterator <E>

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

 

예제 코드

import java.util.*;
import static java.util.Collections.*;

public class Try {
	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<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) {
		this.name = name;
		this.ban = ban;
		this.no = no;
	}
}

 

HashMap(K,V)

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

예제 코드

import java.util.*;
import static java.util.Collections.*;

public class Try {
	public static void main(String[] args) {
		HashMap<String, Student> map = new HashMap<String, Student>();
		// HashMap<String, Student> map = new HashMap<>(); // 위와 코드와 동일하다   
		// JDK1.7부터 생성자에 타입지정 생략가능 
		map.put("자바왕",new Student("자바왕",1,1,100,100,100));
		
		Student s = map.get("자바왕");
		
		
		System.out.println(map);
		System.out.println(s);
		System.out.println(s.ban);
		System.out.println(s.no);
		System.out.println(s.kor);
		System.out.println(s.eng);
		System.out.println(s.math);
	}
}

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.no = no;
		this.kor = kor;
		this.eng = eng;
		this.math = math;
	}
}

블로그의 정보

Hello 춘기's world

볼빵빵오춘기

활동하기