GirlsBoy
回首向来萧瑟处,归去,也无风雨也无晴。

  我们都知道判断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)。
我们往往会忽略这些小的细节,然而,为了让我们的代码更加的强壮,写出更优的代码就是我们不断追求的动力。共勉!!!
posted on 2020-11-27 15:46  GirlsBoy  阅读(492)  评论(0编辑  收藏  举报

java\web应用开发&研究

梦想程序改变生活

成为一个了不起的人