zoukankan      html  css  js  c++  java
  • Map中自定义Key

    在使用Map集合的时候可以发现对于Key和Value的类型实际上都可以由使用者定义,这就意味着可以用自定义的类来进行Key类型的设置。
    对自定义Key类型所在的类中,一定要覆写hashCode()和equals()方法。
    package com.iterator.demo;
    
    import java.util.HashMap;
    import java.util.Map;
    
    class Person{
        private String name;
        private int age;
        public Person(String name, int age) {
            this.name = name;
            this.age = age;
        }
        @Override
        public int hashCode() {//覆写hashCode()
            final int prime = 31;
            int result = 1;
            result = prime * result + age;
            result = prime * result + ((name == null) ? 0 : name.hashCode());
            return result;
        }
        @Override
        public boolean equals(Object obj) {//覆写equals()
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            Person other = (Person) obj;
            if (age != other.age)
                return false;
            if (name == null) {
                if (other.name != null)
                    return false;
            } else if (!name.equals(other.name))
                return false;
            return true;
        }
    }
    
    public class IteratorDemo {
        public static void main(String[] args) {
            Map<Person, String> map = new HashMap<Person, String>();//使用自定义类作为Key
            map.put(new Person("张三",18), "张三疯");
            map.put(new Person("李四",18), "李四光");
            map.put(new Person("王五",18), "王五哥");
            System.out.println(map.get(new Person("张三", 18)));//通过key找到value
        }
    }
  • 相关阅读:
    字符串通配
    最短排序
    最长回文子串
    添加回文串
    找零钱
    最优编辑
    01背包
    PHP做分页查询(查询结果也显示为分页)
    PHP 练习3:租房子
    Html5学习3(拖放、Video(视频)、Input类型(color、datetime、email、month 、number 、range 、search、Tel、time、url、week ))
  • 原文地址:https://www.cnblogs.com/sunzhongyu008/p/11233487.html
Copyright © 2011-2022 走看看