Java-Ch 11:集合

目录

1.集合框架概述(默认都用集合) *Collection接口

1.1 Collection接口的方法

1.1.1 增删判 以ArrayList为例

1.1.2 需要*重写equals的接口方法:子集、差集、交集、判等、集合数组转换

1.2 *List接口,三种容器的相同点和不同点

1.2.1 List接口的方法

1.2.2 面试题

1.3 Set

1.3.1 Set接口的框架(hashCode查找效率高)

1.3.2 HashSet & LinkedHashSet *添加过程 考题

*底层分析题——hashCode是属性的函数

1.3.3 TreeSet 涉及compareTo的综合运用(自然、定制)

1.3.4 TreeSet 课后练习1

1.3.5 课后练习2——如何用泛型?

1.3.6 去List内的重复数据

2 Map 接口

2.1 概念理解

2.1.1 Map框架图&实现类之间的异同(习题)

练习题2个

2.2 Map结构的理解

 2.3 HashMap底层

 2.3.1 hashmap 源码分析

2.3.2 Linkedhashmap 源码分析

2.2 Map 常用方法

2.3 TreeMap 涉及排序


1.集合框架概述(默认都用集合) *Collection接口

/**
 * 一、集合框架的概述
 *
 * 1.集合、数组都是对多个数据进行存储操作的结构,简称Java容器。
 *  说明:此时的存储,主要指的是内存层面的存储,不涉及到持久化的存储(.txt,.jpg,.avi,数据库中)


 *
 * 二、集合框架
 *      |----Collection接口:单列集合,用来存储一个一个的对象
 *          |----List接口:存储有序的(equals)、可重复的数据。  -->“动态”数组(toArray)
 *              |----ArrayList、LinkedList、Vector
 *
 *          |----Set接口:存储无序的不可重复的数据   -->高中讲的“集合”
 *              |----HashSet、LinkedHashSet、TreeSet
 *
 *      |----Map接口:双列集合,用来存储一对(key - value)一对的数据   -->高中函数:y = f(x)
 *              |----HashMap、LinkedHashMap、TreeMap、Hashtable、Properties
 

长度元素类型操作效率方法有限
集合Collection初始化时不指定长度,可以不断增加元素可以不同方法多
数组Array初始化时确定,不可修改

定义好,元素类型确定 String[] arr

有序,可重复

添加、删除、插入数据的操作效率不高。涉及移动位置O(n)无法获取数组中实际元素的个数



 */ 

1.1 Collection接口的方法

1.1.1 增删判 以ArrayList为例

增add addall

查size isEmpty

删clear

package com.lee.java2;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;

/**
 * @author Lee
 * @create 2021-09-02 18:54
 */
public class CollectionTest {

    @Test
    public void test1(){
        Collection coll = new ArrayList();

        //add(Object):元素e添加到集合coll中
        coll.add("AA");
        coll.add("BB");
        coll.add("CC");
        coll.add("DD");
        coll.add(12345);
        coll.add(new Date());

        //size():获取添加的元素的个数
        System.out.println(coll.size());//6

        //addAll(Collection coll1):将coll1集合中的元素添加到当前的集合中
        Collection coll1 = new ArrayList();
        coll1.add(456);
        coll1.add("CC");
        coll.addAll(coll1);
        System.out.println(coll.size());
        System.out.println(coll);

        //clear():清空集合元素
        coll.clear();

        //isEmpty():判断当前集合是否为空
        System.out.println(coll.isEmpty());//元素没有,不是空指针

    }
}

1.1.2 需要*重写equals的接口方法:子集、差集、交集、判等、集合数组转换

 * 结论:
 * 向Collection接口的实现类的对象中添加数据obj时,要求obj所在类要重写equals().

Person.class

package lee.java;

import java.util.Objects;

/**
 * @author Lee
 * @create 2021-09-04 9:55
 */
public class Person {
    private String name;
    private int age;

    public Person() {
    }

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

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

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

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

    @Override
    public boolean equals(Object o) {
//        System.out.println("Person类的equals");
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return age == person.age && Objects.equals(name, person.name);
    }


}
package lee.java;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

/**
 * @author Lee
 * @create 2021-09-04 9:50
 */
public class CollectionTest {
    @Test
    public void test1(){
        Collection coll = new ArrayList();//可以重复,有序
        //添加
        coll.add(123);
        coll.add(456);
        coll.add(new String("Tom"));
        coll.add(false);
        coll.add(456);
        coll.add(new Person("李瑾",29));
        coll.add(new Person("Mike",23));
        Person p = new Person("Jerry",20);
        coll.add(p);

        //1.contains(Object obj):判断当前集合中是否包含obj
        //我们在判断时会调用obj对象所在类的equals()。
        boolean contains = coll.contains(123);
        System.out.println(contains);
        System.out.println(coll.contains(new String("Tom")));//true 两个对象,判断的内容
        System.out.println(coll.contains(new Person("Mike",23)));//没重写equals,调用Object.==,false ——> true
        System.out.println(coll.contains(new Person("Mike",22)));//false
        System.out.println(coll.contains(p));//true //不管重写与否都是true

        //2.containsAll(Collection coll1):判断形参coll1中的所有元素是否都存在于当前集合中。
        Collection coll1 = Arrays.asList(123,456);//list是collection的子接口 多态
        System.out.println(coll.containsAll(coll1));
    }

    //求差集
    @Test
    public void test2(){
        //3.remove
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(456);
        coll.add(new String("Tom"));
        coll.add(false);
        coll.add(456);
        coll.add(new Person("李瑾",29));
        coll.add(false);

        coll.remove(123);//调用equals
        System.out.println(coll);

        coll.remove(new Person("李瑾",29));//重写了equals 可以移除
        System.out.println(coll);

        //4.removeall 求差集
        Collection coll1 = Arrays.asList(456,"Tom",789);//会将两个456都移除调
        coll.removeAll(coll1);
        System.out.println(coll);


    }

    //求交集
    @Test
    public void test3(){
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(456);
        coll.add(new String("Tom"));
        coll.add(false);
        coll.add(456);
        coll.add(new Person("李瑾",29));
        coll.add(false);


        //5.retain 求交集
        Collection coll1 = Arrays.asList(123,456,789);
        coll.retainAll(coll1);
        System.out.println(coll);//修改当前结合——交集 [123, 456, 456]

        //6.equals
        Collection coll2 = new ArrayList();
//        coll2.addAll(123,456,456);
        coll2.add(123);
        coll2.add(456);
        coll2.add(456);
        System.out.println(coll2.equals(coll));//true 依次调用equals 有序

    }

