简体   繁体   English

检查该数组是否为空,但不是null

[英]Check that array is empty, but not null

I have an array of objects ( Object[] array ), and I want to check whether it is empty, but fail fast if it is null with NPE or any other exception. 我有一个对象数组( Object[] array ),我想检查它是否为空,但如果它与NPE或任何其他异常为空则快速失败。

I know that I can do the following check 我知道我可以做以下检查

array.length == 0

but eg in case of String or collections it is not recommended practice, IntelliJ even has inspection for that: 但是,例如在String或集合的情况下,不建议练习,IntelliJ甚至检查:

Reports any .size() or .length() comparisons with a 0 literal which can be replaced with a call to .isEmpty() . 报告任何.size().length()与0文字的比较,可以用.isEmpty()调用替换。

Is there any replacement for .isEmpty() for arrays? 数组的.isEmpty()是否有替换?

There is ArrayUtils.html#isEmpty(java.lang.Object[]) , but it also checks for null , while I'd like to avoid that. ArrayUtils.html#isEmpty(java.lang.Object []) ,但它也检查null ,而我想避免这种情况。

Because .size() is method, its implementation is hidden. 因为.size()是方法,所以它的实现是隐藏的。 And you can't be sure that this method optimized (there's a possibility , that some collections, for example, enumerate items every time you call .size() method). 并且您无法确定此方法是否已优化(有可能 ,某些集合,例如,每次调用.size()方法时都会枚举项目)。 That is why computing the .size() of collection could be expensive. 这就是为什么计算集合的.size() 可能会很昂贵。 In the same time, .isEmpty() can checks just is there at least one item in collection, and return result. 同时, .isEmpty()可以检查集合中是否至少有一个项目,并返回结果。

But .length is just a field. .length只是一个领域。 It does nothing, just returns a value. 它什么都不做,只返回一个值。 There are no calculations. 没有计算。 This field just stores the length of array with fixed size. 该字段仅存储具有固定大小的数组的长度。

I believe that .size() and .length are totally different things and in this case they can not be compared, as well as collections and arrays. 我相信.size().length是完全不同的东西,在这种情况下它们是无法比较的,以及集合和数组。

The easiest way would to be to write such a method yourself. 最简单的方法就是自己编写这样的方法。 It would be fairly trivial. 这将是相当微不足道的。 Something like the following 像下面这样的东西

public boolean isArrayEmpty(Object[] array) {
    if (array == null) {
        //Throw nullpointer exception
        //An easy of method of doing this would be accessing any array field (for example: array.length)
    }
    return (ArrayUtils.isEmpty(array));
}

That being said, there's very little reason why array.length == 0 would be harmful. 话虽这么说,没有理由说array.length == 0会有害。 It's the simplest, cleanest way to do this and does exactly what you want. 这是最简单,最干净的方法,并且完全符合您的要求。 Most likely part of the reason for ArrayUtils.isEmpty is to allow easy testing of whether or not a array is empty or null, a relatively common need, but you don't want to do that. 最有可能的部分原因是ArrayUtils.isEmpty允许轻松测试数组是否为空空,这是一个相对常见的需求,但您不希望这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM