在 Java 中的 Collections 对象中声明类型参数两次
Declaring type parameter twice in Collections objects in Java
我一直在学习 Java(使用 Java 6)并且我注意到当创建一个 Collections
对象(比如 ArrayList
)时,一个必须在引用类型和对象类型中声明类型参数。仅在引用类型中声明类型参数不是更容易吗?或者是否存在类型参数可以不同的情况?
例如下面的类型参数(String
)必须声明两次。
List<String> aList = new ArrayList<String>();
查看 https://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained 静态构造函数:
在JDK7之前,构造新的泛型集合需要不愉快的代码重复:
List<TypeThatsTooLongForItsOwnGood> list = new ArrayList<TypeThatsTooLongForItsOwnGood>();
我想我们都同意这很不愉快。 Guava提供了使用泛型推断右边类型的静态方法:
List<TypeThatsTooLongForItsOwnGood> list = Lists.newArrayList();
Map<KeyType, LongishValueType> map = Maps.newLinkedHashMap();
可以肯定的是,JDK 7 中的菱形运算符使这不再那么麻烦:
List<TypeThatsTooLongForItsOwnGood> list = new ArrayList<>();
Java 7 还介绍了 "diamond" form,它可以推断类型并让您编写不那么冗长的代码。
If the type argument list to the class is empty — the diamond form
"<>" — the type arguments of the class are inferred. It is legal,
though strongly discouraged as a matter of style, to have white space
between the "<" and ">" of a diamond.
所以,你可以这样写:
List<String> aList = new ArrayList<>();
有几个例子here.
我一直在学习 Java(使用 Java 6)并且我注意到当创建一个 Collections
对象(比如 ArrayList
)时,一个必须在引用类型和对象类型中声明类型参数。仅在引用类型中声明类型参数不是更容易吗?或者是否存在类型参数可以不同的情况?
例如下面的类型参数(String
)必须声明两次。
List<String> aList = new ArrayList<String>();
查看 https://code.google.com/p/guava-libraries/wiki/CollectionUtilitiesExplained 静态构造函数:
在JDK7之前,构造新的泛型集合需要不愉快的代码重复:
List<TypeThatsTooLongForItsOwnGood> list = new ArrayList<TypeThatsTooLongForItsOwnGood>();
我想我们都同意这很不愉快。 Guava提供了使用泛型推断右边类型的静态方法:
List<TypeThatsTooLongForItsOwnGood> list = Lists.newArrayList();
Map<KeyType, LongishValueType> map = Maps.newLinkedHashMap();
可以肯定的是,JDK 7 中的菱形运算符使这不再那么麻烦:
List<TypeThatsTooLongForItsOwnGood> list = new ArrayList<>();
Java 7 还介绍了 "diamond" form,它可以推断类型并让您编写不那么冗长的代码。
If the type argument list to the class is empty — the diamond form "<>" — the type arguments of the class are inferred. It is legal, though strongly discouraged as a matter of style, to have white space between the "<" and ">" of a diamond.
所以,你可以这样写:
List<String> aList = new ArrayList<>();
有几个例子here.