Collection中的size()和isEmpty()区别

一、背景

  没耐心请直接跳到“第三节、最佳实践”
  最近才发现很多网上的“纲领性”的指导完完全全不能相信,比如有的人说isEmpty()判空性能更好,也有的人拿出源码说这两个没区别。Collection集合中有十几种最终实现的类,比如HashMap、ArrayList、TreeSet之类的,如何判空这些集合类是最优雅,性能最好的呢?真的好想知道,既然网上没有那只好自己做测试了。

二、Collection集合类介绍与实验

2.1 测试的集合类

类型 实现类
Map HashMap、TreeMap、LinkedHashMap
List ArrayList
Set HashSet、TreeSet、LinkedHashSet

2.2 Map

HashMap源码:

//每次put元素
final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
    //省略N行代码...
    ++modCount;
    if (++size > threshold) resize();
    afterNodeInsertion(evict);
    return null;
}
//HashMap的size()函数,复杂度为O(1)
public int size() { return size; }
//HashMap的isEmpty()函数,复杂度同为O(1)
public boolean isEmpty() { return size == 0; }

根据上述源码可以看到,HashMap在每次put元素时便维护了size字段,size()==0和isEmpty没任何性能上的区别

2.3 List

ArrayList源码:

//每次添加新的元素的逻辑
public boolean add(E e) {
    ensureCapacityInternal(size + 1);  
    elementData[size++] = e;
    return true;
}
//ArrayList的size()函数,复杂度为O(1)
public int size() { return size; }
//ArrayList的isEmpty()函数,复杂度同为O(1)
public boolean isEmpty() { return size == 0; }

可以看到,用size()==0和isEmpty()性能上没任何区别

2.4 Set

HashSet相对比较简单,其内部维护了一个HashMap而已:

//内部声明的HashMap与其他函数
private transient HashMap<E,Object> map;
public int size() { return map.size(); }
public boolean isEmpty() { return map.isEmpty(); }

HashSet的size()==0和isEmpty()也没有任何性能区别。

三、最佳实践

个人总结,如有雷同,不甚荣幸。

原创文章 18 获赞 25 访问量 9777

猜你喜欢

转载自blog.csdn.net/BlackButton_CC/article/details/103297555