zoukankan      html  css  js  c++  java
  • ==和equals()

    1、==:基本数据类型(int a = 1; String s = “hello”;)比较的是值,引用数据类型(Integer c = new Integer(2); String str = new String(“world”);)比较的是内存地址

    2、equals():

    情况1:类没有覆盖equals()方法。等价于通过“==”比较这两个对象,也就是比较地址

    情况2:类覆盖了equals()方法。一般,都(String类,Integer类等)覆盖equals()方法来比较两个对象的值

    public class Hello {
    
        public static void main(String[] args) {
            //基本数据类型
            int a1 = 1;
            int a2 = 1;
            System.out.println(a1 == a2); //true
    
            String s1 = "hello";
            String s2 = "hello";
            System.out.println(s1 == s2);   //true
    
            //引用数据类型
            Integer a3 = new Integer(2);
            Integer a4 = new Integer(2);
            System.out.println(a3 == a4);   //false
            System.out.println(a3.equals(a4));  //true
    
            String s3 = new String("world");
            String s4 = new String("world");
            System.out.println(s3 == s4);   //false
            System.out.println(s3.equals(s4));  //true
    
            User user1 = new User("y0", 20);
            User user2 = new User("y0", 20);
            System.out.println(user1 == user2); //false
            System.out.println(user1.equals(user2));    //User类没有覆盖equals()方法时为false,User类覆盖了equals()方法时为true
        }
    
    }

    重写equals()方法时必须重写hashCode()方法 

    hashCode()的作用是获取哈希码,也称为散列码;它实际上是返回一个int整数。这个哈希码的作用是确定该对象在哈希表中的索引位置。哈希表存储的是键值对,它的特点是能根据键快速的检索出对应的值,这其中就利用到了散列码。

    public class Hello {
    
        public static void main(String[] args) {
            String s1 = new String("hello");
            String s2 = new String("hello");
            System.out.println(s1.hashCode());  //99162322
            System.out.println(s2.hashCode());  //99162322
    
            User user1 = new User("y1", 21);
            User user2 = new User("y1", 21);
            System.out.println(user1.hashCode());
            System.out.println(user2.hashCode());   //User类重写了hashCode()方法时,哈希码是一致的,否则是不一致的
        }
    }

    如果两个对象的equals()方法相等并且对象类重写了hashCode()方法时,哈希码才是一致的。

  • 相关阅读:
    浅析Vue Router中关于路由守卫的应用以及在全局导航守卫中检查元字段
    react-native 项目配置ts运行环境
    #mobx应用在rn项目中
    react-native TextInput输入框输入时关键字高亮
    react-native-亲测可用插件
    nodejs+express实现图片上传
    cordova图片上传,视频上传(上传多个图片,多个视频)
    cordova图片上传,视频上传(上传单个图片,单个视频)
    移动端如何测试(前端,cordova)
    在mac上将apk包安装到android手机上
  • 原文地址:https://www.cnblogs.com/yanguobin/p/11603709.html
Copyright © 2011-2022 走看看