Arrays.getOnlyElement()?

发布于 2024-11-10 08:11:31 字数 296 浏览 2 评论 0原文

是否有相当于 Collections.getOnlyElement() 适用于数组吗?

我知道这是一个实现起来很简单的函数,但 Collections.getOnlyElement() 也是如此,而且它是在番石榴中实现的。

Is there any equivalent to Collections.getOnlyElement() that works with arrays?

I'm aware it's a trivial function to implement, but Collections.getOnlyElement() is as well, and it's in guava.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

过潦 2024-11-17 08:11:31

Iterators.getOnlyElement(Iterators.forArray(array))

通过使用 Iterators.forArray,您可以不需要将此数组的副本创建为列表,而是进行迭代在数组本身之上。然后使用 Iterators.getOnlyElement 从迭代器中获取第一个元素。

Iterators.getOnlyElement(Iterators.forArray(array))

By using Iterators.forArray, you can bypass the need to create a copy of this array as a list, and instead iterate over the array itself. Then use Iterators.getOnlyElement to get the first element from an iterator.

只想待在家 2024-11-17 08:11:31

不太好,但仍然是一句台词:

Object x = Iterables.getOnlyElement(Arrays.asList(t));

Not nice but still a one-liner:

Object x = Iterables.getOnlyElement(Arrays.asList(t));
万劫不复 2024-11-17 08:11:31
 if(myArray != null && myArray.length == 1)
      return myArray[0]

顺便提一句。如果像这样初始化,数组可以为非空且长度为 0:

 MyType[] myArr = new MyType[0];
 if(myArray != null && myArray.length == 1)
      return myArray[0]

Btw. an array can be non-null and have 0 length if initialized like this:

 MyType[] myArr = new MyType[0];
成熟的代价 2024-11-17 08:11:31

我不知道有任何库方法可以做到这一点。这似乎太简单了,不值得付出努力。

我遇到的最接近的(在拖网搜索结果页面之后)是这个 - uk.org.retep.util.collections.ArrayUtils.getFirst - 它与您所要求的语义不同。

I don't know of any library method that does this. It seems too simple to be worth the effort.

The closest I've come across (after trawling pages of search results) is this - uk.org.retep.util.collections.ArrayUtils.getFirst - which has a different semantic to what you are asking for.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文