Skip to content

Instantly share code, notes, and snippets.

@javarouka
Created March 25, 2019 08:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save javarouka/a9deb84708dacec5e39aff5ca1533a01 to your computer and use it in GitHub Desktop.
Save javarouka/a9deb84708dacec5e39aff5ca1533a01 to your computer and use it in GitHub Desktop.
import java.util.ArrayList;
import java.util.List;
public class Test {
static class Creature {}
static class Animal extends Creature {}
static class Person extends Animal {}
static class Singer extends Person {}
static class GirlGroup extends Singer {}
static class Twice extends GirlGroup {}
private static void testProducer(List<? extends Singer> tests) {
// 가수 이하의 불특정 타입을 요소로 하는 리스트가 온다
// 가수, 걸그룹, 트와이스가 올 수 있다
// 변수는 하위 타입을 할당할 수 있다는걸 생각하면, 이 경우는 그대로다.
/*
tests.add(new Creature());
tests.add(new Singer());
tests.add(new GirlGroup());
tests.add(new Twice());
불가능하다.
이 시점에 전달된 리스트의 타입이 가수도 올 수 있고 트와이스도 올 수 있다
어떤 타입을 추가할 수 있는지 판단하기엔 정보가 부족하다.
만일 이 코드가 허용된다면 걸그룹 리스트였는데 가수를 추가할 경우 타입 캐스팅 오류가 날 것이다.
*/
// 특정 요소를 꺼낸다. Singer 의 상위 계층에 있는 요소는 뭐든 반환 가능하다.
Singer singer = tests.get(0);
Person person = tests.get(0);
Animal animal = tests.get(0);
Creature creature = tests.get(0);
}
private static void testConsumer(List<? super Singer> tests) {
// 가수 이상의 불특정 타입을 요소로 하는 리스트가 온다
// 가수, 사람, 동물, 생물이 올 수 있다
// 변수는 하위 타입을 할당할 수 있다는걸 생각하면, 이 경우는 반대다.
// Singer 를 부모로 하는 제한에 걸린 타입을 추가 가능하다.
tests.add(new Singer());
tests.add(new GirlGroup());
tests.add(new Twice());
/*
불가능하다. 이 시점에 인자로 전달된 타입이 무엇인지 알아낼 방법이 없다
Singer c = tests.get(0); ?
Creature c = tests.get(0); ?
*/
// 결국 무엇이든 할당할 수 있는 타입인 Object 만 할당할 수 있다.
Object c = tests.get(0);
}
public static void main(String ...args) {
List<Twice> twice = new ArrayList<>();
List<GirlGroup> girlGroups = new ArrayList<>();
List<Singer> singers = new ArrayList<>();
List<Person> people = new ArrayList<>();
List<Animal> animals = new ArrayList<>();
List<Creature> creatures = new ArrayList<>();
//testProducer(new ArrayList<Object>());
//testProducer(creatures);
//testProducer(animals);
//testProducer(people);
testProducer(singers);
testProducer(girlGroups);
testProducer(twice);
testConsumer(people);
testConsumer(animals);
testConsumer(creatures);
testConsumer(singers);
testConsumer(new ArrayList<Object>());
//testConsumer(girlGroups);
//testConsumer(twice);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment