初探 Java Collections

以前学了很多 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

  • 本质就是一个数组
  • 每当放不下的时候,会增大空间,变成 1.5 倍容量
    oldCapacity + oldCapacity / 2
int newCapacity = oldCapacity + (oldCapacity >> 1);

ArrayList

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

list.add(1);

list.size();

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

Set

  • 不能有重复元素,使用 equals 方法去判断
  • 无序的,可以使用 LinkedHashSet 保证顺序

hashCode

  • 同一个对象必须返回相同的 hashCode
  • equals true,hashCode 必须 true
  • equals false,hashCode 有可能 true

Map

  • 注意修改下面的,原 Map 也会被修改
    keys() -> Set
    values() -> Collection
    entry() -> Map<K, V>

  • 也会自增(和 ArrayList 差不多,也是增 1.5 倍),多线程的时候有可能出现环,导致死循环,即线程不安全。

if (++size > threshold) {
  newHashMap 扩容,和 ArrayList 差不多
}
  • 多线程下应该使用 ConcurrentHashMap
  • Java 7 后使用红黑树,因为 hashCode 都相同,则会变成长 List

TreeSet / TreeMap

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

TreeSet set = new TreeSet(list);

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章