如何使用Generics在Java中实例化一个集合?

时间:2011-12-13 23:12:06

标签: java

什么是最好的方式:

Set<String> myStringSet = new HashSet();

或者

Set<String> myStringSet = new HashSet<String>();

以上都没有?

重要吗?

3 个答案:

答案 0 :(得分:5)

信:

Set<String> myStringSet = new HashSet<String>();

有关详细信息,请参阅the Java documentation on generic types

答案 1 :(得分:3)

您应该始终使用泛型类型

初始化集合
Set<String> myStringSet = new HashSet<String>();

否则你会收到警告

Type safety: The expression of type HashSet needs unchecked conversion 
to conform to Set <String>.

答案 2 :(得分:0)

第二种是最好,最安全的方法。

Set<String> myStringSet = new HashSet();将编译并发出...uses unchecked or unsafe operations.警告。如果您使用的是没有泛型类型说明符(HashSet()而不是HashSet<String>())的集合,则会出现在Java 5及更高版本中。

省略泛型类型说明符将禁止编译器使用泛型来检查您是否以类型安全的方式使用HashSet