public class CollectionClassifier {
public static String classify(Set<?> s) {
return "집합";
}
public static String classify(List<?> lst) {
return "리스트";
}
public static String classify(Collection<?> c) {
return "그 외";
}
public static void main(String[] args) {
Collection<?>[] collections = {
new HashSet<String>(),
new ArrayList<BigInteger>(),
new HashMap<String, String>().values()
};
for (Collection<?> c : collections)
System.out.println(classify(c));
}
}
컴파일타임
에 정해지기 때문이다.Collection<?>
타입이다.class Wine {
String name() { return "포도주"; }
}
class SparklingWine extends Wine {
@Override String name() { return "발포성 포도주"; }
}
class Champagne extends SparklingWine {
@Override String name() { return "샴페인"; }
}
public class Overriding {
public static void main(String[] args) {
List<Wine> wineList = List.of(
new Wine(), new SparklingWine(), new Champagne());
for (Wine wine : wineList)
System.out.println(wine.name());
}
}
가장 하위에서 정의한
재정의 메서드가 실행됨ObjectOutputStream 클래스의 write 메서드는 모든 기본 타입과 일부 참조 타입용 변형을 가지고 있다.
근본적으로 다르다
면 헷갈릴 일이 없다public class SetList {
public static void main(String[] args) {
Set<Integer> set = new TreeSet<>();
List<Integer> list = new ArrayList<>();
for (int i = -3; i < 3; i++) {
set.add(i);
list.add(i);
}
for (int i = 0; i < 3; i++) {
set.remove(i);
list.remove(i);
}
System.out.println(set + " " + list);
}
}
예상 결과 값
list.remove의 인수를 Onteger로 형변환하여 사용하면 된다.
혹은 Integer.valueOf를 이용해 i를 Integer로 변환 후 전달해도 된다.
for (int i = 0; i < 3; i++) {
set.remove(i);
list.remove((Integer) i); // 혹은 remove(Ineger.valueOf(i))
}
List<E>
interface가 remove(Object)와 remove(int)를 다중정의 했기 때문이다.