集合

集合

集合、数组都是对多个数据进行存储操作,简称java容器,此时的存储主要是指内存层次的存储,不涉及数据的持久化

数组:

一旦初始化就不可以改变长度

一旦定义好,就不可以改变元素类型

java集合可以分为两种体系:Colleaction和Map两种体系
Collection接口:单列数据,存储一组对象

​ List:元素有序、可重复

​ Set:元素无序、不可重复

Map:双列数据,保存具有映射关系(Key-Value)

image-20210925150121096

image-20210925150328289

Collection接口

add(Object e)将元素添加到Colleaction中

addAll(Collection e)将集合e 添加到当前集合

size()返回当前集合的大小(元素的个数)

IsEmpty()集合是否为空

clear()清空集合元素

contains(Object obj)判断当前集合中是否包含obj(基本数据类型会自动装箱为包装类,引用数据类型进行比较的时候使用的是equals方法(即没有重写equals方法的话,我们是比较的引用))

package com.geng;

import java.util.ArrayList;
import java.util.Collection;
import java.util.stream.Collector;

public class CollectionTest {


    public static void main(String[] args){
        Collection<Object> collection=new ArrayList<>();
        collection.add(new Student("geng","xiajin"));
        System.out.println(collection.contains(new Student("geng","xiajin")));//false
    }
}
class  Student{
    private String name;
    private String address;


    public Student() {
    }

    public Student(String name, String address) {
        this.name = name;
        this.address = address;
    }
    
}
package com.geng;

import java.util.ArrayList;
import java.util.Collection;
import java.util.stream.Collector;

public class CollectionTest {


    public static void main(String[] args){
        Collection<Object> collection=new ArrayList<>();
        collection.add("123");
        collection.add(new Student("geng","xiajin"));
        System.out.println(collection.contains(new Student("geng","xiajin")));
    }
}
class  Student{
    private String name;
    private String address;


    public Student() {
    }

    public Student(String name, String address) {
        this.name = name;
        this.address = address;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }


    public boolean equals(Object obj) {
        System.out.println("调用了equals方法");
        //此处一定要加上这个if条件,如果不加的话,我们知道在进行contains函数的时候,集合中的每一个元素都会当作equals的形参进行执行。
        //如果不可以当作Student实例化的对象可以直接返回false,如果不进行判断的话,他们就会在进行强制类型转换的时候报错
        if(obj instanceof Student){
            Student student=(Student)obj;
            if(student.getName()==this.name&&student.getAddress()==this.getAddress()){
                return true;
            }
            return false;
        }
        return false;
    }
}

remove(Object obj)方法,也是调用equals方法进行比较

removeAll(Collection coll)方法

package com.geng;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.stream.Collector;

public class CollectionTest {


    public static void main(String[] args){
        Collection<Object> collection=new ArrayList<>();
        collection.add("123");
        collection.add(new Student("geng","xiajin"));
        collection.add(new Student("peng","dezhou"));
        collection.add(new Student("gyp","shandong"));
        Collection collection1= Arrays.asList(new Student("peng","dezhou"),new Student("wula","wula"));
        collection.removeAll(collection1);
        collection.remove(new Student("geng","xiajin"));
        System.out.println(collection.toString());
    }
}
class  Student{
    private String name;
    private String address;


    public Student() {
    }

    public Student(String name, String address) {
        this.name = name;
        this.address = address;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", address='" + address + '\'' +
                '}';
    }

        public boolean equals(Object obj) {
        System.out.println("调用了equals方法");
        //此处一定要加上这个if条件,如果不加的话,我们知道在进行contains函数的时候,集合中的每一个元素都会当作equals的形参进行执行。
        //如果不可以当作Student实例化的对象可以直接返回false,如果不进行判断的话,他们就会在进行强制类型转换的时候报错
        if(obj instanceof Student){
            Student student=(Student)obj;
            if(student.getName()==this.name&&student.getAddress()==this.getAddress()){
                return true;
            }
            return false;
        }
        return false;
    }
}

image-20210925160333458

toArray()集合转换成数组(数组类型和Collection泛型类型一样)

List<Integer> list=Arrays.asList(12,213);

List的泛型是不可以为int的,因为集合中使用的是包装类。

数组也可以通过asList()转换成集合

iterator()返回Iterator接口的实例(可以用于遍历集合元素)
Iterator

