集合1.0
-
集合的基本性质和方法
-
单列 collection
- 有序
list ( vector , array list , linked list )
- 无序
set ( tree set , hash set )
-
双列 map
- hash map ( linked hash map ) , hash table ( properties ) , tree map
集合存放的是 object 对象 ( 默认数据类型 , object )
list
可以包含多个相同元素 , 可以包含null
查询多 , 用array , 删改多 , 用linked ( 或者array采用垃圾回收机制 )
Array list
维护了一个object数组 , 可以放所有的类 , 这个数组有 transient 属性 , 表示该数组不会被序列化 , 即在序列化时会被忽略
如果使用无参构造器 , 则初始容量为0 , 在第一次添加的时候变成 10 , 满了以10 的1.5 倍扩容
如果指定长度构造器 , 则满了之后以设定长度的1.5倍扩容
linked list
Linkes list 维护了一个双向链表 , 可以重复 , 可以有null , 线程不安全
vector
和arra list 性质基本一致 , 不同点有两点
- 是线程安全的 , 但效率较慢
- 无参默认10 , 一次扩容2倍
set
不能存放相同的元素 , 存放和取出的顺序不一致 , 但是是固定的 , 可以有null但只能有一次 , 添加成功返回 T ,失败( 重复 ) 返回 F
set 如何判断是否相同
如果 hash 和 equals 判断相同 , 则为同一个元素
先判断 hash , 后判断 equals
-
获取对象的hash值,hash值获得途径
- 通过地址值转化
- 通过class的tohashcode方法重写来决定用某几个属性来决定hash,或者返回固定值(该类的对象hash相同)
-
hash值通过特定算法得到table数组索引,相同的hash会放在同一个链表中
-
如果加入的对象的索引处没有元素,直接加入,如果有,通过equals来判断链表中的元素是否相同,不一样则挂在最后
-
如果需要加入一个类让某几个属性决定是否相同,则hashcode和equals都要重写,hashcode保证在一个链表(不在一个链表则equals一样也可以加入)
set 的加入方式
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
// private static final Object PRESENT = new Object();
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
//返回处理后的hash,处理是为了降低重复性
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//如果是初次加入,n(table长度)为默认容量(默认tab = resize())
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
//如果索引(i = (n - 1) & hash)处的对象为空就直接让进去
//如果不为空
else {
Node<K,V> e; K k;
//首先比较和放在数组中的链表第一个元素hash相等并且(和链表第一个元素指向同一个对象或者equals为真)
//为真则e!=null,放入失败
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
//如果放入的是红黑树,则用红黑树比较法
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
//如果和第一个不相等,不是树,则和哈希值计算索引的数组位置放的链表的每一个元素来比较,如果都不一样,则加入到链表的最后
for (int binCount = 0; ; ++binCount) {//死循环
if ((e = p.next) == null) {//所有的都比较完了//下移动作//直接加
p.next = newNode(hash, key, value, null);//在尾巴上加
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st//把元素添加到链表最后时,即刻对当前链表进行树化,在树化时,还会进行一个判断,需要table长度大于64,否则会对数组扩容
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))//链表中存在相同
break;
p = e;//下移动作
}
}
if (e != null) {//对象重复时会e!=null,即e指向相同的元素,如果e==null,则说明链表找完了都没找到 // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;//加入次数+1
if (++size > threshold)//如果下一个长度比临界值大
resize();//扩容
afterNodeInsertion(evict);//由hashmap子类完成
return null;//返回上一级,如果返回的是null则加入成功
}
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;//threshold = 16 *0.75
int newCap, newThr = 0;
if (oldCap > 0) {
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {
Node<K,V> 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<K,V>)e).split(this, newTab, j, oldCap);
else { // preserve order
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> 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;
}
}
}
}
}
return newTab;
}
//4. 关于扩容,加入12个元素或者同一个链表加到8个即会让table扩容2倍,同时满足table大于64且一个链表元素大于8则该链表树化
hash 的扩容方式
hash 的 结构是 链表 node 组成的数组 table , 当node达到 8 的时候 , 会对 table进行两倍扩容 , 如果table 大于 68 , node 大于 8 , 则会进行树化
hash set
底层存储是存放单向链表的数组
linked hash set
属于hash set 子类
用 hash code 决定数据储存的位置 , 同时用链表维护数据顺序 , 使元素看起来像用插入顺序保存的
集合的操作方式
加入元素 add , add All
返回 T / F , list 支持在特定位置插入 , 如果指定位置超过list 长度 , 会显示数组越界异常
arrayList.add(1);//加入基本类型时候自动装箱
arrayList.add("akaashi");
arrayList.add(true);
list.add(1,12);//在指定位置插入元素
System.out.println(arrayList);//输出list名即使toString输出所有元素
arrayList.addAll(arrayList1);//可以加入适配的collection集合
arrayList.addAll(2,list);//可以在指定位置加入适配的collection集合
不同之处
-
list 底层调用
-
public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! elementData[size++] = e; return true; } -
set 底层调用
-
public boolean add(E e) { return map.put(e, PRESENT)==null; }
删除元素 remove , clear
list 可以通过索引和对象来 remove , 索引返回删除对象或者数组越界异常 , 对象返回 T / F , 如果删除 数字 类型对象 , 需要类型转化成对应的包装类
set 是无序的 , 不能通过索引来删除 , 可以通过对象来 remove , 返回 T / F
arrayList.remove((Integer)1);
//单独删除
arrayList.removeall(arrayList1);
//批量删除
arrayList.clear();
//清空list
判断是否存在is Empty , contains , contains All
判断集合是否存在 is Empty , 返回 T / F
判断元素是否存在 contains , contains All , 返回 T / F
arrayList.clear();
arrayList.contains("akaashi");
arrayList.containsAll(arrayList1);
获得长度 size
ArrayList list = new ArrayList();
list.add("123");
list.add("asd");
list.add(1234);
list.add(23);
list.add("123");
System.out.println(list.size());
list特有操作
获得指定位置元素 get
返回获得的对象 , 或者数组越界异常
list.get(0)
获得元素索引 indexOf , lastIndexOf
list 元素可以重复 , 可以获得第一次出现或者最后一次出现的索引 , 没有找到返回 -1
list.add("123");
list.add("asd");
list.add(1234);
list.add(23);
list.add("123");
System.out.println(list.indexOf("123"));
//0
System.out.println(list.lastIndexOf("123"));
//4
替换指定位置元素 set
ArrayList list = new ArrayList();
list.add("123");
list.add("asd");
System.out.println(list.set(1,12));
//返回替换的元素
System.out.println(list);
[123, 12]
分割list得到指定范围集合 subList
ArrayList list = new ArrayList();
list.add("123");
list.add("asd");
list.add(1234);
list.add(23);
System.out.println(list.subList(1,4));
//范围前闭后开,超出范围返回异常
//Exception in thread "main" java.lang.IndexOutOfBoundsException: toIndex = 100
//前面大于后面返回异常
//Exception in thread "main" java.lang.IllegalArgumentException: fromIndex(10) > toIndex(1)
遍历元素
list特有 : 一般for循环
list ( vector , array list , linked list ) 是有序的 , 可以用下标检索 , 可以用一般for循环
ArrayList list = new ArrayList();
list.add("123");
list.add("asd");
for (int i = 0; i < list.size(); i++) {
System.out.println(i +" = " + list.get(i));
}
list , set 都能用
迭代器iterator
collection 接口实现了 iterator 接口 , 集合实例可以用里面方法可以返回 对象 , 用返回的对象 , 就是迭代器 , 来遍历集合
Iterator iterator = arrayList.iterator();
while (iterator.hasNext()){//判断是否还会有下一个对象
System.out.println(iterator.next());//下移并取出下移位置的对象
//最开始next作为头指针不存任何数据
//itit可以快速使用迭代器while
//Ctrl + j 查看所有快捷键
迭代器遍历循环完成时 , next指向最后 , 不能在向下走 , 强行走报错 no such element exception
如果要重新遍历 , 可以重置next指针
iterator = arrayList.iterator();
增强for循环
简化版的迭代器循环
for (Object a:arrayList) {
System.out.println(a);
}
//快捷键I 或者arraylist.for
-
单列 collection
- 有序
list ( vector , array list , linked list )
- 无序
set ( tree set , hash set )
-
双列 map
- hash map ( linked hash map ) , hash table ( properties ) , tree map
集合存放的是 object 对象 ( 默认数据类型 , object , )
map
hashmap
双列结构 , 和 set 结构相似 , set 保存的值保存在 key 部分 , v 部分是默认的 , map 则是 key ,v 都可以设置 , 同样的 , map 的 key 部分可以允许一个null , 查重 , 扩容的部分和 hash set 相同 , v 部分没有限制
linked hash map
维护了一个双向链表 , 可以保证放入顺序和取出顺序一致
hashtable
map常用遍历
map 取出元素的方式
利用key集合 使用增强for或者迭代器 get (k)
注意 , 增强for和迭代器取出的都是键值对 , 需要用 get (key) 来取出值
//第一组: 先取出 所有的 Key , 通过 Key 取出对应的 Value
Set keyset = map.keySet();
//(1) 增强 for
System.out.println("-----第一种方式-------");
for (Object key : keyset) { System.out.println(key + "-" + map.get(key)); }
//(2) 迭代器
System.out.println("----第二种方式--------");
Iterator iterator = keyset.iterator();
while (iterator.hasNext())
{ Object key = iterator.next();
System.out.println(key + "-" + map.get(key)); }
使用map维护的储存v值的单列集合 values()再迭代
//第二组: 把所有的 values 取出
Collection values = map.values();
//这里可以使用所有的 Collections 使用的遍历方法
//(1) 增强 for
System.out.println("---取出所有的 value 增强 for----");
for (Object value : values) { System.out.println(value); }
//(2) 迭代器
System.out.println("---取出所有的 value 迭代器----");
Iterator iterator2 = values.iterator();
while (iterator2.hasNext())
{ Object value = iterator2.next();
System.out.println(value); }
使用map维护的储存数据的set entrySet()
node 实现了 entry 接口 , 最先出现 node 是hash set , node 是储存数据的地方 , entry 也是储存数据的地方 , 可以取出 entry 集合 , 遍历取出 , 此时为object形式接收 , 转化成(Map.Entry) , getkey , getvalue ,
//第三组: 通过 EntrySet 来获取 k-v
Set entrySet = map.entrySet();
// EntrySet<Map.Entry<K,V>>
//(1) 增强 for
System.out.println("----使用 EntrySet 的 for 增强(第 3 种)----");
for (Object entry : entrySet) {
//将 entry 转成 Map.Entry
Map.Entry m = (Map.Entry) entry;
System.out.println(m.getKey() + "-" + m.getValue()); }
//(2) 迭代器
System.out.println("----使用 EntrySet 的 迭代器(第 4 种)----");
Iterator iterator3 = entrySet.iterator();
while (iterator3.hasNext()) {
Object entry = iterator3.next();
//System.out.println(next.getClass());
//HashMap$Node -实现-> Map.Entry (getKey,getValue)
//向下转型
Map.Entry Map.Entry m = (Map.Entry) entry;
System.out.println(m.getKey() + "-" + m.getValue());
map常用方法
加入put
根据键删除键值对 remove
// remove:根据键删除映射关系
map.remove(null);
System.out.println("map=" + map);
根据键获得值 get
// get:根据键获取值
Object val = map.get("鹿晗");
System.out.println("val=" + val);
获得数组长度 size
// size:获取元素个数
System.out.println("k-v=" + map.size());
查找键是否存在 containsKey
// containsKey:查找键是否存在
System.out.println("结果=" + map.containsKey("hsp"));//T
清除所有数据 clear
// clear:清除 k-v
map.clear();
System.out.println("map=" + map);
判断数据量是否为0 isEmpty
// isEmpty:判断个数是否为 0
System.out.println(map.isEmpty());//F

浙公网安备 33010602011771号