Collections.emptySet()与new HashSet<>()

huangapple go评论64阅读模式
英文:

Collections.emptySet() vs new HashSet<>()

问题

如何验证Set是否为空集或为new HashSet<>()
尝试了两种方法 -

  1. size
  2. CollectionUtils.isEmpty()
    两者的结果相同。
英文:

How can I validate if the Set is empty set or new HashSet<>() ?
Tried two approaches -

  1. size
  2. CollectionUtils.isEmpty()
    Both result in same value.

答案1

得分: 6

当然,一个新的new HashSet<>()是空的,Set.of()或者Collections.emptySet()也是一样的。重点是:它们都是空集合,我不知道为什么你想要区分这两者之间的差异。

唯一的区别在于,new HashSet<>()现在是空的,但以后可能不为空(它可以被修改;你可以向其中添加元素),而根据规范,Set.of()或者Collections.emptySet()的结果现在是空的,并且以后也会是空的:你不能向它们添加任何内容,在它们上调用.add会导致运行时异常。

这等同于在问:我怎么知道它是否是不可变的。不幸的是,你基本上无法知道,所以问题回归到:为什么你需要知道呢?

英文:

Of course, a fresh new HashSet&lt;&gt;() is empty, and so is Set.of() or Collections.emptySet(). The point is: Both are empty sets, I have no idea why you would want to tell the difference between these two.

The one difference is that new HashSet&lt;&gt;() is empty now but may not be empty later (it can be changed; you can add things to it), whereas as per the spec, the result of Set.of() or Collections.emptySet(), they are empty now and will be empty later: You can't add anything to them, calling .add on them will cause a runtime exception.

That's tantamount to asking: How do I know if it is immutable. You unfortunately basically can't, so that goes right back to: Why would you need to know?

答案2

得分: 1

Collections.emptySet() 返回位于 java.util.Collections 内部的静态类 EmptySet,但 new HashSet&lt;&gt;() 返回一个 java.util.HashSet 类。这两个集合在实例化后都将为空,即大小为 0,但您可以通过调用 .getClass() 来区分这两者,它将返回:

class java.util.Collections$EmptySet
class java.util.HashSet
英文:

Collections.emptySet() returns a static class EmptySetwithin java.util.Collections but new HashSet&lt;&gt;() returns a java.util.HashSet class. Both collections will be empty, i.e., size = 0 after instantiated but you can distinguish those two by calling .getClass() which will return:

class java.util.Collections$EmptySet
class java.util.HashSet

答案3

得分: 1

使用.getClass查看所使用的不同实现。

英文:

Use .getClass to see the different implementation that was used.

答案4

得分: -2

我有一个实用的方法,可以用来执行这个操作 -

Collections.EMPTY_SET.equals(mySet)

感谢大家的回答。

英文:

I got one utility method that can be used to perform the operation -

Collections.EMPTY_SET.equals(mySet)

Thanks all for your answers.

huangapple
  • 本文由 发表于 2020年10月16日 11:11:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/64382398.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定