zoukankan      html  css  js  c++  java
  • == 和 equals 的区别

    总是忘记,记录一下。
    ==
    对于基本类型和引用类型==作用的效果不同
    1:对于基本类型比较的是值
    2:对于引用类型比较的是引用地址

    String a = "hello";
    String b = "hello";
    String c = new String("hello");
    System.out.println(a == b); //true
    System.out.println(a == c); //false


    解读:对于 a 和 b之间的比较,因为a和b都指向了字符串常量池中的"hello",所有==结果为true,而c指向的是堆内存中的"hello",所以为false。

    equals
    equals 本质上就是 ==,只不过 String 和 Integer 等重写了 equals 方法,把它变 成了值比较。
    object类中的eqauls方法:

    public boolean equals(Object obj) {
      return (this == obj); //和==一样
    }
    
    
    String c = new String("hello");
    String d = new String("hello");
    
    System.out.println(c== d);//false
    System.out.println(c.equals(d)); //true


    解读:c指向的引用不同于d指向的引用,所以==的结果为false,而对于equals方法,因为String重写了equals,所以这时候比较的是c和d的值,结果当然为true。

    String类中的eqauls方法:

    public boolean equals(Object anObject) {
    if (this == anObject) {
    return true;
    }
    if (anObject instanceof String) {
      String anotherString = (String)anObject;
      int n = value.length;
      if (n == anotherString.value.length) { //逐一比较每个字符
        char v1[] = value;
        char v2[] = anotherString.value;
        int i = 0;
        while (n-- != 0) {
          if (v1[i] != v2[i])
          return false;
          i++;
      }
          return true;
      }
        }
          return false;
    }

    总结::== 对于基本类型来说是值比较,对于引用类型来说是比较的是引用; 而 equals 默认情况下是引用比较,只是很多类重写了 equals 方法,比如 String、Integer 等把它变成了值比较,所以一般情况下 equals 比较的是值是 否相等。

  • 相关阅读:
    题解 CF171G 【Mysterious numbers
    题解 P1157 【组合的输出】
    题解 P3955 【图书管理员】
    题解 P2036 【Perket】
    题解 CF837A 【Text Volume】
    题解 CF791A 【Bear and Big Brother】
    题解 CF747A 【Display Size】
    题解 P1332 【血色先锋队】
    题解 P2660 【zzc 种田】
    题解 P4470 【[BJWC2018]售票】
  • 原文地址:https://www.cnblogs.com/swqblog/p/12853062.html
Copyright © 2011-2022 走看看