在Java中实例化集合集?
我想实例化一组Set(of strings),然后将两个Set
放入其中,如下所示:
Set setOne = retrieveSetOne(); Set setTwo = retrieveSetTwo(); Set<Set> myCollection = new HashSet<new HashSet<String(); // not working myCollection.add(setOne); myCollection.add(setTwo);
问题是,我对嵌套集的实例化不起作用。 我该怎么做呢?
改为
Set> myCollection = new HashSet>();
在创建实例时按实现初始化,对于需要匹配声明的类型,
如果你已经使用Java7,那么你可以简单地使用
Set> myCollection = new HashSet<>();
Set> myCollection = new HashSet();
为什么实例化内部集? 由于内部集合将在您调用add()时实例化,因此这是多余的,并且可能会破坏您的代码。
我会更像这样的东西:
Set> myCollection = new HashSet>();