    //
    @Test
    public void test4(){
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(456);
        coll.add(new String("Tom"));
        coll.add(false);
        coll.add(456);
        coll.add(new Person("李瑾",29));
        coll.add(false);

        //7.hashCode(): 返回当前对象的hash值
        System.out.println(coll.hashCode());//-1609751794

        //8.集合——>数组 toArray
        Object[] arr = coll.toArray();
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }

        //拓展:数组——>集合:调用Arrays类的静态方法asList()
        List<String> list = Arrays.asList(new String[]{"AA", "CC"});
        System.out.println(list);

        List arr1 = Arrays.asList(new int[]{123, 456});
        System.out.println(arr1);//[[I@504bae78]
        System.out.println(arr1.size());//1

        List arr2 = Arrays.asList(123,456);
        System.out.println(arr2);//[123,456]
        System.out.println(arr2.size());//2

        List arr3 = Arrays.asList(new Integer[]{123, 456});
        System.out.println(arr3.size());//2
    }
}

含 contains containsAll

差 remove removeAll

交 retainAll

hashCode

转 toArray

iterator

package lee.java;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

/**
 * 集合元素的遍历操作,使用迭代器Iterator接口
 * 1.内部的方法:hasNext() 和  next()
 * 2.集合对象每次调用iterator()方法都得到一个全新的迭代器对象,
 * 默认游标都在集合的第一个元素之前。
 * 3.内部定义了remove(),可以在遍历的时候,删除集合中的元素。此方法不同于集合直接调用remove()
 *
 * @author Lee
 * @create 2021-09-05 17:23
 */
public class IteratorTest {
    @Test
    public void test1(){
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(456);
        coll.add(new Person("Jerry",20));
        coll.add(new String("Tom"));
        coll.add(false);

        Iterator iterator = coll.iterator();

        //方式一:一个一个单独输出
//        System.out.println(iterator.next());
//        System.out.println(iterator.next());
//        System.out.println(iterator.next());
//        System.out.println(iterator.next());
//        System.out.println(iterator.next());
//        System.out.println(iterator.next());//报错

        //方式二:
        while (iterator.hasNext()){
            //next():①指针下移 ②将下移以后集合位置上的元素返回
            System.out.println(iterator.next());
        }
    }
    @Test
    public void test2(){
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(456);
        coll.add(new Person("Jerry",20));
        coll.add(new String("Tom"));
        coll.add(false);

        //删除集合中的“Tom”
        Iterator iterator = coll.iterator();
        while (iterator.hasNext()){
            Object obj = iterator.next();
            if (obj.equals("Tom")){
                iterator.remove();
            }
        }

        iterator = coll.iterator();
        while (iterator.hasNext()){//迭代器只能调用一次,上一次循环以后迭代器已空
//            System.out.println("进入循环");
            System.out.println(iterator.next());
        }

    }
}

1.2 *List接口,三种容器的相同点和不同点

方法?

增:在指定位置插入元素 or 所有元素

查:查指定位置元素 or 查指定元素位置(首次、莫次) or 返回一段位置的索引值

删:移除指定位置元素 

改:设置指定位置元素

 * 1. List接口框架
 *
 *    |----Collection接口:单列集合,用来存储一个一个的对象
 *          |----List接口:存储有序的、可重复的数据。  -->“动态”数组,替换原有的数组
 *              |----ArrayList:作为List接口的主要实现类;线程不安全的,效率高;底层使用Object[] elementData存储
 *              |----LinkedList:对于频繁的插入、删除操作,使用此类效率比ArrayList高;底层使用双向链表存储
 *              |----Vector:作为List接口的古老实现类;线程安全的,效率低;底层使用Object[] elementData存储
 *
 *
 *   2. ArrayList的源码分析:
 *   2.1 jdk 7情况下
 *      ArrayList list = new ArrayList();//底层创建了长度是10的Object[]数组elementData
 *      list.add(123);//elementData[0] = new Integer(123);自动装箱
 *      ...
 *      list.add(11);//如果此次的添加导致底层elementData数组容量不够,则扩容。
 *      默认情况下,扩容为原来的容量的1.5倍,同时需要将原有数组中的数据复制到新的数组中。
 *
 *      结论:建议开发中使用带参的构造器:ArrayList list = new ArrayList(int capacity),通过调整参数调整数组大小
 *
 *   2.2 jdk 8中ArrayList的变化:
 *      ArrayList list = new ArrayList();//底层Object[] elementData初始化为{}.并没有创建长度为10的数组
 *
 *      list.add(123);//第一次调用add()时,底层才创建了长度10的数组,并将数据123添加到elementData[0]
 *      ...
 *      后续的添加和扩容操作与jdk 7 无异。
 *   2.3 小结:jdk7中的ArrayList的对象的创建类似于单例的饿汉式,而jdk8中的ArrayList的对象
 *            的创建类似于单例的懒汉式,延迟了数组的创建,节省内存。

 *
 *  3. LinkedList的源码分析:
 *      LinkedList list = new LinkedList(); 内部声明了Node类型的first和last属性,默认值为null
 *      list.add(123);//将123封装到Node中,创建了Node对象。
 *
 *      其中,Node定义为:体现了LinkedList的双向链表的说法
 *      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;
             }
         }
 *
 *   4. Vector的源码分析:jdk7和jdk8中通过Vector()构造器创建对象时,底层都创建了长度为10的数组。
 *      在扩容方面,默认扩容为原来的数组长度的2倍。
 *
 *  面试题:ArrayList、LinkedList、Vector三者的异同?
 *  同:三个类都是实现了List接口,存储数据的特点相同:存储有序的、可重复的数据
 *  不同:见上
 *
 *
 *
 *   5. List接口中的常用方法

实现方式效率        扩容查找插入、删除
VectorObject[] elementData线程安全,效率低2
ArrayListObject[] elementData线程不安全,效率高1.5O(1) 第 i 位O(1)
LinkedList

双向链表

Person的属性指向Person

O(n)O(1)

1.2.1 List接口的方法

what?

一个变成数组

