集合
-
什么是集合:对象的容器,实现对对象的常用操作
-
集合和数组的区别
- 数组长度固定,集合的不固定
- 数组长度可以存储基本数据类型和引用类型,集合只能存储引用类型
-
Collection体系集合
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-8BLKdxQm-1617759551669)(C:\Users\wu\Desktop\markdown\image-20210316201324157.png)]
-
//(1)添加元素(2)删除元素(3)遍历元素(4)判断 //创建集合 Collection collection = new ArrayList(); //1.添加元素 collection.add("香蕉"); collection.add("苹果"); collection.add("西瓜"); System.out.println("元素个数:"+collection.size()+" "+collection); //2.删除 collection.remove("香蕉"); System.out.println("元素个数:"+collection.size()+" "+collection); //3.遍历 //3.1增强for for (Object o:collection) { System.out.println(o); } //3.2迭代器Iterator //Iterator接口有hasNext,next和remove方法 Iterator iterator = collection.iterator(); while (iterator.hasNext()){ System.out.println(iterator.next()); } System.out.println(collection.isEmpty()); System.out.println(collection.contains("香蕉"));
List子接口
- 特点:有序,有下标,元素可重复
- 方法:
- void add(int index,0bject o)//在index位置插入对象o。
- boolean addAll(int index,Collection c) //将一个集合中的元素添加到此集合中的index位置
- Object get(int index) 获取下标为index的对象
- List subList(int fromIndex,int toIndex)//返回fromIndex和toIndex之间的集合元素,含头不含尾。
public static void main(String args[]){
List list = new ArrayList<>();
//添加
list.add("d1");
list.add("d2");
list.add(0,"d0");
System.out.println(list);
//删除
list.remove(0);
System.out.println(list);
//遍历
//1.for循环
for(int i=0;i<list.size();i++){
System.out.println(list.get(i));
}
//2.foreach
for(Object o:list){
System.out.println(o);
}
//3.迭代器
Iterator iterator = list.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
//4.列表迭代器
ListIterator listIterator = list.listIterator();
//从前往后遍历
while (listIterator.hasNext()){
System.out.println(listIterator.nextIndex()+":"+listIterator.next());
}
//从后往前
while(listIterator.hasPrevious()){
System.out.println(listIterator.previousIndex()+":"+listIterator.previous());
}
}
//运行结果
[d0, d1, d2]
[d1, d2]
d1
d2
d1
d2
d1
d2
0:d1
1:d2
1:d2
0:d1
Process finished with exit code 0
List实现类
- ArrayList
- 数组结构实现,查询快,增删慢
- JDK1.2,线程不安全,运行效率快
- Vector
- 数组结构实现,查询快,增删慢
- JDK1.0,线程安全,运行效率低
- LinkedList
- 链表结构实现,增删快,查询慢
- 线程不安全,效率比较高
ArrayList
默认容量:DEFAULT_CAPACITY = 10
存放元素的数组:elementData
实际元素个数size
如果没向集合中添加任何元素是,容量为0,添加任意一个元素后容量就是10
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
private static int calculateCapacity(Object[] elementData, int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return minCapacity;
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++; //修改次数
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
// 右移一位 == 除以2,所以新容量是旧容量的1.5倍
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);
}
泛型 本质是参数化类型,把类型作为参数传递,代码复用,防止类型转换异常
常见形式有 泛型类,泛型接口,泛型方法
<T …> 类型占位符,T可以替换成E,K之类的字母
泛型集合:参数化类型,类型安全,强制集合元素必须一致
set子接口
特点:无序,无下标,元素不可重复
方法:全部继承Collection
set接口的使用
- HashSet
- 基于HashCode实现元素不可重复
- 当存入元素哈希码相同是,调用equals判断,为真才存入
- 哈希表
- TreeSet
- 基于排列顺序实现元素不重复
HashSet的使用(底层就是hashmap)
public static void main(String args[]){
HashSet<String> hashSet = new HashSet<>();
hashSet.add("AA");
hashSet.add("BB");
hashSet.add("GG");
hashSet.add("JJ");
//添加一个重复值
hashSet.add("JJ");
//可以添加null
hashSet.add(null);
System.out.println("个数:"+hashSet.size());
System.out.println(hashSet.toString());
//删除
hashSet.remove(null);
System.out.println(hashSet.toString());
//遍历 foreach
for (String s:hashSet) {
System.out.println(s);
}
//迭代器遍历
Iterator<String> it = hashSet.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-lqKJpGFg-1617759551670)(C:\Users\wu\Desktop\markdown\image-20210322102202934.png)]
存储过程
(1)根据hashcode计算保存的位置,如果此位置为空,则直接保存,如果不为空执行第二步。
(2)再执行equals方法,如果equals方法为true,则认为是重复,否则,形成链表
i<<5 == i * 2^5
i >>1 == i/2
TreeSet
- 基于排序顺序实现元素不重复
- 不可以添加null元素
- 实现了SortedSet接口,对集合元素自动排序
- 元素对象的类型必须实现Comparable接口,指定排序规则
- 通过CompareTo方法确定是否为重复元素
@Override
public int compareTo(Person o) {
//Person就name和age两个属性
int n1=this.getName().compareTo(o.getName());
int n2=this.age-o.getAge();
//n1等于0代表两者名字相等
return n1==O?n2:n1;
}
comparator(实现定制比较)
TreeSet<String> treeSet = new TreeSet<>(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
});
//
TreeSet<String> treeSet = new TreeSet<>((o1, o2) -> o1.compareTo(o2));
Map集合
Map接口特点
- 键值对形式存值(key-value)
- 无序无下标
- 键不可重复,而值可以
- 方法:
- put 添加元素,key重复则覆盖原则
- get 获得
- entrySet 返回所有key
- value() 返回包含所有值的Collection集合
HashMap
public static void main(String args[]){
Map<String,String> map = new HashMap();
//添加
map.put("cn","中国");
map.put("us","美国");
map.put("uk","英");
map.put("uk","英国");
map.put(null,null);
System.out.println(map.size()+":"+map);
//删除
map.remove(null);
System.out.println(map.size()+":"+map);
//遍历
for(String s:map.keySet()){
System.out.print(s+" "+map.get(s)+" | ");
}
System.out.println();
// 利用entrySet来遍历
Set<Map.Entry<String,String>> entries = map.entrySet();
for(Map.Entry<String,String> m:entries){
System.out.print(m.getKey()+" "+m.getValue()+" | ");
}
System.out.println();
//判断
System.out.println(map.containsKey("cn"));
System.out.println(map.containsValue("韩国"));
}
/**
* The default initial capacity - MUST be a power of two.
初始容量大小,必须为2的倍数
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
//最大容量
static final int MAXIMUM_CAPACITY = 1 << 30;
//默认的装载因子 假如容量为100 有75个元素,此时装载因子就达到了0.75就需要扩容了
static final float DEFAULT_LOAD_FACTOR = 0.75f;
//当链表长度大于8 集合元素个数大于64时,调整黑树
// THRESHOLD 阈值
static final int TREEIFY_THRESHOLD = 8;
//当链表长度小于6时,调整成成链表
static final int UNTREEIFY_THRESHOLD = 6;
static final int MIN_TREEIFY_CAPACITY = 64;
//哈希表中的数组
transient Node<K,V>[] table;
// 刚创建hashmap之后没有添加table=null size=0
//添加元素
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);
}
//
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;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
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
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
//resize()会将容量初始化为16(DEFAULT_INITIAL_CAPACITY),之后每次元素数量达到容量的0.75(比如16*0.75=12时)就会扩容2倍,newCap = oldCap << 1
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
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;
}
(1)HashMap刚创建时,table是null,为了节省空间,当添加第一个元素时,table容量调整为16
(2)当元素个数大于阈值(16*0.75=12)时,会进行扩容,扩容后大小为原来的2倍。目的是减少调整元素的个数。
(3)jdk1.8当每个链表长度大于8,并且数组元素个数大于等于64时,会调整为红黑树,目的提高执行效率
(4)jdk1.8单个Node节点下的红黑树节点的个数小于6时候,会将红黑树转化成为链表。
HashTable
- JDK1.0版本,线程安全,运行效率慢;不允许null作为key或是value。在每个增删改元素的方法前都加了synchronized,导致运行效率低
Properties
- Hashtable的子类,要求key和value都是String。通常用于配置文件的读取
TreeMap
- 实现了SortedMap接口(是Map的子接口),可以对key自动排序。和TreeSet类似,存储的元素的类 需要实现一个能够比较排序的方法,或者实现定制比较(Comparetor)
Collections工具类
- 集合工具类,定义除了存取以外的集合常用方法
- 方法:
- public static void reverse(List<?> list)//反转集合中元素的顺序
- public static void shuffle(List<?> list)//随机重置集合元素的顺序
调整为红黑树,目的提高执行效率
(4)jdk1.8单个Node节点下的红黑树节点的个数小于6时候,会将红黑树转化成为链表。
HashTable
- JDK1.0版本,线程安全,运行效率慢;不允许null作为key或是value。在每个增删改元素的方法前都加了synchronized,导致运行效率低
Properties
- Hashtable的子类,要求key和value都是String。通常用于配置文件的读取
TreeMap
- 实现了SortedMap接口(是Map的子接口),可以对key自动排序。和TreeSet类似,存储的元素的类 需要实现一个能够比较排序的方法,或者实现定制比较(Comparetor)
Collections工具类
- 集合工具类,定义除了存取以外的集合常用方法
- 方法:
- public static void reverse(List<?> list)//反转集合中元素的顺序
- public static void shuffle(List<?> list)//随机重置集合元素的顺序
- public static void sort(List list)//升序排序(元素类型必须实现Comparable接口)