什么是从HashSet中检索(任何)元素的更好方法?

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

What is the better way to retrieve (any) element from a HashSet?

问题

我想从我的 HashSet 中检索一些元素,任何元素都可以。由于没有简单的 get 方法存在,目前我使用:

for (Object o : myHashSet){
    return o;
}
return null;

有没有更好的方法来检索 HashSet 中的某个元素?

英文:

I'd like to retrieve some element from my HashSet, any would do. Since no simple get method exists, at the moment I use :

for (Object o : myHashSet){
    return o;
}
return null;

Is there a better way to retrieve just some element from my HashSet?

答案1

得分: 3

你可以使用迭代器:

if (!myHashSet.isEmpty())
    return myHashSet.iterator().next();
return null;

或者,如果你确定Set不为空,可以简单地:

return myHashSet.iterator().next();
英文:

You can use an iterator:

if (!myHashSet.isEmpty())
    return myHashSet.iterator().next();
return null;

or, if you know for sure the Set is not empty, simply:

return myHashSet.iterator().next();

huangapple
  • 本文由 发表于 2020年9月9日 15:58:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/63807190.html
匿名

发表评论

匿名网友

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

确定