​ Iterator对象称为迭代器(设计模式的一种),主要用于遍历集合中的元素,他主要是为了实现:提供一种方法访问一个容器对象中的各个元素,而又不暴露该对象的内部细节。

​ Collection接口继承了java.lang.Iterable接口,该接口有一个iterator()方法,在Colleaction中实现了这个接口,返回了一个Iterator对象。

​ iterator()方法每次调用都会得到一个全新的迭代器对象,默认的游标在集合的第一个元素之前。

​ 常用方法为

​ hasNext()判断指针下移后是否有元素

​ 和

​ next()先指针下移,再取出当前指针的元素

public static void main(String[] args){
   Collection collection=new ArrayList();
   collection.add("123");
   collection.add("456");
   collection.add("123");
   collection.add("456");
   Iterator iterator=collection.iterator();
   while(iterator.hasNext()){
       System.out.println(iterator.next().toString());
   }
}

常见的两种错误使用方式:

public static void main(String[] args){
   Collection collection=new ArrayList();
   collection.add("123");
   collection.add("456");
   collection.add("123");
   collection.add("456");
   //错误一
   Iterator iterator1=collection.iterator();
   while(iterator1.next()!=null){
       System.out.println(iterator1.next().toString());
   }

   //错误二
    while(collection.iterator().hasNext()){
        System.out.println(collection.iterator().next());
    }
}

迭代器的remove方法(和集合的remove方法不同)

public static void main(String[] args){
   Collection collection=new ArrayList();
   collection.add("123");
   collection.add("456");
   collection.add("123");
   collection.add("456");

   Iterator iterator=collection.iterator();
   while(iterator.hasNext()){
       String str=(String) iterator.next();
       if("123".equals(str)){
           iterator.remove();
       }
   }
   iterator=collection.iterator();
   while(iterator.hasNext()){
       System.out.println(iterator.next().toString());
   }
}

增强for循环foreach(jdk5.0新增,可以用于遍历数组、集合)

for( a: b){

}

List接口(动态数组)

​ 一般看成是数组的替代(List中元素有序并且可以重复)

​ java中List接口的实现类常用的有三个ArrayList LinkedList Vector

​ jdk1.0的时候就出现了vector。jdk1.2的时侯有了list接口,并且将vector作为了接口实现类之一

ArrayList :线程不安全,底层是使用的Object数组(查询、修改效率较高)

Vector:线程安全,底层是使用的是Object数组

LinkedList:底层是使用的是链表结构(双向链表)(频繁增删操作的话效率较高)

ArrayList源码分析:
jdk7:

​ 空参构造器默认创建一个长度为10的数组

​ add函数:

public boolean add(E e) {
    ensureCapacityInternal(size + 1);  // Increments modCount!!
    elementData[size++] = e;
    return true;
}
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;
    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);
}
jdk8:

​ 使用空参构造器的时候,是不会创建数组的的(空数组),在调用add函数的时候会执行以此判断

private static int calculateCapacity(Object[] elementData, int minCapacity) {
    if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
        return Math.max(DEFAULT_CAPACITY, minCapacity);
    }
    return minCapacity;
}

​ 类似于懒汉式和饿汉式的区别(单例模式样例)

LinkedList源码分析

Node内部类数组

private static class Node<E> {
    E item;
    Node<E> next;
    Node<E> prev;

    Node(Node<E> prev, E element, Node<E> next) {
        this.item = element;
        this.next = next;
        this.prev = prev;
    }
}

两个类似于指针的属性:头指针和尾指针------------双向链表

transient Node<E> first;
transient Node<E> last;
Vector

在jdk7 和jdk8中都是使用了饿汉式空参的构造方法,在扩容方面默认扩容为原来的2倍(ArrayList扩容为1.5倍)

常用方法:

image-20211001104841197

所以在list接口中,就容易出现一些重写方法的问题(关于参数是否自动装箱)

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

public class ListTest {
    @Test
    public void test01(){
        List list=new ArrayList();
        list.add(1);
        list.add(2);
        list.add(3);
 /*       updateList1(list);
        System.out.println(list);//1 2*/
  /*      updateList2(list);
        System.out.println(list);//1  3*/
    }

    private static void updateList1(List list){
        list.remove(2);
    }

    private static void updateList2(List list){
        list.remove(new Integer(2));
    }
}

