Hello

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 생략가능하다는 의미이다.

  • 메서드를 호출할 때 타입을 생략하지 않을 때는 클래스 이름 생략하지 못한다.

블로그의 정보

Hello 춘기's world

볼빵빵오춘기

활동하기