what is the difference?

 what is Arrays.asList()?

返回值是一个固定长度的 List 集合

package lee.java;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

/**
 * @author Lee
 * @create 2021-09-05 22:12
 */
public class ListTest {
    
    @Test
    public void test3(){
        ArrayList list = new ArrayList();
        list.add(123);
        list.add(456);
        list.add("AA");

        //方式一:Iterator迭代器方式
        Iterator iterator = list.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
        System.out.println();

        //方式二:增强for循环
        for (Object obj : list) {
            System.out.println(obj);
        }

        System.out.println();

        //方式三:普通for循环
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }

    }
    
    @Test
    public void test2(){
        ArrayList list = new ArrayList();
        list.add(123);
        list.add(456);
        list.add("AA");
        list.add(new Person("Tom",12));
        list.add(456);
        //int indexOf(Object obj):返回obj在集合中首次出现的位置。如果不存在,返回-1.
        int index = list.indexOf(4567);
        System.out.println(index);//-1

        //int lastIndexOf(Object obj):返回obj在当前集合中末次出现的位置。如果不存在,返回-1.
        int index1 = list.lastIndexOf(123);
        System.out.println(index1);//0

        int index2 = list.lastIndexOf(456);
        System.out.println(index2);//4

        //Object remove(int index):移除指定index位置的元素,并返回此元素
        Object obj = list.remove(0);
        System.out.println(obj);//123
        System.out.println(list);//[456, AA, Person{name='Tom', age=12}, 456]

        //Object set(int index, Object ele):设置指定index位置的元素为ele
        list.set(1,"CC");
        System.out.println(list);//[456, CC, Person{name='Tom', age=12}, 456]

        //List subList(int fromIndex, int toIndex):返回从fromIndex到toIndex位置的左闭右开区间的子集合
        List subList = list.subList(2,4);
        System.out.println(subList);//[Person{name='Tom', age=12}, 456]

        System.out.println(list);//[456, CC, Person{name='Tom', age=12}, 456]

    }
    @Test
    public void test1(){
        ArrayList list = new ArrayList();
        list.add(123);
        list.add(456);
        list.add("AA");
        list.add(new Person("Tom",12));
        list.add(456);

        System.out.println(list);//[123, 456, AA, Person{name='Tom', age=12}, 456]

        //void add(int index, Object ele):在index位置插入ele元素
        list.add(1,"BB");
        System.out.println(list);

        //boolean addAll(int index, Collection eles):从index位置开始将eles中的所有元素添加进来
        Object[] array;
        List list1 = Arrays.asList(1, 2, 3);
//        list.addAll(list1);
//        System.out.println(list.size());
//        System.out.println(list);//默认拼接到最后 [123, BB, 456, AA, Person{name='Tom', age=12}, 456, 1, 2, 3]

        list.addAll(2,list1);//[123, BB, 1, 2, 3, 456, AA, Person{name='Tom', age=12}, 456]
        System.out.println(list);

        //Object get(int index):获取指定index位置的元素
        System.out.println(list.get(0));//123
    }
}

1.2.2 面试题

package lee.exer;

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

/**
 * @author Lee
 * @create 2021-09-06 10:33
 */
public class testListRemove {
    public static void main(String[] args) {
        List list = new ArrayList();
        list.add(1);
        list.add(2);
        list.add(3);
        updateList(list);
        System.out.println(list);
    }
    private static void updateList(List list) {
        list.remove(2);//按照索引值删除,不自动装箱
        list.remove(new Integer(2));//自己进行装箱,删除指定元素
    }
}

1.3 Set

1.3.1 Set接口的框架(hashCode查找效率高)
 


 * |----Collection接口:单列集合,用来存储一个一个的对象
 *          |----Set接口:存储无序的、不可重复的数据   -->高中讲的“集合”
 *              |----HashSet:作为Set接口的主要实现类;线程不安全的;可以存储null值
 *                  |----LinkedHashSet:作为HashSet的子类;遍历其内部数据时,可以按照添加的顺序遍历
 *                                      对于频繁的遍历操作,LinkedHashSet效率高于HashSet.
 *              |----TreeSet:可以按照添加对象的指定属性,进行排序。
 *
 *
 *  1. Set接口中没有额外定义新的方法,使用的都是Collection中声明过的方法
 *
 *  2. 要求:向Set(主要指:HashSet、LinkedHashSet)中添加的数据,其所在的类一定要重写hashCode()和equals()
 *      要求:重写的hashCode()和equals()尽可能保持一致性:相等的对象必须具有相等的散列码
 *      重写两个方法的小技巧:对象中用作 equals() 方法比较的 Field,都应该用来计算 hashCode 值。

 

    @Override
    public int hashCode() {
        //String的hashCode重写过,如果都是“Tom”,则hashCode一样
        //我们希望属性值一样hashCode也一样
        int result = name != null ? name.hashCode() : 0;
        result = 31 * result + age;
        return result;
    }

 为什么选31?

1.3.2 HashSet & LinkedHashSet *添加过程 考题

    /*
    一、Set:存储无序的、不可重复的数据
    以HashSet为例说明:
    1. 无序性:不等于随机性(每次都是一种顺序)。存储的数据在底层数组中并非按照数组索引的顺序添加,而是根据数据的哈希值决定的。

    2. 不可重复性:保证添加的元素按照equals()判断时,不能返回true.即:相同的元素只能添加一个。

    二、添加元素的过程:以HashSet为例:
        我们向HashSet中添加元素a,首先调用元素a所在类的hashCode()方法,计算元素a的哈希值
        此哈希值接着通过某种算法计算出(%)在HashSet底层数组中的存放位置(即为:索引位置),判断
        数组此位置上是否已经有元素:
            如果此位置上没有其他元素,则元素a添加成功。 --->情况1
            如果此位置上有其他元素b(或以链表形式存在的多个元素),则比较元素a与元素b的hash值:
                如果hash值不相同,则元素a添加成功。--->情况2
                如果hash值相同,进而需要调用元素a所在类的equals()方法:
                       equals()返回true,元素a添加失败
                       equals()返回false,则元素a添加成功。--->情况2

        对于添加成功的情况2和情况3而言:元素a 与已经存在指定索引位置上数据以链表的方式存储。
        jdk 7 :元素a放到数组中,指向原来的元素。
        jdk 8 :原来的元素在数组中,指向元素a
        总结:七上八下(新的在上 or 新的在下)

        HashSet底层:数组+链表的结构。

     */

    @Test
    public void test1(){
        Set set = new HashSet();//底层数组长度是16
        set.add(456);
        set.add(123);
        set.add(123);
        set.add("AA");
        set.add("CC");
        set.add(new user("Tom",12));
        set.add(new user("Tom",12));//两个不重复,没有重写equals会显示两个。重写后
        set.add(129);

        Iterator iterator = set.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }

   

