Java-集合

  • 集合的框架体系

image-20230823214521514

image-20230823214526731

Collection

image-20230823215306628

方法名说明
boolean add(E e)向集合添加元素e,若指定集合元素改变了则返回true
boolean addAll(Collection<? extends E> c)把集合C中的元素全部添加到集合中,若指定集合元素改变返回true
void clear()清空所有集合元素
boolean contains(Object o)判断指定集合是否包含对象o
boolean containsAll(Collection<?> c)判断指定集合是否包含集合c的所有元素
boolean isEmpty()判断指定集合的元素size是否为0
boolean remove(Object o)删除集合中的元素对象o,若集合有多个o元素,则只会删除第一个元素
boolean removeAll(Collection<?> c)删除指定集合包含集合c的元素
boolean retainAll(Collection<?> c)从指定集合中保留包含集合c的元素,其他元素则删除
int size()集合的元素个数
T[] toArray(T[] a)将集合转换为T类型的数组
  • Iterator(迭代器)

image-20230823220017023

  • Collection 接口遍历对象方式2-for 循环增强

image-20230823220031544

List

image-20230828103316173

List list = new ArrayList();
list.add("张三丰");
list.add("贾宝玉");
// void add(int index, Object ele):在index 位置插入ele 元素
//在index = 1 的位置插入一个对象
list.add(1, "韩顺平");
System.out.println("list=" + list);
// boolean addAll(int index, Collection eles):从index 位置开始将eles 中的所有元素添加进来
List list2 = new ArrayList();
list2.add("jack");
list2.add("tom");
list.addAll(1, list2);
System.out.println("list=" + list);
// Object get(int index):获取指定index 位置的元素
//说过
// int indexOf(Object obj):返回obj 在集合中首次出现的位置
System.out.println(list.indexOf("tom"));//2
// int lastIndexOf(Object obj):返回obj 在当前集合中末次出现的位置
list.add("韩顺平");
System.out.println("list=" + list);
System.out.println(list.lastIndexOf("韩顺平"));
// Object remove(int index):移除指定index 位置的元素,并返回此元素
list.remove(0);
System.out.println("list=" + list);
// Object set(int index, Object ele):设置指定index 位置的元素为ele , 相当于是替换.
list.set(1, "玛丽");
System.out.println("list=" + list);
// List subList(int fromIndex, int toIndex):返回从fromIndex 到toIndex 位置的子集合
// 注意返回的子集合fromIndex <= subList < toIndex
List returnlist = list.subList(0, 2);
System.out.println("returnlist=" + returnlist);
  • List 的三种遍历方式[ArrayList, LinkedList,Vector]

image-20230828103539165

ArrayList

image-20230828103802095

  • ArrayList 的底层操作机制源码分析(重点,难点.)

image-20230828103929882

image-20230828104715745

image-20230828104536537

Vector

image-20230828104851626

//老韩解读源码
//1. new Vector() 底层
public Vector() {
	this(10);
}
补充:如果是Vector vector = new Vector(8);
走的方法:
public Vector(int initialCapacity) {
	this(initialCapacity, 0);
}
2. vector.add(i)
2.1 //下面这个方法就添加数据到vector 集合
public synchronized boolean add(E e) {
    modCount++;
    ensureCapacityHelper(elementCount + 1);
    elementData[elementCount++] = e;
    return true;
}
2.2 //确定是否需要扩容条件: minCapacity - elementData.length>0
private void ensureCapacityHelper(int minCapacity) {
    // overflow-conscious code
    if (minCapacity - elementData.length > 0)
    grow(minCapacity);
}
2.3 //如果需要的数组大小不够用,就扩容, 扩容的算法
//newCapacity = oldCapacity + ((capacityIncrement > 0) ? capacityIncrement : oldCapacity);
//就是扩容两倍.
private void grow(int minCapacity) {
    // overflow-conscious code
    int oldCapacity = elementData.length;
    int newCapacity = oldCapacity + ((capacityIncrement > 0) ? capacityIncrement : oldCapacity);
    if (newCapacity - minCapacity < 0)
    newCapacity = minCapacity;
    if (newCapacity - MAX_ARRAY_SIZE > 0)
    newCapacity = hugeCapacity(minCapacity);
    elementData = Arrays.copyOf(elementData, newCapacity);
}

Vector 和ArrayList 的比较

image-20230828105229012

LinkedList

image-20230828105250983

  • LinkedList 的底层操作机制

image-20230828105311036

ArrayList 和LinkedList 比较

image-20230828105914632

Set

和List 接口一样, Set 接口也是Collection 的子接口,因此,常用方法和Collection 接口一样.

image-20230828110004963

HashSet

image-20230828110126495

  • HashSet 底层机制说明

image-20230828110423960

image-20230828110443196

老韩对HashSet 的源码解读
    1. 执行HashSet()
    public HashSet() {
    	map = new HashMap<>();
	}
2. 执行add()
    public boolean add(E e) {//e = "java"
    	return map.put(e, PRESENT)==null;//(static) PRESENT = new Object();
	}
