Java 9 enhanced “diamond” syntax
•
Java
List<String> strList = new ArrayList<String>(); Map<String,Integer> scores = new HashMap<String,Integer>();
List<String> strList = new ArrayList<>(); Map<String,Integer> scores = new HashMap<>();
public class Test { public static void main(String[] args) { // Java自动推断出ArrayList的<>里应该是String List<String> names = new ArrayList<>(); names.add("C语言中文网Java入门教程"); names.add("C语言中文网Spring入门教程"); // 遍历names集合,集合元素就是String类型 names.forEach(ele -> System.out.println(ele.length())); // Java 自动推断出 HashMap 的<>里应该是 String,List<String> Map<String,List<String>> coursesInfo = new HashMap<>(); // Java自动推断出ArrayList的<>里应该是String List<String> courses = new ArrayList<>(); courses.add("Java入门教程"); courses.add("Python基础教程"); coursesInfo.put("C语言中文网",courses); // 遍历 Map 时,Map 的 key 是 String 类型,value List<String>类型 coursesInfo.forEach((key,value) -> System.out.println(key + "-->" + value)); } }
interface Foo<T> { void test(T t); } public class AnnoymousTest { public static void main(String[] args) { // 指定Foo类中泛型为String Foo<String> f = new Foo<>() { // test()方法的参数类型为String public void test(String t) { System.out.println("test 方法的 t 参数为:" + t); } }; // 使用泛型通配符,此时相当于通配符的上限为Object Foo<?> fo = new Foo<>() { // test()方法的参数类型为Object public void test(Object t) { System.out.println("test 方法的 Object 参数为:" + t); } }; // 使用泛型通配符,通配符的上限为Number Foo<? extends Number> fn = new Foo<>() { // 此时test ()方法的参数类型为Number public void test(Number t) { System.out.println("test 方法的 Number 参数为:" + t); } }; } }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码