集合
程序员文章站
2022-05-25 20:49:51
...
一.集合框架
1.1 List
链表主要分为两种ArrayList,LinkedList
1.1.1 ArrayList
ArrayList组成是由数组形式生成的.故其拥有查找时速度快.但是插入和删除时的损耗较大
如果添加元素的数量大于其容量时.会触发扩容
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);
}
1.1.2 LinkedList
LinkedList是由双向链表组成,其在添加和删除时速度快.但是查找速度慢.
1.2 Set
集合主要分为HashSet,EnumSet,TreeSet
1.2.1 HashSet
HashSet是将其值进行哈希从而进行进行插入的.默认容量值为4.扩容增长为2的幂次.当其装填因子大于0.75将自动扩容
其
private static final Object PRESENT = new Object();
public HashSet() {
map = new HashMap<>();
}
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
1.2.2TreeSet
TreeSet是个有序集合.通过红黑树实现.如果需要对数据进行排序 最好选TreeSet,如果不需要 则是以HashSet
private static final Object PRESENT = new Object();
public TreeSet() {
this(new TreeMap<E,Object>());
}
public boolean add(E e) {
return m.put(e, PRESENT)==null;
}
1.3 Map
映射主要分为HashMap,TreeMap
1.3.1 HashMap
HashMap主要对键进行散列.
static final int DEFAULT_INITIAL_CAPACITY = 4; //默认容量
static final int MAXIMUM_CAPACITY = 1 << 30; //最大容量为2^30
static final float DEFAULT_LOAD_FACTOR = 0.75f; //装载因子
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY) {
initialCapacity = MAXIMUM_CAPACITY;
} else if (initialCapacity < DEFAULT_INITIAL_CAPACITY) {
initialCapacity = DEFAULT_INITIAL_CAPACITY;
}
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
// Android-Note: We always use the default load factor of 0.75f.
// This might appear wrong but it's just awkward design. We always call
// inflateTable() when table == EMPTY_TABLE. That method will take "threshold"
// to mean "capacity" and then replace it with the real threshold (i.e, multiplied with
// the load factor).
threshold = initialCapacity;
init();
}
1.3.2TreeMap
TreeMap采用红黑树的形式进行key,value值的插入.在插入同时会进行排序.
上一篇: Java面向对象(多态)
下一篇: Java面向对象的基础