在Java中实例化集合集?

时间:2014-08-08 22:08:37

标签: java

我想实例化一组(字符串),然后将两个Set<String>放入其中,如下所示:

Set<String> setOne = retrieveSetOne();
Set<String> setTwo = retrieveSetTwo();
Set<Set<String>> myCollection = new HashSet<new HashSet<String<()>(); // not working
myCollection.add(setOne);
myCollection.add(setTwo);

问题是,我对嵌套集的实例化不起作用。我该怎么做?

2 个答案:

答案 0 :(得分:5)

将其更改为

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

在创建实例时按实现初始化,对于需要匹配声明的类型

如果您已经使用Java7,那么您只需使用

即可
Set<Set<String>> myCollection = new HashSet<>();

答案 1 :(得分:0)

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

为什么要实例化内部集合?由于内部集合将在您调用add()时实例化,因此这是多余的,并且可能会破坏您的代码。

我会更喜欢这样的东西:

Set<Set<String>> myCollection = new HashSet<Set<String>>(); 
相关问题