Trong ví dụ này:
import java.util.*;
public class Example {
static void doesntCompile(Map<Integer, List<? extends Number>> map) {}
static <T extends Number> void compiles(Map<Integer, List<T>> map) {}
static void function(List<? extends Number> outer)
{
doesntCompile(new HashMap<Integer, List<Integer>>());
compiles(new HashMap<Integer, List<Integer>>());
}
}
doesntCompile()
không thể biên dịch với:
Example.java:9: error: incompatible types: HashMap<Integer,List<Integer>> cannot be converted to Map<Integer,List<? extends Number>>
doesntCompile(new HashMap<Integer, List<Integer>>());
^
trong khi compiles()
được chấp nhận bởi trình biên dịch.
Câu trả lời này giải thích rằng sự khác biệt duy nhất là không giống như <? ...>
, <T ...>
cho phép bạn tham khảo loại sau, dường như không phải là trường hợp.
Sự khác biệt giữa <? extends Number>
và <T extends Number>
trong trường hợp này là gì và tại sao không biên dịch đầu tiên?