如果我有如下所示的代码:
Collection<Object> c = new HashSet<Object>();
它是否仍然保留集合不能包含重复值的属性。换句话说,在以下情况下会发生什么?
String h = "Hello World!";
c.add(h);
c.add(h);
最佳答案
是的,Set
的行为和属性仍然有效。 c
将仅包含一个 “Hello World!”
public static void main(String[] args)
{
Collection<Object> c = new HashSet<Object>();
String h = "Hello World!";
c.add(h);
c.add(h);
System.out.println("c contains " + c.size() + " item(s): " + c);
System.out.println("c is an instance of " + c.getClass());
}
上面的main
方法输出:
c contains 1 item(s): [Hello World!]
c is an instance of class java.util.HashSet
关于java - 使用 Set 构造 Collection 会保留 Set 属性吗? ( java ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10842918/