判空 时间复杂度 可读性
我们都知道判断list为空可以通过两种途径:
一、
1 List list = new ArrayList(2);
2 System.out.println(list.size());//当list.size()==0时,说明该list为空
二、
1 List list = new ArrayList(2);
2 System.out.println(list.isEmpty());//当list.isEmpty为true时,说明该list为空
这样的文章在网上一搜一大堆,并且明确指出两种方式完全一样,真的是这样的吗? 在使用sonar进行代码扫描后,sonar给出这样的说法:
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).
可以概括为两点: 第一:从代码的可读性来说,isEmpty()方法的使用使得代码更具可读性; 第二:从时间复杂度来说,在任何时候isEmpty()方法实现的时间复杂度应为O(1),而size()的某些实现则可以为O(n)。我们往往会忽略这些小的细节,然而,为了让我们的代码更加的强壮,写出更优的代码就是我们不断追求的动力。共勉!!!
Original: https://www.cnblogs.com/ladyM/p/14048410.html
Author: GirlsBoy
Title: java如何效率较高的判断list为空
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/607954/
转载文章受原作者版权保护。转载请注明原作者出处!