• 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));
        }
    }
  • 相关阅读:
    年年岁岁花相似,岁岁年年竟相同
    两情相悦,亦或情投意合
    FreeBSD学习笔记1
    MySQL学习笔记2
    门户网站镜像站以及CDN技术
    候车
    MySQL学习笔记1
    JDBC | 第一章: 快速开始使用JDBC连接Mysql数据库之简单CRUD
    JDBC | 第零章: 什么是JDBC?
    JDBC | 第二章: JDBC之批量更新,添加,和删除操作
  • 原文地址:https://www.cnblogs.com/hujingwei/p/5322821.html
Copyright © 2020-2023  润新知