Arrays.getOnlyElement()?
Is there any equivalent to Collections.getOnlyElement() that works with arrays?
I'm aware it's a trivial fu开发者_开发问答nction to implement, but Collections.getOnlyElement() is as well, and it's in guava.
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.
Not nice but still a one-liner:
Object x = Iterables.getOnlyElement(Arrays.asList(t));
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];
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.
精彩评论