package Practise;

import java.util.Collection;
import java.util.HashSet;

/**
 * @author Lee
 * @create 2021-09-09 11:01
 */
public class SetTest2 {
    public static void main(String[] args) {
        Collection set = new HashSet();//底层数组长度是16
//        set.add(new Person("Tom",12));
//        set.add(new Person("Tom",12));//两个不重复,没有重写equals会显示两个。重写后只显示一个

        Person p1 = new Person("L",11);
        Person p2 = new Person("X",12);
        set.add(p1);
        set.add(p2);
        System.out.println(set);
        //[Person{name='L', age=11}, Person{name='X', age=12}]

        p1.name = "K";
        set.remove(p1);
        System.out.println(set);
        //不重写equals则成功删去——hashCode是地址的函数
        //重写则
        //[Person{name='X', age=12}, Person{name='K', age=11}]

        set.add(new Person("V",23));
        System.out.println(set);
        //[Person{name='V', age=23}, Person{name='X', age=12}, Person{name='K', age=11}]

        set.add(new Person("L",11));
        System.out.println(set);
        //[Person{name='V', age=23}, Person{name='X', age=12}, Person{name='K', age=11}, Person{name='L', age=11}]
    }
}

//LinkedHashSet的使用
    //LinkedHashSet作为HashSet的子类,在添加数据的同时,每个数据还维护了两个引用,记录此数据前一个
    //数据和后一个数据。
    //优点:对于频繁的遍历操作,LinkedHashSet效率高于HashSet

why?

    @Test
    public void test2(){
        Set set = new LinkedHashSet();
        set.add(456);
        set.add(123);
        set.add(123);
        set.add("AA");
        set.add("CC");
        set.add(new User("Tom",12));
        set.add(new User("Tom",12));
        set.add(129);

        Iterator iterator = set.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }

*底层分析题——hashCode是属性的函数

p1 和 p2 根据hash值计算得到的索引存储在数组里面

p1的name改变后,hash值变了(类似查找),结果找到了别的位置

package Practise;

import java.util.Collection;
import java.util.HashSet;

/**
 * @author Lee
 * @create 2021-09-09 11:01
 */
public class SetTest2 {
    public static void main(String[] args) {
        Collection set = new HashSet();//底层数组长度是16
//        set.add(new Person("Tom",12));
//        set.add(new Person("Tom",12));//两个不重复,没有重写equals会显示两个。重写后只显示一个

        Person p1 = new Person("L",11);
        Person p2 = new Person("X",12);
        set.add(p1);
        set.add(p2);
        System.out.println(set);
        //[Person{name='L', age=11}, Person{name='X', age=12}]

        p1.name = "K";
        set.remove(p1);
        System.out.println(set);
        //不重写equals则成功删去——hashCode是地址的函数
        //重写则
        //[Person{name='X', age=12}, Person{name='K', age=11}]

        set.add(new Person("V",23));
        System.out.println(set);
        //[Person{name='V', age=23}, Person{name='X', age=12}, Person{name='K', age=11}]

        set.add(new Person("L",11));
        System.out.println(set);

    }
}

1.3.3 TreeSet 涉及compareTo的综合运用(自然、定制)

    /*
    1.向TreeSet中添加的数据,要求是相同类的对象。
    2.两种排序方式:自然排序(实现Comparable接口) 和 定制排序(Comparator)
    3.自然排序中,比较两个对象是否相同的标准为:compareTo()返回0.不再是equals().
    4.定制排序中,比较两个对象是否相同的标准为:compare()返回0.不再是equals().
     */

package lee.java1;

import org.junit.Test;

import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;

/**
 * @author Lee
 * @create 2021-09-06 13:58
 */
public class TreeSetTest {
    @Test
    public void test(){
        TreeSet set = new TreeSet();
        //必须相同类别
//        set.add(123);
//        set.add(456);
//        set.add("AA");
//        set.add(new User("Tom",12));

//        举例一:
//        set.add(34);
//        set.add(-34);
//        set.add(43);
//        set.add(11);
//        set.add(8);

        //举例二:
        //对自定义的类无法排序,怎么办?
        set.add(new User("Tom",12));
        set.add(new User("Jerry",32));
        set.add(new User("Jim",2));
        set.add(new User("Mike",65));
        set.add(new User("Jack",33));
        set.add(new User("Jack",56));//如果排序方法只比较姓名,无法显示第二个Jack

        //输出的结果必然是从小到大的
        Iterator iterator = set.iterator();
        while (iterator.hasNext()){
            System.out.print(iterator.next() + " ");//-34 8 11 34 43
        }
    }
    
    @Test
    public void test2() {
        Comparator com = new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                if (o1 instanceof User && o2 instanceof User) {
                    User u1 = (User) o1;
                    User u2 = (User) o2;
                    return Integer.compare(u1.getAge(), u2.getAge());
                } else {
                    throw new RuntimeException("输入数据的类型不匹配");
                }
            }
        };
        TreeSet set = new TreeSet(com);//按照com的标准进行排序:年龄从小到大
        set.add(new User("Tom", 12));
        set.add(new User("Jerry", 32));
        set.add(new User("Jim", 2));
        set.add(new User("Mike", 65));
        set.add(new User("Jack", 33));//先来后到,有Jack没Mary
        set.add(new User("Mary", 33));
        set.add(new User("Jack", 56));

        Iterator iterator = set.iterator();
        while (iterator.hasNext()) {
            System.out.print(iterator.next() + " ");
        }
    }
}

package lee.java1;

/**
 * @author Lee
 * @create 2021-09-06 13:59
 */
public class User implements Comparable {
    private String name;
    private int age;

    public User() {
    }

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

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

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

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        User user = (User) o;

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

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

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

