饥人谷技术博客

Java Collections 初探

2020-06-09  本文已影响0人  写代码的海怪

以前学了很多 ArrayList, List, Set 啥的,他们的爹都是 Collection,Collection 是一个接口,里面提供了很多方法,如 add, remove 等。

初始化

Collection<Integer> c = new LinkedHashSet();

List<Integer> list = new ArrayList<>(c);

等价于

List<Integer> list = new ArrayList<>();
list.addAll(c);

等价于

List<Integer> list = new ArrayList<>();
for (Integer i : c) {
  list.add(i);
}

List

int newCapacity = oldCapacity + (oldCapacity >> 1);

ArrayList

List<Integer> list = new ArrayList<>(初始容量);

list.add(1);

list.size();

list.retainAll(list2); // 做交集

Set

hashCode

Map

if (++size > threshold) {
  newHashMap 扩容,和 ArrayList 差不多
}

TreeSet / TreeMap

HashSet 顺序的随机的
TreeSet 使用 Comparable 可以变成有顺的

TreeSet set = new TreeSet(list);

TreeMap 的 Key 就是 TreeSet,也是有顺序的。

上一篇 下一篇

猜你喜欢

热点阅读