Map的各种实现类

package com.qiaoyx.java;

import org.junit.Test;

import java.util.*;

/**
 *一,Map实现类的结构
 * Map:双列数据,存储key-value对的数据    --类似于高中讲的函数:y = f(x)
 *          HashMap:作为map的主要实现类;线程不安全,效率高;存储null的key和value
 *              LinkedHashMap:保证在遍历map元素时,可以按照添加的顺序实现遍历。
 *                      原因:在原有的hashMap底层机构的基础上,添加了一对指针,指向前一个和后一个元素。
 *                      对于频繁的遍历操作,此类执行效率要高于hashmap。
 *          TreeMap:保证按照添加的key和value进行排序,实现排序遍历。此时考虑key的自然排序或定制排序
 *          Hashtable:作为古老的实现类;线程安全,效率低;不能存储null的key和value
 *              Properties:常用来处理配置文件。key和value都是String类型
 *
 *          HashMap的底层:数组+链表    (jdk7及之前)
 *                        数组+链表+红黑树 (jdk8)
 *
 * 二:map结构的理解
 *      Map中的key:无序的,不可重复的,使用set存储所有的key   --->  key所在的类要重写hashcode和equals方法
 *      Map中的value:无需的,可重复的,使用Collection存储所有的value      ---> value所在的类要重写equals方法
 *      一个键值对:key-value构成了一个entry对象
 *      map中的entry:无序的,不可重复的,使用set存储所有的entry。
 *
 * 三,HashMap的底层实现原理
 *      HashMap map = new HashMap();
 *      在实例化以后,底层创建了长度是16的一维数组Entry[] table。
 *      ...可能已经执行过多次put...
 *      map.put(key1,value1):
 *      首先调用key1所在类的hascode()计算key1哈希值,此哈希值经过某种算法计算以后,得到在entry数组中的存放位置
 *      如果此位置上的数据为空,此时的key1-value1添加成功 ----情况一
 *      如果此位置上的数据不为空,(意味着此为这存在一个或多个数据(以链表的形式存在)),比较key1和已经存在的一个或多个数据的哈希值
 *              如果key1的哈希值与已经存在的数据哈希值都不相同,此时key1-value1添加成功。    ---情况二
 *              如果key1哈希值和已经存在的某一数据(key2-value2)的哈希值相同,继续比较:调用key1所在类的equals()方法,比较:
 *                  如果equals()返回false:此时key1-value1添加成功   ----情况三
 *                  如果equals()返回true:使用value1替换value值。
 *
 *      补充:关于情况二和情况三:此时key1-value1和原来的数据以链表的方式存储。
 *
 *      在不断添加的过程中,会涉及扩容问题,当超出临界值(且存放的位置非空)时,扩容为原来的两倍,并将原有的数据复制过来。
 *
 *      jdk8相较于jdk7在底层实现方面的不同:
 *      1.new HashMap():底层没有创建一个长度为16的Entry数组
 *      2.jdk 8底层的数组是:Node[],而非entry[]
 *      3.首次调用put()方法时,底层创建长度为16的数组
 *      4.jdk7底层结构只有:数组+链表。jdk8中底层结构:数组+链表+红黑树。
 *          当数组的某一个索引位置上的元素以链表形式存在的数据个数 > 8 且当前数组的长度 >64 时,此时此索引位置上的所有数据改为使用红黑树存储
 *
 *      Map中常用的方法
 *      增加:put(key,value)
 *      删除:remove(key)
 *      修改:put(key,value)
 *      查询:get(key)
 *      长度:size()
 *      遍历:entrySet(),keySet(),values()
 *
 * @author: qyx
 * @date: 2022-08-08 15:44
 * @desc:
 */
public class MapTest {

    //Hashtable不能放入null的key和value
    @Test
    public void test1(){
        Map map = new HashMap();
        map = new Hashtable();
//        map.put(null,null);

    }