    //按照姓名从小到大排序
    //String定义过CompareTo
    @Override
    public int compareTo(Object o) {
        if (o instanceof User){
            User user = (User)o;
//            return this.getName().compareTo(user.getName());
            int compare = -this.getName().compareTo(user.getName());//从大到小
            if (compare != 0){
                return compare;
            }else{
                return Integer.compare(this.age,user.age);//默认从小到大
            }
        }else{
            throw new RuntimeException("输入的类型不匹配!");
        }
    }
}

1.3.4 TreeSet 课后练习1

package lee.exer1;

import org.junit.Test;

import java.util.Iterator;
import java.util.TreeSet;

/**
 * @author Lee
 * @create 2021-09-09 9:21
 */
public class EmployeeTest {
    //1 自然排序
    @Test
    public void test1(){
        TreeSet set = new TreeSet();
        Employee e1 = new Employee("Lu",55,new MyDate(1967,1,1));
        Employee e2 = new Employee("Xiu",40,new MyDate(1968,1,1));
        Employee e3 = new Employee("Miu",30,new MyDate(1969,1,1));
        Employee e4 = new Employee("Tiu",20,new MyDate(1961,1,1));
        Employee e5 = new Employee("Ziu",10,new MyDate(1962,1,1));

        set.add(e1);
        set.add(e2);
        set.add(e3);
        set.add(e4);
        set.add(e5);

        //元素放在树的左边还是右边?利用compare判断
        //Employee实现comparable

        Iterator iterator = set.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
            
        //结果
//        Employee{name='Lu', age=55, birthday=MyDate{year=1967, month=1, day=1}}
//        Employee{name='Miu', age=30, birthday=MyDate{year=1969, month=1, day=1}}
//        Employee{name='Tiu', age=20, birthday=MyDate{year=1961, month=1, day=1}}
//        Employee{name='Xiu', age=40, birthday=MyDate{year=1968, month=1, day=1}}
//        Employee{name='Ziu', age=10, birthday=MyDate{year=1962, month=1, day=1}}
        }
    }
}

MyDate

package lee.exer1;

/**
 * @author Lee
 * @create 2021-09-09 9:14
 */
public class MyDate {
    private int year;
    private int month;
    private int day;

    public MyDate() {
    }

    public MyDate(int year, int month, int day) {
        this.year = year;
        this.month = month;
        this.day = day;
    }

    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }

    public int getMonth() {
        return month;
    }

    public void setMonth(int month) {
        this.month = month;
    }

    public int getDay() {
        return day;
    }

    public void setDay(int day) {
        this.day = day;
    }

    @Override
    public String toString() {
        return "MyDate{" +
                "year=" + year +
                ", month=" + month +
                ", day=" + day +
                '}';
    }
}

Employee 重写compareTo

package lee.exer1;

/**
 * @author Lee
 * @create 2021-09-09 9:16
 */
public class Employee implements Comparable{
    private String name;
    private int age;
    private MyDate birthday;

    public Employee() {
    }

    public Employee(String name, int age, MyDate birthday) {
        this.name = name;
        this.age = age;
        this.birthday = birthday;
    }

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

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

    public MyDate getBirthday() {
        return birthday;
    }

    public void setBirthday(MyDate birthday) {
        this.birthday = birthday;
    }

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

    //按照姓名排序
    @Override
    public int compareTo(Object o) {
        if (o instanceof Employee) {
            Employee e = (Employee) o;
            return this.name.compareTo(e.name);//默认从小到大。什么是树的从小到大?
        }
//        return 0;
        throw new RuntimeException("传入的数据类型不一致");
    }

}

1.3.5 课后练习2——如何用泛型?

比较年月日 涉及三种方法

    @Test
    public void test2(){
        TreeSet set = new TreeSet(new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                if (o1 instanceof Employee && o2 instanceof Employee) {
                    Employee e1 = (Employee) o1;
                    Employee e2 = (Employee) o2;

                    MyDate d1 = e1.getBirthday();
                    MyDate d2 = e2.getBirthday();
                    //方法1
//                    if (d1.getYear() == d2.getYear()){
//                        if (d1.getMonth() == d2.getMonth()){
//                            if (d1.getDay() == d2.getDay()){
//                                return 0;
//                            }
//                            else {
//                                if (d1.getDay() > d2.getDay()){
//                                    return 1;
//                                }else{
//                                    return -1;
//                                }
//
//                            }
//                        }else{
//                            if (d1.getMonth() > d2.getMonth()){
//                                return 1;
//                            }else{
//                                return -1;
//                            }
//                        }
//                    }else{
//                        if (d1.getYear() > d2.getYear()){
//                            return 1;
//                        }else{
//                            return -1;
//                        }
//                    }
//                方法2 也可以在MyDate里面实现CompareTo
//                    int minusYear = d1.getYear() - d2.getYear();//前-后 默认从小到大
//                    if (minusYear != 0) {
//                        return minusYear;
//                    }
//
//                    int minusMonth = d1.getMonth() - d2.getMonth();
//                    if (minusMonth != 0) {
//                        return minusMonth;
//                    }
//
//                    return d1.getDay() - d2.getDay();

//                方式3
                return d1.compareTo(d2);
                }
            throw new RuntimeException("数据格式不对");}
        });

        Employee e1 = new Employee("Lu",55,new MyDate(1967,1,1));
        Employee e2 = new Employee("Xiu",40,new MyDate(1967,2,1));
        Employee e3 = new Employee("Miu",30,new MyDate(1967,1,3));
        Employee e4 = new Employee("Tiu",20,new MyDate(1961,1,1));
        Employee e5 = new Employee("Ziu",10,new MyDate(1962,1,1));

        set.add(e1);
        set.add(e2);
        set.add(e3);
        set.add(e4);
        set.add(e5);

        Iterator iterator = set.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }
package lee.exer1;

/**
 * @author Lee
 * @create 2021-09-09 9:14
 */
public class MyDate implements Comparable{
    private int year;
    private int month;
    private int day;

    public MyDate() {
    }

