在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);

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

将其更改为

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

当您创建实例时,您可以通过实现进行初始化,对于需要匹配声明的类型,

如果你已经使用Java7,那么你可以简单地使用

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

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

我会放一些更像这样的东西:

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

最新更新