    //LinkedHashMap按照添加的顺序遍历,遍历的效率比较高
    @Test
    public void test2(){
        Map map = new HashMap();
        map = new LinkedHashMap();
        map.put(123,"AA");
        map.put(345,"BB");
        map.put(12,"CC");
        System.out.println(map);
    }

    @Test
    public void test3(){
        Map map = new HashMap();
        //添加
        map.put("AA",123);
        map.put(45,123);
        map.put("BB",56);
        //修改
        map.put("AA",87);
        System.out.println(map);

        Map map1 = new HashMap();
        //添加
        map1.put("CC",123);
        map1.put("DD",123);
        map.putAll(map1);
        System.out.println(map);

        //remove(Object key)
        Object value = map.remove("CC");
        System.out.println(value);
        System.out.println(map);

        //clear()
        map.clear();
        System.out.println(map.size());
        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(32423453));
        //boolean containsKey(Object key)
        boolean isExist = map.containsKey("BB");
        System.out.println(isExist);
        isExist = map.containsValue(123);
        System.out.println(isExist);
        map.clear();
        System.out.println(map.isEmpty());
    }

    @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 o : values){
            System.out.println(o);
        }

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

        //方式二:
        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);

        }

    }
}


package com.qiaoyx.java;

import org.junit.Test;

import java.util.Comparator;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;

/**
 * @author: qyx
 * @date: 2022-08-09 18:12
 * @desc:
 */
public class TreeMapTest {
    //向TreeMap中添加key-value,要求key必须是由同一个类创建的对象
    //因为要按照key进行排序:自然排序,定制排序
    @Test
    public void test1(){
        TreeMap treeMap = new TreeMap();
        User u1 = new User("Tom",23);
        User u2 = new User("Jerry",32);
        User u3 = new User("Jack",20);
        User u4 = new User("Rose",18);
        treeMap.put(u1,98);
        treeMap.put(u2,89);
        treeMap.put(u3,76);
        treeMap.put(u4,100);

        Set keySet = treeMap.keySet();
        Iterator iterator = keySet.iterator();
        while (iterator.hasNext()){
            Object key = iterator.next();
            Object value = treeMap.get(key);
            System.out.println(key + "-----------" + value);
        }
    }

    @Test
    public void test2(){
        TreeMap treeMap = new TreeMap(new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                if(o1 instanceof User){
                    User user1 = (User) o1;
                    User user2 = (User) o2;
                    return Integer.compare(user1.getAge(),user2.getAge());
                }else throw new RuntimeException("类型不是User类型无法比较");
            }
        });
        User u1 = new User("Tom",23);
        User u2 = new User("Jerry",32);
        User u3 = new User("Jack",20);
        User u4 = new User("Rose",18);
        treeMap.put(u1,98);
        treeMap.put(u2,89);
        treeMap.put(u3,76);
        treeMap.put(u4,100);

        Set keySet = treeMap.keySet();
        Iterator iterator = keySet.iterator();
        while (iterator.hasNext()){
            Object key = iterator.next();
            Object value = treeMap.get(key);
            System.out.println(key + "-----------" + value);
        }
    }
}

package com.qiaoyx.java;

import java.util.Objects;

/**
 * @author: qyx
 * @date: 2022-08-04 11:52
 * @desc:
 */
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;
    }

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

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

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

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }

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

    }



}


package com.qiaoyx.java;

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

/**
 * @author: qyx
 * @date: 2022-08-09 18:39
 * @desc:
 */
public class PropertiesTest {
    //properties:常用来处理属性文件。key和value都是String类型
    public static void main(String[] args) throws Exception {
        FileInputStream fis = null;
        try {
            Properties pros = new Properties();
            fis = new FileInputStream("jdbc.properties");
            pros.load(fis);//加载流对应的文件
            String name = pros.getProperty("name");
            String password = pros.getProperty("password");
            System.out.println("name  " + name + " password   " + password);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            if(fis != null){
                try {
                    fis.close();
                } finally {

                }
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值