    public MyDate(int year, int month, int day) {
        this.year = year;
        this.month = month;
        this.day = day;
    }

    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }

    public int getMonth() {
        return month;
    }

    public void setMonth(int month) {
        this.month = month;
    }

    public int getDay() {
        return day;
    }

    public void setDay(int day) {
        this.day = day;
    }

    @Override
    public String toString() {
        return "MyDate{" +
                "year=" + year +
                ", month=" + month +
                ", day=" + day +
                '}';
    }

    @Override
    public int compareTo(Object o) {
        if (o instanceof MyDate){
            MyDate m = (MyDate) o;
            int minusYear = this.getYear() - m.getYear();//前-后 默认从小到大
            if (minusYear != 0) {
                return minusYear;
            }

            int minusMonth = this.getMonth() - m.getMonth();
            if (minusMonth != 0) {
                return minusMonth;
            }

            return this.getDay() - m.getDay();
        }
        throw new RuntimeException("数据格式不匹配!");
    }
}

1.3.6 去List内的重复数据

package Practise;

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

/**
 * @author Lee
 * @create 2021-09-09 10:51
 */
public class SetTest1 {
    public static void main(String[] args) {
        List list = new ArrayList();
        list.add(new Integer(1));
        list.add(new Integer(1));
        list.add(new Integer(2));
        list.add(new Integer(3));
        list.add(new Integer(4));
        List list1 = duplicateList(list);
        for (Object integer : list1){
            System.out.println(integer);
        }
    }

    public static List duplicateList(List list){
        HashSet set = new HashSet();

        //将list的数据全部添加到set
        set.addAll(list);
        return new ArrayList(set);
    }
}

2 Map 接口

2.1 概念理解

2.1.1 Map框架图&实现类之间的异同(习题)

安全性元素功能
1 Hashtable线程安全的,效率低不能存储null的key和value
1- 1 Propertieskey和value都是String类型常用来处理配置文件
2 HashMap线程不安全的,效率高存储null的key和value底层
2-1 LinkedHashMap在原有的HashMap底层结构基础上,添加了一对指针,指向前一个和后一个元素

1 可以按照添加顺序遍历

2 对于频繁的遍历操作,此类执行效率高于HashMap

数组+链表  (jdk7及之前)

数组+链表+红黑树 (jdk 8)

3 TreeMap排序二叉树——红黑树

按照添加的key-value对进行排序,实现排序遍历

此时考虑key的自然排序或定制排序

练习题2个

 *  1. HashMap的底层实现原理?


 *  2. HashMap 和 Hashtable的异同?

Hashtable最古老,安全性高,效率低,不能存储null键值对

HashMap在此基础上改进,效率高,安全性低,安全性利用Collections工具类实现,可以存储null键值对

两者都是Map的实现类
 *  3. CurrentHashMap 与 Hashtable的异同?(暂时不讲)

2.2 Map结构的理解

 *    Map中的key:无序的、不可重复的,使用Set存储所有的key  ---> key所在的类要重写equals()和hashCode() (以HashMap为例)
 *    Map中的value:无序的、可重复的,使用Collection存储所有的value --->value所在的类要重写equals()
 *    一个键值对:key-value构成了一个Entry对象。
 *    Map中的entry:无序的、不可重复的,使用Set存储所有的entry

 2.3 HashMap底层

 1      HashMap map = new HashMap():
 *      在实例化以后,底层创建了长度是16的一维数组Entry[] table。
 *      ...可能已经执行过多次put...

2       map.put(key1,value1):
 *      首先,调用key1所在类的hashCode()计算key1哈希值,此哈希值经过某种算法计算以后,得到在Entry数组中的存放位置
 *      如果此位置上的数据为空,此时的key1-value1添加成功。 ----情况1
 *      如果此位置上的数据不为空,(意味着此位置上存在一个或多个数据(以链表形式存在)),比较key1和已经存在的一个或多个数据
 *      的哈希值:
 *              如果key1的哈希值与已经存在的数据的哈希值都不相同,此时key1-value1添加成功。----情况2
 *              如果key1的哈希值和已经存在的某一个数据(key2-value2)的哈希值相同,继续比较:调用key1所在类的equals(key2)方法,比较:
 *                      如果equals()返回false:此时key1-value1添加成功。----情况3
 *                      如果equals()返回true:使用value1替换value2
 *
 *       补充:关于情况2和情况3:此时key1-value1和原来的数据以链表的方式存储。
 *
 *      在不断的添加过程中,会涉及到扩容问题,当超出临界值(且要存放的位置非空)时,扩容。默认的扩容方式:扩容为原来容量的2倍,并将原有的数据复制过来。
 *
 *      jdk8 相较于jdk7在底层实现方面的不同:
 *      1. new HashMap():底层没有创建一个长度为16的数组
 *      2. jdk 8底层的数组是:Node[],而非Entry[]
 *      3. 首次调用put()方法时,底层创建长度为16的数组
 *      4. jdk7底层结构只有:数组+链表。jdk8中底层结构:数组+链表+红黑树。
 *         4.1 形成链表时,七上八下(jdk7:新的元素指向旧的元素。jdk8:旧的元素指向新的元素)
           4.2 当数组的某一个索引位置上的元素以链表形式存在的数据个数 > 8 且当前数组的长度 > 64时,此时此索引位置上的所数据改为使用红黑树存储。O(n)——>logn


 *
 *      DEFAULT_INITIAL_CAPACITY : HashMap的默认容量,16
 *      DEFAULT_LOAD_FACTOR:HashMap的默认加载因子:0.75
 *      threshold:扩容的临界值,=容量*填充因子:16 * 0.75 => 12
 *      TREEIFY_THRESHOLD:Bucket中链表长度大于该默认值,转化为红黑树:8
 *      MIN_TREEIFY_CAPACITY:桶中的Node被树化时最小的hash表容量:64

 2.3.1 hashmap 源码分析

//1 构造器 
//加载因子为0.75
//并没有创建长度为16的数组

/**
 * Constructs an empty <tt>HashMap</tt> with the default initial capacity
 * (16) and the default load factor (0.75).
 */
