본문 바로가기

👩‍💻 BackEnd/☕️ 자바 [Java]

[자바의 정석] 12-7. Iterator

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;
    }
}