본문 바로가기

하../java

ch 12 Iterator<E>

ch 12 Iterator<E>

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

 

	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);
			System.out.println(it.next().name); //위 두줄을 한줄로 가능
		}
	} // main
}

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 static void main(String[] args) {
		HashMap<String, Student> map = new HashMap<String, Student>();
		//jdk1.7부터 생성자에 타입지정(String, Student) 생략가능
		map.put("자바왕", new Student("자바왕",1,1,100,100,100));
		System.out.println(map);
	} // main
}

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;
	}
}
출력값
{자바왕=Student@515f550a}

'하.. > java' 카테고리의 다른 글

ch12 와일드카드 <?> 제네릭메서드  (0) 2021.12.24
ch12 제한된 제네릭 클래스  (0) 2021.12.24
ch12 제네릭스 용어  (0) 2021.12.24
ch12 타입 변수  (0) 2021.12.24
ch12 제네릭스란?  (0) 2021.12.24