zoukankan      html  css  js  c++  java
  • java中hashCode()方法的作用

           hashcode方法返回该对象的哈希码值。
          hashCode()方法可以用来来提高Map里面的搜索效率的,Map会根据不同的hashCode()来放在不同的位置,Map在搜索一个对象的时候先通过hashCode()找到相应的位置,然后再根据equals()方法判断这个位置上的对象与当前要插入的对象是不是同一个。
    所以,Java对于eqauls方法和hashCode方法是这样规定的:
       *如果两个对象相同,那么它们的hashCode值一定要相同;
       *如果两个对象的hashCode相同,它们并不一定相同。

    如下代码:

    package demos;
    
    import java.util.HashSet;
    import java.util.Set;
    
    /**
     * Created by hu on 2016/3/26.
     */
    public class Student {
        private String name;
        private Integer age;
        public Student(String name, Integer age) {
            this.name = name;
            this.age = age;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getName() {
            return name;
        }
    
        public Integer getAge() {
            return age;
        }
    
        public void setAge(Integer age) {
            this.age = age;
        }
    
        public String toString() {
            return name + "'s age is " + String.valueOf(age);
        }
    
        public boolean equals(Object other) {
            if(this == other)
                return true;
            if(other == null)
                return false;
            if(!(other instanceof Student))
                return false;
    
            final Student stu = (Student)other;
            if(!getName().equals(stu.getName()))
                return false;
            if(!getAge().equals(stu.getAge()))
                return false;
            return true;
        }
    
        public int hashCode() {
            int result = getName().hashCode();
            result = 29*result + getAge().hashCode();
            return result;
        }
    
        public static void main(String[] args){
            Set<Student> set = new HashSet<Student>();
            Student s1 = new Student("ZhangSan", 13);
            Student s2 = new Student("ZhangSan", 13);
            System.out.println(s1.hashCode());
            System.out.println(s2.hashCode());
            set.add(s1);
            set.add(s2);
            System.out.println(set);
            System.out.println(s1.equals(s2));
        }
    }
  • 相关阅读:
    将打开的网页以html格式下载到本地
    Shiro自定义realm实现密码验证及登录、密码加密注册、修改密码的验证
    JS或jsp获取Session中保存的值
    HTML添加上传图片并进行预览
    springMVC多图片压缩上传的实现
    DropZone图片上传控件的使用
    Wireshark安装使用及报文分析
    Spring—Document root element "beans", must match DOCTYPE root "null"分析及解决方法
    web.xml中如何设置配置文件的加载路径
    正则表达式的认识
  • 原文地址:https://www.cnblogs.com/hujingwei/p/5322821.html
Copyright © 2011-2022 走看看