在进行集合判空时,能用Collection.isEmpty(testList)的就不要用testList.size(),isEmpty不仅可以判断集合是否为null,在时间复杂度上也更优秀。
sonar规范这样描述:
Collection.isEmpty() should be used to test for emptiness
Using Collection.size() to test for emptiness works, but using Collection.isEmpty() makes the code more readable and can be more performant. The time complexity of any isEmpty() method implementation should be O(1) whereas some implementations of size() can be O(n).
也就是说,Collection的实现不同,那么size()方法的时间复杂度也是不同的。