Java 와일드카드, 지네릭메서드
by 볼빵빵오춘기와일드 카드 <?>
- 하나의 참조 변수로 대입된 타입이 다른 객체를 참조 가능하다.
더보기




⇒ 대부분 <? extends T>를 많이 쓴다.
⇒ <? extends Product> = Product와 그 자손들 = Product, Tv, Audio
- 메서드의 매개변수에 와일드 카드를 사용
더보기



위와같이 되면 올 수 있는것은 Fruit, Apple 둘 다 들어올 수 있으나 와일드카드를 쓰지않으면 Fruit 밖에 쓰지 못한다.

예제 코드
import java.util.*;
class Fruit2 { public String toString() { return "Fruit";}}
class Apple2 extends Fruit2 { public String toString() { return "Apple";}}
class Grape2 extends Fruit2 { public String toString() { return "Grape";}}
class Juice {
String name;
Juice(String name) { this.name = name + "Juice"; }
public String toString() { return name; }
}
class Juicer {
static Juice makeJuice(FruitBox2<? extends Fruit2> box) {
String tmp = "";
for(Fruit2 f : box.getList()) // 향상된 for문
tmp += f + " ";
return new Juice(tmp);
}
}
public class Try {
public static void main(String[] args) {
FruitBox2<Fruit2> fruitBox = new FruitBox2<Fruit2>();
FruitBox2<Apple2> appleBox = new FruitBox2<Apple2>();
fruitBox.add(new Apple2());
fruitBox.add(new Grape2());
appleBox.add(new Apple2());
appleBox.add(new Apple2());
System.out.println(Juicer.makeJuice(fruitBox));
System.out.println(Juicer.makeJuice(appleBox));
}
}
class FruitBox2<T extends Fruit2> extends Box2<T> {}
class Box2<T> {
ArrayList<T> list = new ArrayList<T>();
void add(T item) { list.add(item); }
T get(int i) { return list.get(i); }
ArrayList<T> getList() { return list; }
int size() { return list.size(); }
public String toString() { return list.toString();}
}
지네릭 메서드
- 지네릭 타입이 선언된 메서드(타입 변수는 메서드 내에서만 유효)이다.
더보기


⇒ <T> 타입변수가 선언된 것
- 클래스의 타입 매개변수 <T>와 메서드의 타입 매개변수 <T>는 별개
더보기


⇒ iv와 lv의 관계와 같다.
- 메서드를 호출할 때마다 타입을 대입해야 한다.(대부분 생략 가능)
더보기


⇒ 화살표로 가르킨 Fruit, Apple 생략가능하다는 의미이다.
- 메서드를 호출할 때 타입을 생략하지 않을 때는 클래스 이름 생략하지 못한다.
'👩🏻💻 About 프로그래밍 > Java' 카테고리의 다른 글
Java 열거형(enum) (0) | 2023.12.09 |
---|---|
Java 지네릭 타입의 형변환 (0) | 2023.12.09 |
Java 제한된 지네릭 클래스, 지네릭스의 제약 (0) | 2023.12.08 |
Java Iterator, HashMap과 지네릭스 (0) | 2023.12.08 |
Java 지네릭스 용어, 타입과 다형성 (0) | 2023.12.07 |
블로그의 정보
Hello 춘기's world
볼빵빵오춘기