public static void main(String[] args) {
ArrayList list = new ArrayList();
list.add(1);
list.add("a");
list.add(true);
list.add(1.000);
list.add(null); //可以存入null
list.add(null); //可以重复
list.add('z');
System.out.println(list); //按顺序存入
System.out.println("------------------------------");
Iterator iterator = list.iterator(); //获取迭代器
while (iterator.hasNext()) {
System.out.println(iterator.next()); //指针下移并返回指向的元素
}
System.out.println("------------------------------");
System.out.println("移除下标为4的元素:" + list.remove(4)); //移除下标为4的元素,返回移除的元素
System.out.println("移除值为1的元素:" + list.remove((Integer) 1)); //移除值为1的元素,返回是否移除成功
System.out.println(list);
System.out.println("集合的大小:" + list.size());
System.out.println("集合是否包含值为true的元素:" + list.contains(true));
//list.clear(); //清空集合 没有返回值
System.out.println("清空集合中所有元素:" + list.removeAll(list)); //返回是否成功
System.out.println(list);
}
ArrayList扩容机制:
无参构造:
有参构造:
总结:
-
ArrayList使用无参构造时,初始化容量为0,当存入第一个元素时,扩容为默认容量10,以后
每次扩容为原本容量的1.5倍
-
ArrayList使用有参构造时,初始容量为传入的值大小,之后的每次扩容为原本容量的1.5倍
Vector扩容机制:
无参构造:
有参构造:
之后同样扩容为原来容量的2倍
总结:
Vector集合无参构造默认容量为10,之后按照这个大小的2倍进行扩容;有参构造容量为传入值
的大小,之后按照这个值的大小进行2倍扩容
LinkedList:
底层使用双向链表,不存在扩容,
@Test
public void test(){
LinkedList list = new LinkedList<>();
list.add(1); //默认使用尾插法插入元素
list.addLast(2); //使用尾插法插入元素
list.addFirst(3); //使用头插法插入元素
System.out.println(list); //[3, 1, 2]
}
2.Set
HashSet:
基本方法:
@Test
public void test()
{
HashSet set = new HashSet<>();
set.add(1);
set.add("s");
set.add(true);
set.add(1.2);
set.add(null); //可以存入null
set.add(null); //存入元素不可重复
set.add(new String("a"));
set.add("a");
System.out.println(set); //取出元素顺序和存入顺序不一致,但是取出顺序唯一
System.out.println("set集合的大小" + set.size()); //无法通过下标获取元素
System.out.println("=================================");
Iterator iterator = set.iterator();
while(iterator.hasNext())
{
System.out.println(iterator.next());
}
System.out.println("=================================");
}
HashSet底层分析:
//向集合中添加值
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
//辅助变量
Node[] tab; Node p; int n, i;
//如果Node数组table为null或者长度为0 调用resize()方法进行第一次扩容
if ((tab = table) == null || (n = tab.length) == 0)
//tab变量记录初始化后的table
//n变量记录初始化table数组的大小16
n = (tab = resize()).length;
//p变量记录添加值所在table的下标位置的值
//判断当前位置的值是否为空
if ((p = tab[i = (n - 1) & hash]) == null)
//如果为null,直接将值封装成一个Node节点放入table数组当前位置
tab[i] = newNode(hash, key, value, null);
//如果table数组当前位置已经存在Node节点
else {
Node e; K k;
//如果已存在的Node节点和当前添加的Node节点相同
//先判断hash值再调用equal()方法判断
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//如果已存在的Node节点为树节点
else if (p instanceof TreeNode)
//调用红黑树的添加节点方法
e = ((TreeNode)p).putTreeVal(this, tab, hash, key, value);
//如果已存在的Node节点和当前添加的Node节点不相同
else {
//循环遍历单链表
for (int binCount = 0; ; ++binCount) {
//如果链表中不存在相同值 e = null
if ((e = p.next) == null) {
//将该Node节点添加到链表的尾部
p.next = newNode(hash, key, value, null);
//(TREEIFY_THRESHOLD=8)
//即如果链表的长度(不包括头节点) >= 8 则执行treeifyBin()方法
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
//如果链表中存在相同的值则e != null
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
//e != null 返回存在的Node节点的value值
//static finalObject PRESENT 添加失败
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
//修改次数加一,用于多线程下抛出异常
++modCount;
//如果集合大小size超过了当前的阈值threshold(每次成功添加一个元素size就加一)
if (++size > threshold)
resize(); //进行扩容
afterNodeInsertion(evict);
return null; //添加元素成功返回null
}
//将oldTable中的所有元素复制到newTable中
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {
Node e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
((TreeNode)e).split(this, newTab, j, oldCap);
else { // preserve order
Node loHead = null, loTail = null;
Node hiHead = null, hiTail = null;
Node next;
do {
next = e.next;
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
else {
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
//树化 final void treeifyBin(Node[] tab, int hash) { int n, index; Node e; //static final int MIN_TREEIFY_CAPACITY = 64; //如果Node数组的长度 < 64 if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY) resize(); //对数组进行扩容 //如果Node数组的长度 <= 64 就把table数组添加值的那个位置的单链表树化 else if ((e = tab[index = (n - 1) & hash]) != null) { TreeNode hd = null, tl = null; do { TreeNode p = replacementTreeNode(e, null); if (tl == null) hd = p; else { p.prev = tl; tl.next = p; } tl = p; } while ((e = e.next) != null); if ((tab[index] = hd) != null) hd.treeify(tab); } }
测试:
@Test
public void treeify(){
HashSet hashSet = new HashSet();
//将HashSet数组长度扩容到64
for (int i = 1; i < 12; i++) {
hashSet.add(i);
}
for (int i = 12; i <= 25; i++) {
hashSet.add(i);
}
//测试树化条件
for (int i = 0; i < 8; i++) {
hashSet.add(new A(i));
}
}
class A{
private int num;
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public A(int num) {
this.num = num;
}
@Override
public String toString() {
return "A{" +
"num=" + num +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
A a = (A) o;
return num == a.num;
}
@Override
public int hashCode() {
return 0; //设置固定值,用于将所有A类对象加到HashSet的同一条链表中
}
}
总结:
-
HashSet底层使用HashMap,第一次添加数据时扩容到默认容量16,默认加载因子(DEFAULT_LOAD_FACTOR)为0.75,阈值(threshold)为16 * 0.75 = 12
-
向HashSet中添加元素时,先计算出该元素所对应的hash值
hashCode() ^ (hashCode() >>> 16),
然后计算出该元素添加到数组中的下标
(n - 1) & hash [n为数组的长度]
如果数组该位置没有节点则直接添加,如果存在节点就遍历这一条链表,
判断是否存在相同的值(先比较hash值,再调用equal()方法比较),
如果存在则放弃添加,如果不存在则将该元素添加至链表的最后
-
每次添加元素,HashSet的size就加一,当到达阈值时,会再次进行扩容,新的容量为原来的2倍,新的阈值也是原来的两倍,容量(阈值):16(12) --> 32(24) --> 64(48) … 依次类推
-
当一条链表的元素个数 >= 8(TREEIFY_THRESHOLD),并且Node数组的长度>= 64时,整条链表开始树化(红黑树)
LinkedHashSet:
基本方法:
@Test
public void test()
{
LinkedHashSet set = new LinkedHashSet();
set.add(1);
set.add("s");
set.add(true);
set.add(1.2);
set.add(null); //可以存入null
set.add(null); //存入元素不可重复
set.add(new String("a"));
set.add("a");
System.out.println(set); //取出元素顺序和存入顺序一致
System.out.println("set集合的大小" + set.size()); //无法通过下标获取元素
System.out.println("=================================");
Iterator iterator = set.iterator();
while(iterator.hasNext())
{
System.out.println(iterator.next());
}
System.out.println("=================================");
}
总结:
- LinkedHashSet底层使用LinkedHashMap,添加元素还是使用HashSet的那一套模式
- 构建双向链表用于保存添加元素的顺序
TreeSet:
@Test
public void test(){
//自然排序即从小到大
//TreeSet set = new TreeSet();
//从大到小进行排序
TreeSet set = new TreeSet(new Comparator() {
@Override
public int compare(Object o1, Object o2) {
return ((String) o2).compareTo((String) o1);
}
});
set.add("123");
set.add("s");
set.add("asd");
set.add("asd");
System.out.println(set);
}
排序分析:
1.无参构造(不传入Comparator比较器时):
public V put(K key, V value) {
Entry t = root;
//第一次向TreeSet中添加元素
if (t == null) {
compare(key, key); // type (and possibly null) check
未传入Comparator时,调用元素所属类中的comparaTo()方法进行比较(自然排序)
String和各个包装类都实现了Comparable接口
root = new Entry<>(key, value, null);
size = 1;
modCount++;
return null; //添加元素成功返回null
}
int cmp;
Entry parent;
// split comparator and comparable paths
Comparator super K> cpr = comparator;
//如果传入自定义的比较器
if (cpr != null) {
do {
parent = t;
cmp = cpr.compare(key, t.key);
if (cmp < 0)
t = t.left;
else if (cmp > 0)
t = t.right;
else
return t.setValue(value);
} while (t != null);
}
//如果未传入自定义的比较器
else {
//key为null抛出空指针异常
if (key == null)
throw new NullPointerException();
@SuppressWarnings("unchecked")
//使用添加元素所属类中的comparaTo()方法进行比较(自然排序)
Comparable super K> k = (Comparable super K>) key;
do {
parent = t;
//cmp保存比较后的结果
cmp = k.compareTo(t.key);
//如果cmp < 0 向左子树递归比较
if (cmp < 0)
t = t.left;
//如果cmp > 0 向右子树递归比较
else if (cmp > 0)
t = t.right;
//如果cmp = 0 已经存在该元素更新value值
else
return t.setValue(value);
} while (t != null);
}
//将添加元素封装成一个Entry节点
Entry e = new Entry<>(key, value, parent);
//如果cmp < 0 将Entry节点添加至左子节点
if (cmp < 0)
parent.left = e;
//如果cmp >= 0 将Entry节点添加至右子节点
else
parent.right = e;
//添加节点后对树进行平衡处理
fixAfterInsertion(e);
size++;
modCount++;
return null; //添加元素成功返回null
}
2.无参构造(传入自定义Comparator比较器时):
使用自定义的比较器:
//从大到小排序
TreeSet set = new TreeSet(new Comparator() {
@Override
public int compare(Object o1, Object o2) {
return ((String)o2).compareTo((String) o1);
}
});
总结:
- TreeSet底层使用TreeMap,在添加元素时会和已经存在的元素进行比较,将该元素放到排序后的位置
- 当未传入Comparator比较器时,添加元素时使用该元素所在类的compareTo()方法,当传入比较器时,则调用自定义规则进行比较
- 当进行比较后,结果等于0则表示该元素已经存在不会添加
HashMap:
常用方法:
@Test
public void test(){
HashMap map = new HashMap();
map.put("1", "a");
map.put("2", true);
map.put("3", 'a');
map.put("3", 'b'); //key存在时会更新value值
map.put("4", 1);
map.put("5", 1.123);
map.put("6", new Object());
map.put("7", null); //value可以为null
map.put(null, null); //key可以为null,但不能重复
System.out.println("map是否存在key为1:" + map.containsKey("1"));
System.out.println("删除map中key为3的值:" + map.remove("3"));
System.out.println("删除map中key为3值为null的值:"+ map.remove("3", null));
System.out.println("map的大小:" + map.size());
System.out.println(map);
map.clear(); //清空map
System.out.println(map);
}
HashMap的putVal()方法:
四种遍历方式:
@Test
public void get(){
HashMap map = new HashMap();
map.put("1", new Object());
map.put("2", new Object());
map.put("3", new Object());
System.out.println("第一种方式遍历:");
Set set = map.keySet();
for (Object o : set) {
String key = (String)o;
System.out.println(key + "-" + map.get(key));
}
System.out.println("------------------------------");
System.out.println("第二种方式遍历:");
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
String key = (String) iterator.next();
System.out.println(key + "-" + map.get(key));
}
System.out.println("------------------------------");
System.out.println("第三种方式遍历:");
Set entrySet = map.entrySet();
for (Object o : entrySet) {
Map.Entry entry = (Map.Entry)o;
System.out.println(entry.getKey() + "-" + entry.getValue());
}
System.out.println("------------------------------");
System.out.println("第四种方式遍历:");
Iterator iterator1 = entrySet.iterator();
while (iterator1.hasNext()) {
Object o = iterator1.next();
Map.Entry entry = (Map.Entry)o;
System.out.println(entry.getKey() + "-" + entry.getValue());
}
}
//线程同步
public synchronized V put(K key, V value) {
// Make sure the value is not null
//当添加元素的value值为null时抛出空指针异常
if (value == null) {
throw new NullPointerException();
}
// Makes sure the key is not already in the hashtable.
Entry,?> tab[] = table;
//key.hashCode() ---> 当添加元素的key值为null时抛出空指针异常
int hash = key.hashCode();
//Integer.MAX_VALUE = 0x7fffffff(2,147,483,647)
//计算元素添加到Entry数组的下标
int index = (hash & 0x7FFFFFFF) % tab.length;
@SuppressWarnings("unchecked")
//遍历Entry数组该下标的链表,判断是否已经存在相同的key
Entry entry = (Entry)tab[index];
for(; entry != null ; entry = entry.next) {
//如果已经存在(先比较hash再调用equals()方法比较),则更新value值
if ((entry.hash == hash) && entry.key.equals(key)) {
V old = entry.value;
entry.value = value;
return old; //返回原来的value值
}
}
//如果不存在则添加entry节点
addEntry(hash, key, value, index);
return null; //添加元素成功返回null
}
//HashTable扩容
protected void rehash() {
int oldCapacity = table.length;
Entry,?>[] oldMap = table;
// overflow-conscious code
//新的容量为原来容量的两倍加一
int newCapacity = (oldCapacity << 1) + 1;
if (newCapacity - MAX_ARRAY_SIZE > 0) {
if (oldCapacity == MAX_ARRAY_SIZE)
// Keep running with MAX_ARRAY_SIZE buckets
return;
newCapacity = MAX_ARRAY_SIZE;
}
Entry,?>[] newMap = new Entry,?>[newCapacity];
modCount++;
//新的阈值为原来阈值的两倍加一
threshold = (int)Math.min(newCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
table = newMap;
//将原来的Entry数组中的元素拷贝到新的数组中
for (int i = oldCapacity ; i-- > 0 ;) {
for (Entry old = (Entry)oldMap[i] ; old != null ; ) {
Entry e = old;
old = old.next;
int index = (e.hash & 0x7FFFFFFF) % newCapacity;
e.next = (Entry)newMap[index];
newMap[index] = e;
}
}
}
测试:
@Test
public void enlarge() {
Hashtable table = new Hashtable();
for (int i = 0; i < 8; i++) {
table.put(i, i);
}
//第一次扩容
table.put(8, 8);
for (int i = 9; i < 17; i++) {
table.put(i, i);
}
//第二次扩容
table.put(17, 17);
}
总结:
- HashTable添加元素的key和value值都不能为null,不然会抛出空指针异常
- HashTable做了线程同步,是线程安全的,但速度会比HashMap慢
- HashTable默认容量为11,默认加载因子为0.75,默认阈值为8,当HashTable中的元素个数到达当前阈值时会进行扩容,新的容量为原来容量的两倍加一,新的阈值为原来阈值的两倍加一,即容量(阈值):11(8) —> 23(17) —> 47(35),依次类推
TreeMap:
@Test
public void test(){
TreeMap map = new TreeMap(new Comparator() {
@Override
public int compare(Object o1, Object o2) {
return ((String)o2).compareTo((String) o1);
}
});
map.put("1", "1");
map.put("as", "as");
map.put("ys", "ys");
map.put("45", "45");
map.put("qe", "qe");
System.out.println(map);
}
总结:
- TreeSet和TreeMap底层原理一样,不同的是当比较值为0时TreeMap会更新key对应的value值,而TreeSet则是放弃添加元素
存储数据为单列:
选择Collection接口:
数据可以重复:List接口
增加删除操作多:LinkedList(使用双向链表,方便增加和删除)
修改和查找操作多:ArrayList(使用数组,方便遍历)
数据不能重复:Set接口
取出顺序无序:HashSet(使用哈希表[数组+链表]和红黑树)
排序:TreeSet
存入和取出顺序一致:LinkedHashSet(使用数组和双向链表)
存储数据为双列:
选择Map接口:
键无序:HashMap(使用哈希表[数组+链表]和红黑树)
键排序:TreeMap
存入和取出顺序一致:LinkedHashMap(使用数组和双向链表)