public HashMap() {
    this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
//2 存储单元是 Node
    /**
     * The table, initialized on first use, and resized as
     * necessary. When allocated, length is always a power of two.
     * (We also tolerate length zero in some operations to allow
     * bootstrapping mechanics that are currently not needed.)
     */
    transient Node<K,V>[] table;

3 放入数据


    /**
     * Associates the specified value with the specified key in this map.
     * If the map previously contained a mapping for the key, the old
     * value is replaced.
     *
     * @param key key with which the specified value is to be associated
     * @param value value to be associated with the specified key
     * @return the previous value associated with <tt>key</tt>, or
     *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
     *         (A <tt>null</tt> return can also indicate that the map
     *         previously associated <tt>null</tt> with <tt>key</tt>.)
     */
    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

 3.1 需要利用hash()计算哈希值


    /**
     * Computes key.hashCode() and spreads (XORs) higher bits of hash
     * to lower.  Because the table uses power-of-two masking, sets of
     * hashes that vary only in bits above the current mask will
     * always collide. (Among known examples are sets of Float keys
     * holding consecutive whole numbers in small tables.)  So we
     * apply a transform that spreads the impact of higher bits
     * downward. There is a tradeoff between speed, utility, and
     * quality of bit-spreading. Because many common sets of hashes
     * are already reasonably distributed (so don't benefit from
     * spreading), and because we use trees to handle large sets of
     * collisions in bins, we just XOR some shifted bits in the
     * cheapest possible way to reduce systematic lossage, as well as
     * to incorporate impact of the highest bits that would otherwise
     * never be used in index calculations because of table bounds.
     */
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

3.2 put方法具体


    /**
     * Implements Map.put and related methods
     *
     * @param hash hash for key
     * @param key the key
     * @param value the value to put
     * @param onlyIfAbsent if true, don't change existing value
     * @param evict if false, the table is in creation mode.
     * @return previous value, or null if none
     */
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        /*
            首次调用,table没有初始化,是null,则tab == null
            利用resize()扩容,即造数组,现用现造。
        */
        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)//查看当前存keyvalue的位置是否为空
            tab[i] = newNode(hash, key, value, null);
        else {//存在值 p是现有的Node
            Node<K,V> e; K k;
            //先判断 p和待传入元素的hash是否相等
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;//如果hash相等,key也相等,先将p存放在e里面,不直接替换
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            //p只是链表里的第一个元素,虽然和要添加的元素相等,还要继续和之后的数据比较
            else {
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {//只有一个p,七上八下添加新元素
                        p.next = newNode(hash, key, value, null);//新造一个元素作为p的next
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);//链表长度>8重新整合为tree
                        break;
                    }

                    //比较p.next和d
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;//之前的都不是,则p=p.next继续循环
                }
            }
            //将旧的数据替换为新的
            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;
    }

3.3 调用resize()


    /**
     * Initializes or doubles table size.  If null, allocates in
     * accord with initial capacity target held in field threshold.
     * Otherwise, because we are using power-of-two expansion, the
     * elements from each bin must either stay at same index, or move
     * with a power of two offset in the new table.
     *
     * @return the table
     */
    final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        int oldCap = (oldTab == null) ? 0 : oldTab.length;//table初始是null 赋值0
        int oldThr = threshold;//临界值初始 = 0
        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;//赋值16
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);//0.75*16
        }
        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];//创建数组,长度16
        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;
    }

3.4 调用treeifyBin

    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)//后者是64
            resize();//只是扩容
        else if ((e = tab[index = (n - 1) & hash]) != null) {
            TreeNode<K,V> hd = null, tl = null;
            do {
                TreeNode<K,V> 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);
        }
    }

2.3.2 Linkedhashmap 源码分析

能够记录添加元素的先后顺序

putVal 继承于父类HashMap

重写newNode

    Node<K,V> newNode(int hash, K key, V value, Node<K,V> e) {
        LinkedHashMap.Entry<K,V> p =
            new LinkedHashMap.Entry<K,V>(hash, key, value, e);
        linkNodeLast(p);
        return p;
    }

继承了Node 同时多了before 和 after


    /**
     * HashMap.Node subclass for normal LinkedHashMap entries.
     */
    static class Entry<K,V> extends HashMap.Node<K,V> {
        Entry<K,V> before, after;
        Entry(int hash, K key, V value, Node<K,V> next) {
            super(hash, key, value, next);
        }
    }

2.2 Map 常用方法


 添加、删除、修改操作:
 Object put(Object key,Object value):将指定key-value添加到(或修改)当前map对象中
 void putAll(Map m):将m中的所有key-value对存放到当前map中
 Object remove(Object key):移除指定key的key-value对,并返回value
 void clear():清空当前map中的所有数据


 元素查询的操作:
 Object get(Object key):获取指定key对应的value
 boolean containsKey(Object key):是否包含指定的key
 boolean containsValue(Object value):是否包含指定的value
 int size():返回map中key-value对的个数
 boolean isEmpty():判断当前map是否为空
 boolean equals(Object obj):判断当前map和参数对象obj是否相等


 元视图操作的方法:
 Set keySet():返回所有key构成的Set集合
 Collection values():返回所有value构成的Collection集合
 Set entrySet():返回所有key-value对构成的Set集合

 *总结:常用方法:
 * 添加:put(Object key,Object value)
 * 删除:remove(Object key)
 * 修改:put(Object key,Object value)
 * 查询:get(Object key)
 * 长度:size()
 * 遍历:keySet() / values() / entrySet()
 */

    @Test
    public void test3(){

        Map map = new HashMap();
        map.put(123,"a");
        map.put(32,"b");
        map.put("ccc",9);//添加
        map.put("ccc",2);//添加
        map.put("ccc",1);//修改
        System.out.println(map);//{32=b, ccc=1, 123=a}

        //——————————————————————
        Map map1 = new HashMap();
        map1.put("CC",123);
        map1.put("DD",123);
        System.out.println(map1);//{CC=123, DD=123}

        map.putAll(map1);
        System.out.println(map);//{32=b, CC=123, DD=123, ccc=1, 123=a}

        //remove(Object key)
        Object value = map.remove("CC");
        System.out.println(value);//123
        System.out.println(map);//{32=b, DD=123, ccc=1, 123=a}

        //clear()
        map.clear();//与map = null操作不同
        System.out.println(map.size());//0
        System.out.println(map);//{}


    }
    @Test
    public void test4(){
        Map map = new HashMap();
        map.put("AA",123);
        map.put(45,123);
        map.put("BB",56);
        // Object get(Object key)
        System.out.println(map.get(45));//123

        //containsKey(Object key)
        boolean isExist = map.containsKey("BB");
        System.out.println(isExist);//true

        isExist = map.containsValue(123);
        System.out.println(isExist);//true

        map.clear();//new的对象还在
        System.out.println(map.isEmpty());//true
    }
    @Test
    public void test5(){
        Map map = new HashMap();
        map.put("AA",123);
        map.put(45,1234);
        map.put("BB",56);

        //遍历所有的key集:keySet()
        Set set = map.keySet();
        Iterator iterator = set.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
        System.out.println();

        //遍历所有的value集:values()
        Collection values = map.values();
        for (Object obj : values){
            System.out.println(obj);
        }
        System.out.println();

        //遍历所有的key-value
        //方式一:entrySet()
        Set entrySet = map.entrySet();//键值对
        Iterator iterator1 = entrySet.iterator();
        while (iterator1.hasNext()){
            Object obj = iterator1.next();
            //entrySet集合中的元素都是entry
            Map.Entry entry = (Map.Entry) obj;
            System.out.println(entry.getKey() + "---->" + entry.getValue());
        }
        System.out.println();

        //方式二
        Set keySet = map.keySet();
        Iterator iterator2 = keySet.iterator();
        while (iterator2.hasNext()){
            Object key = iterator2.next();
            Object value = map.get(key);
            System.out.println(key + "=====" + value);
        }
    }

