12-7. Iterator
Iterator 또한 지네릭 클래스로 타입을 정해주면, 꺼낼 때 형변환을 따로 해주지 않아도 된다.
따라서 코드가 더욱 간결해진다!
import java.util.ArrayList;
import java.util.Iterator;
public class GenericTest {
public static void main(String[] args) {
ArrayList<Student> list = new ArrayList<Student>(); // Tv 타입의 객체만 저장 가능
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 = it.next();
// System.out.println("s.name = " + s.name);
System.out.println("it.next().name = " + it.next().name);
}
}
}
class Student {
String name = "";
int classNum; // 반
int no; // 번호
public Student(String name, int classNum, int no) {
this.name = name;
this.classNum = classNum;
this.no = no;
}
}
12-8 HashMap<K,V>
- 여러 개의 타입 변수가 필요한 경우, 콤마(,)를 구분자로 선언
- K : key / V: value
import java.util.HashMap;
public class GenericTest {
public static void main(String[] args) {
HashMap<String, Student> map = new HashMap<>(); // JDK 1.7 부터 생성자에 타입지정 생략 가능
map.put("자바왕", new Student("자바왕", 1, 1, 100, 100, 100));
Student s = map.get("자바왕");
System.out.println("s.name = " + s.name);
System.out.println("s.classNum = " + s.classNum);
System.out.println(map.get("자바왕").math;
System.out.println("map = " + map);
}
}
class Student {
String name = "";
int classNum;
int no;
int kor;
int eng;
int math;
public Student(String name, int classNum, int no, int kor, int eng, int math) {
this.name = name;
this.classNum = classNum;
this.no = no;
this.kor = kor;
this.eng = eng;
this.math = math;
}
}
'👩💻 BackEnd > ☕️ 자바 [Java]' 카테고리의 다른 글
[Java] 자바의 정석 : 다형성 (1) | 2024.02.23 |
---|---|
[Java] 자바의 정석 : 접근제어자, 캡슐화 (0) | 2024.02.23 |
[자바의 정석] 12-2 ~ 12-5. 타입변수, 대입, 지네릭스 용어, 지네릭스 타입과 다형성 (0) | 2024.01.04 |
[자바의 정석] 12-1. 지네릭스란? (0) | 2024.01.04 |
[자바 스터디] day01. 지네릭스, 콜렉션 프레임워크 (0) | 2023.10.10 |