`
goon
  • 浏览: 184597 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Java基础:== 、 equals 、hashCode

 
阅读更多

== :比较内存地址

---------------------------------------------------

Object.equals():

 public boolean equals(Object obj) {
	return (this == obj);
    }

 

Long.equals():

 public boolean equals(Object obj) {
	if (obj instanceof Long) {
	    return value == ((Long)obj).longValue();
	}
	return false;
    }
Test:
Long a = new Long(1);
int b = 1;
System.out.println(a.equals(b));//false,b被装箱后比较a与b的内存地址
System.out.println(a==b);//true,a被拆箱后比较a与b的内存地址
Long a1 = new Long(1);
System.out.println(a == a1);//false

 

String.equals():

 public boolean equals(Object anObject) {
	if (this == anObject) {
	    return true;
	}

HashMap.equals():

public final boolean equals(Object o) {
            if (!(o instanceof Map.Entry))
                return false;
            Map.Entry e = (Map.Entry)o;
            Object k1 = getKey();
            Object k2 = e.getKey();
            if (k1 == k2 || (k1 != null && k1.equals(k2))) {
                Object v1 = getValue();
                Object v2 = e.getValue();
                if (v1 == v2 || (v1 != null && v1.equals(v2)))
                    return true;
            }
            return false;
        }

---------------------------------------------------

Object.hashCode(): 返回内存地址

/**
     * Returns a hash code value for the object. This method is 
     * supported for the benefit of hashtables such as those provided by 
     * <code>java.util.Hashtable</code>. 
     * <p>
     * The general contract of <code>hashCode</code> is: 
     * <ul>
     * <li>Whenever it is invoked on the same object more than once during 
     *     an execution of a Java application, the <tt>hashCode</tt> method 
     *     must consistently return the same integer, provided no information 
     *     used in <tt>equals</tt> comparisons on the object is modified.
     *     This integer need not remain consistent from one execution of an
     *     application to another execution of the same application. 
     * <li>If two objects are equal according to the <tt>equals(Object)</tt>
     *     method, then calling the <code>hashCode</code> method on each of 
     *     the two objects must produce the same integer result. 
     * <li>It is <em>not</em> required that if two objects are unequal 
     *     according to the {@link java.lang.Object#equals(java.lang.Object)} 
     *     method, then calling the <tt>hashCode</tt> method on each of the 
     *     two objects must produce distinct integer results.  However, the 
     *     programmer should be aware that producing distinct integer results 
     *     for unequal objects may improve the performance of hashtables.
     * </ul>
     * <p>
     * As much as is reasonably practical, the hashCode method defined by 
     * class <tt>Object</tt> does return distinct integers for distinct 
     * objects. (This is typically implemented by converting the internal 
     * address of the object into an integer, but this implementation 
     * technique is not required by the 
     * Java<font size="-2"><sup>TM</sup></font> programming language.)
     *
     * @return  a hash code value for this object.
     * @see     java.lang.Object#equals(java.lang.Object)
     * @see     java.util.Hashtable
     */
    public native int hashCode();

 Long.hashCode():返回Long的值

    /**
     * Returns a hash code for this <code>Long</code>. The result is
     * the exclusive OR of the two halves of the primitive
     * <code>long</code> value held by this <code>Long</code>
     * object. That is, the hashcode is the value of the expression:
     * <blockquote><pre>
     * (int)(this.longValue()^(this.longValue()&gt;&gt;&gt;32))
     * </pre></blockquote>
     *
     * @return  a hash code value for this object.
     */
    public int hashCode() {
	return (int)(value ^ (value >>> 32));
    }

 

String.hashCode():

 /**
     * Returns a hash code for this string. The hash code for a
     * <code>String</code> object is computed as
     * <blockquote><pre>
     * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
     * </pre></blockquote>
     * using <code>int</code> arithmetic, where <code>s[i]</code> is the
     * <i>i</i>th character of the string, <code>n</code> is the length of
     * the string, and <code>^</code> indicates exponentiation.
     * (The hash value of the empty string is zero.)
     *
     * @return  a hash code value for this object.
     */
    public int hashCode() {
	int h = hash;
        int len = count;
	if (h == 0 && len > 0) {
	    int off = offset;
	    char val[] = value;

            for (int i = 0; i < len; i++) {
                h = 31*h + val[off++];
            }
            hash = h;
        }
        return h;
    }

 test:

String s = "abc";
System.out.println(s.hashCode());//96354
		
String s2 = "abc";
System.out.println(s2.hashCode());//96354

 

Object obj = 1;
System.out.println(obj.hashCode());//1
Object obj2 = new Long(1);
System.out.println(obj.hashCode());//1
Object obj3 = new Long(1);
System.out.println(obj.equals(obj2));//false
System.out.println(obj==obj3);//false
System.out.println(obj2==obj3);//false
Object obj4 = 1;
  System.out.println(obj==obj4);//true

Long obj5 = 1L;   System.out.println(obj == obj5);//false   System.out.println(obj4.equals(obj5));//false

 

分享到:
评论

相关推荐

    java中的==和equals()方法1

    在Java编程语言中,了解如何正确使用`==`和`equals()`方法是非常关键的,因为它们在比较对象和基本类型时有不同的行为。下面将详细解释这两个方法的工作原理、使用场景以及一些常见误区。 首先,`==`运算符主要用于...

    ==和equals方法究竟有什么区别

    同时,为了保持一致性,如果重写了`equals()`,通常也需要重写`hashCode()`方法,以满足`equals()`和`hashCode()`的合同约定,即如果两个对象相等(`equals()`返回`true`),它们的`hashCode()`应该也相等。...

    Java中equals,hashcode和==的区别

    "Java中equals、hashcode和==的区别" Java 中 equals、hashcode 和==的区别是 Java 编程语言中一个经常遇到的问题。这三个概念都是用来比较对象的,但是它们之间存在着本质的区别。 首先,==号是Java中的一个...

    Java理论与实践:hashCode()和equals()方法

    本文介绍了Java语言不直接支持关联数组,可以使用任何对象作为一个索引的数组,但在根Object类中使用 hashCode()方法明确表示期望广泛使用HashMap。理想情况下基于散列的容器提供有效插入和有效检索;直接在对象模式...

    Java中==运算符与equals方法的区别及intern方法详解

    "Java中==运算符与equals方法的区别及intern方法详解" Java中==运算符与equals方法的区别是Java程序设计语言中的一個非常重要的概念,它們兩者都是用來比较字符串是否相等,但是它们的比较方式完全不同。 ==运算符...

    Java常见笔试、面试题目深度剖析 相等性(==及equals方法)详解

    在Java编程语言中,相等性是理解和使用对象时至关重要的概念。本篇文章将深入剖析“==”运算符和equals()方法的区别与联系,帮助你在Java的...了解这些基础知识,能够让你在面对Java相关的面试或编程挑战时更加自信。

    Java_重写equals()和hashCode()

    在Java编程语言中,`equals()` 和 `hashCode()` 方法是对象的基本组成部分,它们在很多场景下都发挥着至关重要的作用。这两个方法与对象的相等性比较和哈希表(如HashMap、HashSet)的运作紧密相关。这篇博客将深入...

    298.296.JAVA基础教程_面向对象(中)-总结==与equals()(298).rar

    在Java中,理解和正确使用“==”和“equals()”方法是编程基础的重要部分,尤其对于初学者来说至关重要。本教程将深入探讨这两个概念以及它们在Java中的应用。 首先,“==”运算符在Java中主要用于比较基本类型(如...

    知识点 比较运算符==和equals方法的比较

    在Java编程语言中,比较运算符`==`和`equals()`方法是用来检查两个对象是否相等的,但它们之间存在显著的区别。理解这些差异对于编写正确的代码至关重要。 首先,我们来看`==`运算符。它主要用于基本数据类型的比较...

    java 基础之(equals hashcode)

    总的来说,理解和正确使用 `equals()` 和 `hashCode()` 是Java开发者必备的基础知识,这对于编写健壮、高效的代码至关重要。在进行对象比较和使用哈希表时,这两个方法的合理实现可以极大地提高程序的性能和正确性。

    Java重写equals同时需要重写hashCode的代码说明

    Java重写equals同时需要重写hashCode的代码说明,以及如何重写hashCode方法,此代码演示按照effective java书籍说明的重写思路。代码中演示了使用集合存储对象,并且对象作为key,需重写equals和hashCode.

    Java中的== 和equals()方法详解与实例

    在Java编程语言中,`==` 和 `equals()` 方法是用来比较对象或基本数据类型的值的。两者虽然在外观上相似,但...同时,为了保持一致性,通常也会重写 `hashCode()` 方法,以遵循 `equals()` 和 `hashCode()` 的契约。

    java中hashcode()和equals()方法详解

    `hashCode()`方法定义于`Object`类中,它是Java语言的基础类,所有Java类都直接或间接地继承自`Object`。`hashCode()`的主要作用在于生成一个整数,这个整数通常用来表示对象的一个哈希值。在Java集合框架中,特别是...

    java中hashcode()和equals()的详解

    在Java编程语言中,`hashCode()`和`equals()`方法是对象身份验证的关键组成部分,它们主要用于对象的比较和哈希表(如HashMap、HashSet等)的操作。理解这两个方法的工作原理对于编写高效和可靠的代码至关重要。 ...

    详解java==运算符和equals()方法的区别

    Java编程语言中有两种主要的方法来比较对象的平等性:`==`运算符和`equals()`方法。理解这两者的区别对于编写正确和可靠的代码至关重要。 1. `==`运算符: `==`运算符主要用于比较基本类型(如int、char等)的值,...

    java中hashcode()和equals()和==的详解

    有许多人学了很长时间的Java,但一直不明白hashCode方法的作用以及equals()和==的区别,我来解释一下吧。首先,想要明白hashCode的作用,你必须要先知道Java中的集合。总的来说,Java中的集合(Collection)有两类,...

    解析Java对象的equals()和hashCode()的使用

    深入解析Java对象的equals()和hashCode()的使用 在Java语言中,equals()和hashCode()两个函数的使用是紧密配合的,你要是自己设计其中一个,就要设计另外一个。在多数情况下,这两个函数是不用考虑的,直接使用它们...

    重写equals和hashcode方法_equals_重写equals和hashcode方法_

    总的来说,理解并正确地重写 `equals()` 和 `hashCode()` 方法是Java编程中的基础技能,它有助于确保对象的比较和集合操作的正确性。在开发过程中,要时刻注意这两个方法的正确实现,以提高代码质量和可维护性。

    Java容器集合(equals 和 hashCode+基础数据结构+ArrayList+Vector和LinkedList)

    Java容器集合(equals和hashCode+基础数据结构+ArrayList+Vector和LinkedList) Java容器集合是Java中的一种基础数据结构,用于存储和管理数据。其中,equals和hashCode方法是Java容器集合中两个非常重要的方法,...

Global site tag (gtag.js) - Google Analytics