2.3 TreeMap 涉及排序

package Java;

import org.junit.Test;

import java.util.*;

/**
 * @author Lee
 * @create 2021-09-10 20:20
 */
public class TreeMapTest {
    //向TreeMap中添加key-value,要求key必须是由同一个类创建的对象
    //因为要按照key进行排序:自然排序 、定制排序
    //自然排序
    @Test
    public void test1(){
        TreeMap map = new TreeMap();
        User u1 = new User("Jerry",12);
        User u2 = new User("Jerry",32);
        User u3 = new User("Jack",20);
        User u4 = new User("Rose",18);

        map.put(u1,98);
        map.put(u2,89);
        map.put(u3,76);
        map.put(u4,100);

        Set entrySet = map.entrySet();
        Iterator iterator1 = entrySet.iterator();
        while (iterator1.hasNext()){
            Object obj = iterator1.next();
            Map.Entry entry = (Map.Entry) obj;
            System.out.println(entry.getKey() + "---->" + entry.getValue());
        }
    }

    @Test
    public void test2(){
        //年龄从小到大
        TreeMap map = new TreeMap(new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                if (o1 instanceof User && o2 instanceof User){
                    User u1 = (User) o1;
                    User u2 = (User) o2;
                    return Integer.compare(u1.getAge(),u2.getAge());
                }
                throw new RuntimeException("输入的类型不匹配");
            }
        });

        User u1 = new User("Jerry",12);
        User u2 = new User("Jerry",32);
        User u3 = new User("Jack",20);
        User u4 = new User("Rose",18);

        map.put(u1,98);
        map.put(u2,89);
        map.put(u3,76);
        map.put(u4,100);

        Set entrySet = map.entrySet();
        Iterator iterator1 = entrySet.iterator();
        while (iterator1.hasNext()){
            Object obj = iterator1.next();
            Map.Entry entry = (Map.Entry) obj;
            System.out.println(entry.getKey() + "---->" + entry.getValue());
        }
    }
}

2.4 Properties(HashTable)

 记得打勾

  

package Java;

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

/**
 * @author Lee
 * @create 2021-09-11 20:47
 */
public class PropertiesTest {
    public static void main(String[] args){
        FileInputStream fis = null;
        try {
            //1.生成对象
            Properties pros = new Properties();
            //2.导入配置文件(Resource Bundle)
            fis = new FileInputStream("jdbc.properties");
            //3.加载
            pros.load(fis);//加载流对应的文件
            //4.利用pros所拥有的方法去取key对应的value
            String name = pros.getProperty("name");
            String password = pros.getProperty("password1");
            System.out.println("name = " + name + ", password = " + password);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null){
                try {
                    fis.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }
    }
}

3 Collections 工具类

package Java;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @author Lee
 * @create 2021-09-11 21:05
 */
public class CollectionsTest {
    /*
reverse(List):反转 List 中元素的顺序
shuffle(List):对 List 集合元素进行随机排序
sort(List):根据元素的自然顺序对指定 List 集合元素按升序排序
sort(List,Comparator):根据指定的 Comparator 产生的顺序对 List 集合元素进行排序
swap(List,int, int):将指定 list 集合中的 i 处元素和 j 处元素进行交换

Object max(Collection):根据元素的自然顺序,返回给定集合中的最大元素
Object max(Collection,Comparator):根据 Comparator 指定的顺序,返回给定集合中的最大元素
Object min(Collection)
Object min(Collection,Comparator)
int frequency(Collection,Object):返回指定集合中指定元素的出现次数
void copy(List dest,List src):将src中的内容复制到dest中
boolean replaceAll(List list,Object oldVal,Object newVal):使用新值替换 List 对象的所有旧值

 */
    @Test
    public void test2(){
        List list = new ArrayList();
        list.add(123);
        list.add(43);
        list.add(765);
        list.add(-97);
        list.add(0);

        //报异常:IndexOutOfBoundsException("Source does not fit in dest")
//        List dest = new ArrayList();
//        Collections.copy(dest, list);
//        System.out.println(dest);
        List dest = Arrays.asList(new Object[list.size()]);//数组转list
        System.out.println(dest.size());//5

                /*
        Collections 类中提供了多个 synchronizedXxx() 方法,
        该方法可使将指定集合包装成线程同步的集合,从而可以解决
        多线程并发访问集合时的线程安全问题

         */
        //返回的list1即为线程安全的List
        List list1 = Collections.synchronizedList(list);

    }
    @Test
    public void test1(){
        List list = new ArrayList();
        list.add(123);
        list.add(43);
        list.add(765);
        list.add(765);
        list.add(765);
        list.add(-97);
        list.add(0);

        System.out.println(list);//[123, 43, 765, 765, 765, -97, 0]


//        Collections.reverse(list);//[0, -97, 765, 765, 765, 43, 123]
//        Collections.shuffle(list);//[123, 0, 765, 43, 765, 765, -97]
//        Collections.sort(list);//[-97, 0, 43, 123, 765, 765, 765] 从小到大 自然排序
//        Collections.swap(list,1,2);//[123, 765, 43, 765, 765, -97, 0]
//        System.out.println(list);

        int fre = Collections.frequency(list,765);
        System.out.println(fre);//3

        //2.




    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值