Iterator & HashMap과 지네릭스(Generics), 지네릭스의 제한과 제약

이의준·2024년 6월 11일

Java

목록 보기
70/87

Iterator<E>

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

public class imsi3 {
    public static void main(String[] args) {
        ArrayList<Student> list = new ArrayList<Student>();
        list.add(new Student("김김김", 1, 1));
        list.add(new Student("이이이", 1, 1));
        list.add(new Student("박박박", 1, 1));

        Iterator<Student> it = list.iterator();
        while (it.hasNext()) {
            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;
    }
}
  • 지네릭스를 사용함으로 인해 name 출력시 Student로 형변환을 하지 않아도 됨

HashMap<K,V>

  • 여러 개의 타입 변수가 필요한 경우, 콤마()를 구분자로 선언
public class imsi4 {
    public static void main(String[] args) {
        HashMap<String, Student21> map = new HashMap<>();
        map.put("자바왕", new Student21("자바왕", 1, 1, 100, 100, 100));

        Student21 s = map.get("자바왕");
        
        System.out.println(map);
    }
}

class Student21 {
    String name = "";
    int ban;
    int no;
    int kor;
    int eng;
    int math;

    Student21(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;
    }
  • 생성자에 지정하는 타입은 위와 같이 생략 가능 (new HashMap<>)
  • get이 반환하는게 Object라서 원래라면 형변환을 해야하지만 지네릭스 덕에 형 변환이 필요가 없음


제한된 지네릭 클래스

  • extends로 대입할 수 있는 타입을 제한
class FruitBox<T extends Fruit> { // Fruit의 자손만 타입으로 지정 가능
	ArrayList<T> list = new ArrayList<T>();
    ...
}
FruitBox<Apple> appleBox = new FruitBox<Apple>(); // OK
FruitBox<Toy> toyBox = new FruitBox<Toy>(); // 에러. Toy는 Fruit의 자손이 아님
  • 인터페이스인 경우에도 extends를 사용
interface Etable {}
class FruitBox<T extends Eatable> { ... }

지네릭스의 제약

  • 타입 변수에 대입은 인스턴스 별로 다르게 가능
Box<Apple> appleBox = new Box<Apple>(); // Apple 객체만 저장 가능
Box<Grape> grapeBox = new Box<Grame>(); // Grape 객체만 저장 가능
  • static 멤버 타입 변수 사용 불가
class Box<T> {
	static T item; // 에러
    static int compare(T t1, T t2) { ... } // 에러
    ...
}
  • 배열 생성할 때 타입 변수 사용불가 (타입 변수로 배열 선언은 가능)
class Box<T> {
	T[] itemArr; // OK. T타입의 배열을 위한 참조변수
    ...
    T[] toArray() {
    	T[] tmpArr = new T[itemArr.length]; // 에러. 지네릭 배열 생성불가
        ...
    }
}


0개의 댓글