3.执行put() , 该方法会执行hash(key) 得到key 对应的hash 值算法h = key.hashCode()) ^ (h >>> 16)
    public V put(K key, V value) {//key = "java" value = PRESENT 共享
    	return putVal(hash(key), key, value, false, true);
	}
4.执行putVal
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i; //定义了辅助变量
        //table 就是HashMap 的一个数组,类型是Node[]
        //if 语句表示如果当前table 是null, 或者大小=0
        //就是第一次扩容,到16 个空间.
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        //(1)根据key,得到hash 去计算该key 应该存放到table 表的哪个索引位置
        //并把这个位置的对象,赋给p
        //(2)判断p 是否为null
        //(2.1) 如果p 为null, 表示还没有存放元素, 就创建一个Node (key="java",value=PRESENT)
        //(2.2) 就放在该位置tab[i] = newNode(hash, key, value, null)
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            //一个开发技巧提示: 在需要局部变量(辅助变量)时候,在创建
            Node<K,V> e; K k; //
            //如果当前索引位置对应的链表的第一个元素和准备添加的key 的hash 值一样
            //并且满足下面两个条件之一:
            //(1) 准备加入的key 和p 指向的Node 结点的key 是同一个对象
            //(2) p 指向的Node 结点的key 的equals() 和准备加入的key 比较后相同
            //就不能加入
            if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            //再判断p 是不是一颗红黑树,
            //如果是一颗红黑树,就调用putTreeVal , 来进行添加
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {//如果table 对应索引位置,已经是一个链表, 就使用for 循环比较
                //(1) 依次和该链表的每一个元素比较后,都不相同, 则加入到该链表的最后
                // 注意在把元素添加到链表后,立即判断该链表是否已经达到8 个结点
                // , 就调用treeifyBin() 对当前这个链表进行树化(转成红黑树)
                // 注意,在转成红黑树时,要进行判断, 判断条件
                // if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY(64))
                // resize();
                // 如果上面条件成立,先table 扩容.
                // 只有上面条件不成立时,才进行转成红黑树
                //(2) 依次和该链表的每一个元素比较过程中,如果有相同情况,就直接break
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD(8) - 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;
        //size 就是我们每加入一个结点Node(k,v,h,next), size++
        if (++size > threshold)
            resize();//扩容
        afterNodeInsertion(evict);
        return null;
	}

image-20230828142452302

LinkedHashSet

image-20230828142710910

image-20230828142759693

Map

image-20230828142833241

image-20230828153154096

  • Map 接口遍历方法

image-20230828153641583

image-20230828153737770

//第一组: 先取出所有的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));
}
//第二组: 把所有的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);
}
//第三组: 通过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());
}

HashMap

image-20230828154905348

  • 底层机制及源码剖析

image-20230828155012495

image-20230828155056566

1.执行构造器new HashMap()
    初始化加载因子loadfactor = 0.75
    HashMap$Node[] table = null
2. 执行put 调用hash 方法,计算key 的hash 值(h = key.hashCode()) ^ (h >>> 16)
    public V put(K key, V value) {
        //K = "java" value = 10
        return putVal(hash(key), key, value, false, true);
    }
3. 执行putVal
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
        Node<K,V>[] tab; 
        Node<K,V> p; 
        int n, i;//辅助变量
        //如果底层的table 数组为null, 或者length =0 , 就扩容到16
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        //取出hash 值对应的table 的索引位置的Node, 如果为null, 就直接把加入的k-v
        //, 创建成一个Node ,加入该位置即可
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;//辅助变量
            // 如果table 的索引位置的key 的hash 相同和新的key 的hash 值相同,
            // 并满足(table 现有的结点的key 和准备添加的key 是同一个对象|| equals 返回真)
            // 就认为不能加入新的k-v
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            else if (p instanceof TreeNode)//如果当前的table 的已有的Node 是红黑树,就按照红黑树的方式处
                理
                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);
                        //加入后,判断当前链表的个数,是否已经到8 个,到8 个,后
                        //就调用treeifyBin 方法进行红黑树的转换
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash && //如果在循环比较过程中,发现有相同,就break,就只是替换value
                        ((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; //替换,key 对应value
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;//每增加一个Node ,就size++
        if (++size > threshold[12-24-48])//如size > 临界值,就扩容
            resize();
        afterNodeInsertion(evict);
        return null;
    }
5. 关于树化(转成红黑树)
    //如果table 为null ,或者大小还没有到64,暂时不树化,而是进行扩容.
    //否则才会真正的树化-> 剪枝
    final void treeifyBin(Node<K,V>[] tab, int hash) {
        int n, index; Node<K,V> e;
        if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
            resize();
    }

Hashtable

image-20230828161723967

Hashtable 和HashMap 对比

image-20230828161755891

Properties

image-20230828161821327

总结-开发中如何选择集合实现类

image-20230828161901265

Collections 工具类

image-20230828170347812

  • 排序操作:(均为static 方法)

image-20230828170725409

  • 查找、替换

image-20230828170828888

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值