Set接口 无序不可重复

set接口中没有额外添加的方法,都是collection中的方法

HashSet:线程不安全、可以存储null值

LinkedHashSet:HashSet的子类使用链表结构,可以按照添加顺序进行遍历

TreeSet:可以按照添加对象的指定属性进行排序

无序性:按照数据的hash值进行存储(hash值决定存储位置)

不可重复性:hash值用来判断两个元素是否是相同的(可以通过equals和hashCode方法进行改变重复性的规则)

HashSet中使用add添加元素的过程

image-20211001143416703

我们向HashSet中添加元素a,首先会调用他的hashCode方法,计算a的哈希值,此哈希值接着通过某种算法九三出他在HashSet底层数组中的存放位置(索引位置),判断这个位置上是否有元素值,如果为null,则直接进行添加,如果存在一个元素(或者是链表)则比较元素a和元素b的hash值,如果hash值不同·,则直接进行添加,如果相同在通过equals方法进行比较。

此时注意如果是在jdk7中我们是将新增加的元素放在链表的头部,jdk8中是放在尾部。(七上八下)

Object中的hashCode方法是随机值。我们在这里对hashCode进行重写的唯一规则就是如果他们两个是相同(值相同)的我们必须将他们的hashCode结果一样,如果是不同的就随意可以一样也可以不一样。

31这个数为什么经常当作系数:

1、我们选择系数的时候要选择尽量大的数,因为系数越大,你的基数之间的差别就会被放大的越大。

2、31只占5bit,造成溢出的概率比较小。

3、31可以由i*31==(i<<5)-1来表示。

4、31是一个素数,素数作用是:如果我用一个数和素数相乘,那么只会多出一个因子出来,这样也可以减少冲突

import org.junit.Test;

import java.util.*;

public class ListTest {
    @Test
    public void test01(){
        Set<MyStudent> students=new HashSet<MyStudent>();
        students.add(new MyStudent(12,"geng"));
        students.add(new MyStudent(12,"geng"));
        students.add(new MyStudent(13,"geng"));
        students.add(new MyStudent(13,"geng"));
        students.add(new MyStudent(14,"geng"));
        students.add(new MyStudent(14,"geng"));
        Iterator iterator=students.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }

}
class MyStudent{
    private int age;
    private String name;

    public MyStudent(int age, String name) {
        this.age = age;
        this.name = name;
    }

    public MyStudent() {
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        //if (o == null || getClass() != o.getClass()) return false;
        if(!(o instanceof MyStudent)) return false;
        MyStudent myStudent = (MyStudent) o;
        return age == myStudent.age &&
                Objects.equals(name, myStudent.name);
    }

    @Override
    public int hashCode() {
        int result=name!=null?name.hashCode():0;
        result=31*result+age;
        return result;
    }


