zoukankan      html  css  js  c++  java
  • Java——HashMap使用Demo

    package map;
    
    import java.util.Collection;
    import java.util.HashMap;
    import java.util.Set;
    
    public class HashMapDemo {
    
        public static void main(String[] args) {
            HashMap<String, String> map = new HashMap<String, String>();
            // 键不能重复,值可以重复
            map.put("san", "张三");
            map.put("si", "李四");
            map.put("wu", "王五");
            map.put("wang", "老王");
            map.put("wang", "老王2");// 老王被覆盖
            map.put("lao", "老王");
            System.out.println("-------直接输出hashmap:-------");
            System.out.println(map);
            /**
             * 遍历HashMap
             */
            // 1.获取Map中的所有键
            System.out.println("-------foreach获取Map中所有的键:------");
            Set<String> keys = map.keySet();
            for (String key : keys) {
                System.out.print(key+"  ");
            }
            System.out.println();//换行
            // 2.获取Map中所有值
            System.out.println("-------foreach获取Map中所有的值:------");
            Collection<String> values = map.values();
            for (String value : values) {
                System.out.print(value+"  ");
            }
            System.out.println();//换行
            // 3.得到key的值的同时得到key所对应的值
            System.out.println("-------得到key的值的同时得到key所对应的值:-------");
            Set<String> keys2 = map.keySet();
            for (String key : keys2) {
                System.out.print(key + ":" + map.get(key)+"   ");
    
            }
            /**
             * 另外一种不常用的遍历方式
             */
            // 当我调用put(key,value)方法的时候,首先会把key和value封装到
            // Entry这个静态内部类对象中,把Entry对象再添加到数组中,所以我们想获取
            // map中的所有键值对,我们只要获取数组中的所有Entry对象,接下来
            // 调用Entry对象中的getKey()和getValue()方法就能获取键值对了
            Set<java.util.Map.Entry<String, String>> entrys = map.entrySet();
            for (java.util.Map.Entry<String, String> entry : entrys) {
                System.out.println(entry.getKey() + "--" + entry.getValue());
            }
    
            /**
             * HashMap其他常用方法
             */
            System.out.println("after map.size():"+map.size());
            System.out.println("after map.isEmpty():"+map.isEmpty());
            System.out.println(map.remove("san"));
            System.out.println("after map.remove():"+map);
            System.out.println("after map.get(si):"+map.get("si"));
            System.out.println("after map.containsKey(si):"+map.containsKey("si"));
            System.out.println("after containsValue(李四):"+map.containsValue("李四"));
            System.out.println(map.replace("si", "李四2"));
            System.out.println("after map.replace(si, 李四2):"+map);
        }
    
    }

     引用型Key重写equals和hashcode方法:

    public class Book{
        
        private String name;
        private double price;
        private String author;
        
        /**
         * 原则:
         * 1、和属性值相关
         * 2、属性一样的话,要求哈希值肯定一样
         *    属性不一样的,尽最大的限度让哈希值不一样!
         */
    
    //    // 简单方式    
    //    @Override
    //    public int hashCode() {
    //        return name.hashCode()+(int)price+author.hashCode()*31;
    //    }
        
    //    @Override
    //    public boolean equals(Object obj) {
    //        System.out.println(this.name+" pk "+((Book)obj).name);
    //        
    //        if(this==obj)
    //            return true;
    //        if(!(obj instanceof Book))
    //            return false;
    //        Book b = (Book) obj;
    //        
    //        return this.name.equals(b.name)&&this.price==b.price&&this.author.equals(b.author);
    //    }
        public String getName() {
            return name;
        }
        
        // 推荐的重写
        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + ((author == null) ? 0 : author.hashCode());
            result = prime * result + ((name == null) ? 0 : name.hashCode());
            long temp;
            temp = Double.doubleToLongBits(price);
            result = prime * result + (int) (temp ^ (temp >>> 32));
            return result;
        }
        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            Book other = (Book) obj;
            if (author == null) {
                if (other.author != null)
                    return false;
            } else if (!author.equals(other.author))
                return false;
            if (name == null) {
                if (other.name != null)
                    return false;
            } else if (!name.equals(other.name))
                return false;
            if (Double.doubleToLongBits(price) != Double.doubleToLongBits(other.price))
                return false;
            return true;
        }
        public void setName(String name) {
            this.name = name;
        }
        public double getPrice() {
            return price;
        }
        public void setPrice(double price) {
            this.price = price;
        }
        public String getAuthor() {
            return author;
        }
        public void setAuthor(String author) {
            this.author = author;
        }
        public Book(String name, double price, String author) {
            super();
            this.name = name;
            this.price = price;
            this.author = author;
        }
        
        public String toString(){
            /*
             * %s:字符串
             * %c:字符
             * %f:浮点
             * %d:整数
             */
            return String.format("名称:%s    价格:%.2f    作者:%s",name,price,author);
        }
    }

    参考:https://snailclimb.top/JavaGuide/#/java/collection/HashMap

  • 相关阅读:
    github打开慢,甚至打不开
    在使用confluent-kafka-go 时遇到如下问题
    Istio Routing极简教程
    kubelet证书过期解决方法
    工具类docker for k8s
    selenium jar包 的下载地址,各版本都有
    使用TestNG进行多浏览器,跨浏览器和并行测试
    简单聊聊TestNG中的并发
    清除Git仓库多余文件及其历史记录 
    【MAVEN】maven系列--pom.xml标签详解
  • 原文地址:https://www.cnblogs.com/MWCloud/p/11332098.html
Copyright © 2011-2022 走看看