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라서 원래라면 형변환을 해야하지만 지네릭스 덕에 형 변환이 필요가 없음
제한된 지네릭 클래스
class FruitBox<T extends Fruit> {
ArrayList<T> list = new ArrayList<T>();
...
}
FruitBox<Apple> appleBox = new FruitBox<Apple>();
FruitBox<Toy> toyBox = new FruitBox<Toy>();
interface Etable {}
class FruitBox<T extends Eatable> { ... }
지네릭스의 제약
- 타입 변수에 대입은 인스턴스 별로 다르게 가능
Box<Apple> appleBox = new Box<Apple>();
Box<Grape> grapeBox = new Box<Grame>();
class Box<T> {
static T item;
static int compare(T t1, T t2) { ... }
...
}
- 배열 생성할 때 타입 변수 사용불가 (타입 변수로 배열 선언은 가능)
class Box<T> {
T[] itemArr;
...
T[] toArray() {
T[] tmpArr = new T[itemArr.length];
...
}
}