    @Override
    public String toString() {
        return "MyStudent{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

LinkedHashSet

image-20211001151415662

在原有hashSet的基础上又提供了一对双向链表,保证顺序(此处的顺序不是有序性)

TreeSet(由于我们TreeSet可以实现排序功能,所以要求元素应该是同一个类的对象)

TreeSet不是通过hashCode和equals方法进行判断,而是通过compareTo方法(如果compareTo方法返回结果为0,则两个元素相同)

import org.junit.Test;

import java.util.*;

public class ListTest {
    @Test
    public void test01(){
        Set<MyStudent> students=new TreeSet<MyStudent>();
        students.add(new MyStudent(12,"geng"));
        students.add(new MyStudent(12,"peng"));
        students.add(new MyStudent(13,"geng"));
        students.add(new MyStudent(13,"seng"));
        students.add(new MyStudent(14,"geng"));
        students.add(new MyStudent(14,"qeng"));
        Iterator iterator=students.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }

}
class MyStudent implements Comparable{
    private int age;
    private String name;

    public MyStudent(int age, String name) {
        this.age = age;
        this.name = name;
    }

    public MyStudent() {
    }

    @Override
    public int compareTo(Object o) {
        if(o instanceof  MyStudent){
            MyStudent myStudent=(MyStudent)o;
            int result=this.getName().compareTo(myStudent.getName());
            if(result==0){
                return this.getAge()-myStudent.getAge();
            }
            return result;
        }
        else{
            throw new RuntimeException("类型不同");
        }
    }

    @Override
    public String toString() {
        return "MyStudent{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

也可以通过Comparator方法进行排序,创建一个Comparator对象,将他作为TreeSet构造器中的参数。

import org.junit.Test;

import java.util.*;

public class ListTest {
    @Test
    public void test01(){
        Comparator comparator=new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                if(o1 instanceof MyStudent&&o2 instanceof MyStudent){
                    MyStudent myStudent1=(MyStudent)o1;
                    MyStudent myStudent2=(MyStudent)o2;
                    return -myStudent1.compareTo(myStudent2);
                }
                else{
                    throw new RuntimeException("类型不同");
                }
            }
        };
        Set<MyStudent> students=new TreeSet<MyStudent>(comparator);
        students.add(new MyStudent(12,"geng"));
        students.add(new MyStudent(12,"peng"));
        students.add(new MyStudent(13,"geng"));
        students.add(new MyStudent(13,"seng"));
        students.add(new MyStudent(14,"geng"));
        students.add(new MyStudent(14,"qeng"));
        Iterator iterator=students.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }

}
class MyStudent implements Comparable{
    private int age;
    private String name;

    public MyStudent(int age, String name) {
        this.age = age;
        this.name = name;
    }

    public MyStudent() {
    }

    @Override
    public int compareTo(Object o) {
        if(o instanceof  MyStudent){
            MyStudent myStudent=(MyStudent)o;
            int result=this.getName().compareTo(myStudent.getName());
            if(result==0){
                return this.getAge()-myStudent.getAge();
            }
            return result;
        }
        else{
            throw new RuntimeException("类型不同");
        }
    }

    @Override
    public String toString() {
        return "MyStudent{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

一道很经典的题目:

import org.junit.Test;

import java.util.HashSet;
import java.util.Set;

public class MySetTest {
    @Test
    public void test01(){
        Set<OurStudent> students=new HashSet<>();
        OurStudent ourStudent1=new OurStudent(12,"aa");
        OurStudent ourStudent2=new OurStudent(14,"bb");
        students.add(ourStudent1);
        students.add(ourStudent2);
        System.out.println(students);
        ourStudent1.setName("cc");
        students.remove(ourStudent1);
        //此处remove的时候,计算这个ourStudent1的hashCode,因为name已经改了,所以大概率无法到达相同的索引,所以大概率无法删除
        System.out.println(students);
        students.add(new OurStudent(14,"cc"));
        //此处添加的时候,也是同样的道理,两个“相同”的元素大概率不在同一个索引上,所以大概率可以添加成功
        System.out.println(students);
    }
}

class OurStudent{
    private int age;
    private String name;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public OurStudent(int age, String name) {
        this.age = age;
        this.name = name;
    }

    public OurStudent() {
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if(!(o instanceof OurStudent))return false;

        OurStudent that = (OurStudent) o;

        if (age != that.age) return false;
        return name != null ? name.equals(that.name) : that.name == null;
    }

    @Override
    public int hashCode() {
        int result = age;
        result = 31 * result + (name != null ? name.hashCode() : 0);
        return result;
    }

    @Override
    public String toString() {
        return "OurStudent{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
}

image-20211001160136101

Map接口

image-20211001160233564

Hashtable:jdk1.0时出现,jdk1.2的时候成为Map接口的实现类,线程安全,不可以存储null的key和value

LinkedHashMap:jdk1.2的时候出现,HashMap的子类

HashMap:jdk1.2时出现,线程不安全,可以存储null的key和value

SortedMap:jdk1.2时出现

Properties:key和value都是String类型,是Hashtable的子类

HashMap在jdk7中的源码分析

底层创建了一个Entry[] table数组。长度为16

其实key就是一个集合。。。。。。。。。。。。原理差不多。

1、在hashMap中,我们是根据一个内部静态方法获取hashcode

static final int hash(Object key) {
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
HashMap在jdk8中的源码分析

底层没有创建Entry[] table数组,使用Node[] table,首次进行put的时候,底层会创建长度为十六的Node[] 。底层结构中使用了红黑树(当数组中某个索引位置上的元素以链表的形式存在的个数超过了8,并且当前数组长度大于64的时候,此索引位置处所有的数据使用红黑树进行存储,以便提高搜索速度)。

空参构造器:

public HashMap() {
    this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
static final float DEFAULT_LOAD_FACTOR = 0.75f;

Node内部类:

static class Node<K,V> implements Map.Entry<K,V> {
    final int hash;
    final K key;
    V value;
    Node<K,V> next;

    Node(int hash, K key, V value, Node<K,V> next) {
        this.hash = hash;
        this.key = key;
        this.value = value;
        this.next = next;
    }

其实本质还是一个Entry

put方法:

public V put(K key, V value) {
    return putVal(hash(key), key, value, false, true);
}
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;
}
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;
}

红黑树中的put

final TreeNode<K,V> putTreeVal(HashMap<K,V> map, Node<K,V>[] tab,
                               int h, K k, V v) {
    Class<?> kc = null;
    boolean searched = false;
    TreeNode<K,V> root = (parent != null) ? root() : this;
    for (TreeNode<K,V> p = root;;) {
        int dir, ph; K pk;
        if ((ph = p.hash) > h)
            dir = -1;
        else if (ph < h)
            dir = 1;
        else if ((pk = p.key) == k || (k != null && k.equals(pk)))
            return p;
        else if ((kc == null &&
                  (kc = comparableClassFor(k)) == null) ||
                 (dir = compareComparables(kc, k, pk)) == 0) {
            if (!searched) {
                TreeNode<K,V> q, ch;
                searched = true;
                if (((ch = p.left) != null &&
                     (q = ch.find(h, k, kc)) != null) ||
                    ((ch = p.right) != null &&
                     (q = ch.find(h, k, kc)) != null))
                    return q;
            }
            dir = tieBreakOrder(k, pk);
        }

        TreeNode<K,V> xp = p;
        if ((p = (dir <= 0) ? p.left : p.right) == null) {
            Node<K,V> xpn = xp.next;
            TreeNode<K,V> x = map.newTreeNode(h, k, v, xpn);
            if (dir <= 0)
                xp.left = x;
            else
                xp.right = x;
            xp.next = x;
            x.parent = x.prev = xp;
            if (xpn != null)
                ((TreeNode<K,V>)xpn).prev = x;
            moveRootToFront(tab, balanceInsertion(root, x));
            return null;
        }
    }
}

DEFAULT_INITIAL_CAPACITY:HashMap默认容量是16

DEFAULT_LOAD_FACTOR:HashMap的默认加载因子 0.75

threadhold:扩容的临界值 = 容量*加载因子

TREEIFY_THRESHOLD:Bucket中链表长度大于该默认值,转换成为红黑树 8

MIN_TREEIFY_CAPACITY:桶中的Node被树化时最小的hash表容量64

Map接口中定义的方法

image-20211001172005580

clear只清除数据!!!!!!!!!!!!

import org.junit.Test;

import java.util.*;

public class MapTest {

    @Test
    public void test(){
        Map<Object,Object> map=new HashMap<>();
        map.put("123",1234);
        map.put("gyp",666);
        map.put(123,"12455");

        //获取所有的key
        Set<Object> set=map.keySet();
        Iterator iterator1=set.iterator();
        while(iterator1.hasNext()){
            System.out.println(iterator1.next());
        }

        //获取所有的value
        Collection<Object> list=map.values();
        Iterator iterator2=list.iterator();
        while(iterator2.hasNext()){
            System.out.println(iterator2.next());
        }

        //获取key-value对
        Set<Map.Entry<Object, Object>> entries = map.entrySet();
        Iterator iterator3=entries.iterator();
        while(iterator3.hasNext()){
            Map.Entry entry=(Map.Entry)iterator3.next();
            System.out.println(entry.getKey()+"       "+entry.getValue());
        }

    }
}
TreeMap 参考TreeSet即可
Properties一般用于处理属性文件

将配置文件中读取到内存中。

import org.junit.Test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

public class PropertiesTest {
    @Test
    public void test01() throws IOException {
        Properties properties=new Properties();
        FileInputStream fileInputStream=new FileInputStream("lala.properties");
        properties.load(fileInputStream);
        System.out.println(properties.getProperty("name"));
        System.out.println(properties.get("password"));
        System.out.println(properties.getProperty("age"));
    }
    fileInputStream.close();
}
Collections工具类

image-20211001190759214

image-20211001190823382

image-20211001190846201

posted on 2021-10-09 19:47  gyp666  阅读(61)  评论(0)    收藏  举报