沉淀再出发:java中的equals()辨析

一、前言

    关于java中的equals,我们可能非常奇怪,在Object中定义了这个函数,其他的很多类中都重载了它,导致了我们对于辨析其中的内涵有了混淆,再加上和“==”的比较,就显得更加的复杂了。

二、java中的equals()

 2.1、Object.java中的equals()

    让我们来看一下Object.java中的equals()。

    首先是Object的定义:

  1 /*
  2  * Copyright (c) 1994, 2012, Oracle and/or its affiliates. All rights reserved.
  3  * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  4  *
  5  *
  6  *
  7  *
  8  *
  9  *
 10  *
 11  *
 12  *
 13  *
 14  *
 15  *
 16  *
 17  *
 18  *
 19  *
 20  *
 21  *
 22  *
 23  *
 24  */
 25 
 26 package java.lang;
 27 
 28 /**
 29  * Class {@code Object} is the root of the class hierarchy.
 30  * Every class has {@code Object} as a superclass. All objects,
 31  * including arrays, implement the methods of this class.
 32  *
 33  * @author  unascribed
 34  * @see     java.lang.Class
 35  * @since   JDK1.0
 36  */
 37 public class Object {
 38 
 39     private static native void registerNatives();
 40     static {
 41         registerNatives();
 42     }
 43 
 44     /**
 45      * Returns the runtime class of this {@code Object}. The returned
 46      * {@code Class} object is the object that is locked by {@code
 47      * static synchronized} methods of the represented class.
 48      *
 49      * <p><b>The actual result type is {@code Class<? extends |X|>}
 50      * where {@code |X|} is the erasure of the static type of the
 51      * expression on which {@code getClass} is called.</b> For
 52      * example, no cast is required in this code fragment:</p>
 53      *
 54      * <p>
 55      * {@code Number n = 0;                             }<br>
 56      * {@code Class<? extends Number> c = n.getClass(); }
 57      * </p>
 58      *
 59      * @return The {@code Class} object that represents the runtime
 60      *         class of this object.
 61      * @jls 15.8.2 Class Literals
 62      */
 63     public final native Class<?> getClass();
 64 
 65     /**
 66      * Returns a hash code value for the object. This method is
 67      * supported for the benefit of hash tables such as those provided by
 68      * {@link java.util.HashMap}.
 69      * <p>
 70      * The general contract of {@code hashCode} is:
 71      * <ul>
 72      * <li>Whenever it is invoked on the same object more than once during
 73      *     an execution of a Java application, the {@code hashCode} method
 74      *     must consistently return the same integer, provided no information
 75      *     used in {@code equals} comparisons on the object is modified.
 76      *     This integer need not remain consistent from one execution of an
 77      *     application to another execution of the same application.
 78      * <li>If two objects are equal according to the {@code equals(Object)}
 79      *     method, then calling the {@code hashCode} method on each of
 80      *     the two objects must produce the same integer result.
 81      * <li>It is <em>not</em> required that if two objects are unequal
 82      *     according to the {@link java.lang.Object#equals(java.lang.Object)}
 83      *     method, then calling the {@code hashCode} method on each of the
 84      *     two objects must produce distinct integer results.  However, the
 85      *     programmer should be aware that producing distinct integer results
 86      *     for unequal objects may improve the performance of hash tables.
 87      * </ul>
 88      * <p>
 89      * As much as is reasonably practical, the hashCode method defined by
 90      * class {@code Object} does return distinct integers for distinct
 91      * objects. (This is typically implemented by converting the internal
 92      * address of the object into an integer, but this implementation
 93      * technique is not required by the
 94      * Java&trade; programming language.)
 95      *
 96      * @return  a hash code value for this object.
 97      * @see     java.lang.Object#equals(java.lang.Object)
 98      * @see     java.lang.System#identityHashCode
 99      */
100     public native int hashCode();
101 
102     /**
103      * Indicates whether some other object is "equal to" this one.
104      * <p>
105      * The {@code equals} method implements an equivalence relation
106      * on non-null object references:
107      * <ul>
108      * <li>It is <i>reflexive</i>: for any non-null reference value
109      *     {@code x}, {@code x.equals(x)} should return
110      *     {@code true}.
111      * <li>It is <i>symmetric</i>: for any non-null reference values
112      *     {@code x} and {@code y}, {@code x.equals(y)}
113      *     should return {@code true} if and only if
114      *     {@code y.equals(x)} returns {@code true}.
115      * <li>It is <i>transitive</i>: for any non-null reference values
116      *     {@code x}, {@code y}, and {@code z}, if
117      *     {@code x.equals(y)} returns {@code true} and
118      *     {@code y.equals(z)} returns {@code true}, then
119      *     {@code x.equals(z)} should return {@code true}.
120      * <li>It is <i>consistent</i>: for any non-null reference values
121      *     {@code x} and {@code y}, multiple invocations of
122      *     {@code x.equals(y)} consistently return {@code true}
123      *     or consistently return {@code false}, provided no
124      *     information used in {@code equals} comparisons on the
125      *     objects is modified.
126      * <li>For any non-null reference value {@code x},
127      *     {@code x.equals(null)} should return {@code false}.
128      * </ul>
129      * <p>
130      * The {@code equals} method for class {@code Object} implements
131      * the most discriminating possible equivalence relation on objects;
132      * that is, for any non-null reference values {@code x} and
133      * {@code y}, this method returns {@code true} if and only
134      * if {@code x} and {@code y} refer to the same object
135      * ({@code x == y} has the value {@code true}).
136      * <p>
137      * Note that it is generally necessary to override the {@code hashCode}
138      * method whenever this method is overridden, so as to maintain the
139      * general contract for the {@code hashCode} method, which states
140      * that equal objects must have equal hash codes.
141      *
142      * @param   obj   the reference object with which to compare.
143      * @return  {@code true} if this object is the same as the obj
144      *          argument; {@code false} otherwise.
145      * @see     #hashCode()
146      * @see     java.util.HashMap
147      */
148     public boolean equals(Object obj) {
149         return (this == obj);
150     }
151 
152     /**
153      * Creates and returns a copy of this object.  The precise meaning
154      * of "copy" may depend on the class of the object. The general
155      * intent is that, for any object {@code x}, the expression:
156      * <blockquote>
157      * <pre>
158      * x.clone() != x</pre></blockquote>
159      * will be true, and that the expression:
160      * <blockquote>
161      * <pre>
162      * x.clone().getClass() == x.getClass()</pre></blockquote>
163      * will be {@code true}, but these are not absolute requirements.
164      * While it is typically the case that:
165      * <blockquote>
166      * <pre>
167      * x.clone().equals(x)</pre></blockquote>
168      * will be {@code true}, this is not an absolute requirement.
169      * <p>
170      * By convention, the returned object should be obtained by calling
171      * {@code super.clone}.  If a class and all of its superclasses (except
172      * {@code Object}) obey this convention, it will be the case that
173      * {@code x.clone().getClass() == x.getClass()}.
174      * <p>
175      * By convention, the object returned by this method should be independent
176      * of this object (which is being cloned).  To achieve this independence,
177      * it may be necessary to modify one or more fields of the object returned
178      * by {@code super.clone} before returning it.  Typically, this means
179      * copying any mutable objects that comprise the internal "deep structure"
180      * of the object being cloned and replacing the references to these
181      * objects with references to the copies.  If a class contains only
182      * primitive fields or references to immutable objects, then it is usually
183      * the case that no fields in the object returned by {@code super.clone}
184      * need to be modified.
185      * <p>
186      * The method {@code clone} for class {@code Object} performs a
187      * specific cloning operation. First, if the class of this object does
188      * not implement the interface {@code Cloneable}, then a
189      * {@code CloneNotSupportedException} is thrown. Note that all arrays
190      * are considered to implement the interface {@code Cloneable} and that
191      * the return type of the {@code clone} method of an array type {@code T[]}
192      * is {@code T[]} where T is any reference or primitive type.
193      * Otherwise, this method creates a new instance of the class of this
194      * object and initializes all its fields with exactly the contents of
195      * the corresponding fields of this object, as if by assignment; the
196      * contents of the fields are not themselves cloned. Thus, this method
197      * performs a "shallow copy" of this object, not a "deep copy" operation.
198      * <p>
199      * The class {@code Object} does not itself implement the interface
200      * {@code Cloneable}, so calling the {@code clone} method on an object
201      * whose class is {@code Object} will result in throwing an
202      * exception at run time.
203      *
204      * @return     a clone of this instance.
205      * @throws  CloneNotSupportedException  if the object's class does not
206      *               support the {@code Cloneable} interface. Subclasses
207      *               that override the {@code clone} method can also
208      *               throw this exception to indicate that an instance cannot
209      *               be cloned.
210      * @see java.lang.Cloneable
211      */
212     protected native Object clone() throws CloneNotSupportedException;
213 
214     /**
215      * Returns a string representation of the object. In general, the
216      * {@code toString} method returns a string that
217      * "textually represents" this object. The result should
218      * be a concise but informative representation that is easy for a
219      * person to read.
220      * It is recommended that all subclasses override this method.
221      * <p>
222      * The {@code toString} method for class {@code Object}
223      * returns a string consisting of the name of the class of which the
224      * object is an instance, the at-sign character `{@code @}', and
225      * the unsigned hexadecimal representation of the hash code of the
226      * object. In other words, this method returns a string equal to the
227      * value of:
228      * <blockquote>
229      * <pre>
230      * getClass().getName() + '@' + Integer.toHexString(hashCode())
231      * </pre></blockquote>
232      *
233      * @return  a string representation of the object.
234      */
235     public String toString() {
236         return getClass().getName() + "@" + Integer.toHexString(hashCode());
237     }
238 
239     /**
240      * Wakes up a single thread that is waiting on this object's
241      * monitor. If any threads are waiting on this object, one of them
242      * is chosen to be awakened. The choice is arbitrary and occurs at
243      * the discretion of the implementation. A thread waits on an object's
244      * monitor by calling one of the {@code wait} methods.
245      * <p>
246      * The awakened thread will not be able to proceed until the current
247      * thread relinquishes the lock on this object. The awakened thread will
248      * compete in the usual manner with any other threads that might be
249      * actively competing to synchronize on this object; for example, the
250      * awakened thread enjoys no reliable privilege or disadvantage in being
251      * the next thread to lock this object.
252      * <p>
253      * This method should only be called by a thread that is the owner
254      * of this object's monitor. A thread becomes the owner of the
255      * object's monitor in one of three ways:
256      * <ul>
257      * <li>By executing a synchronized instance method of that object.
258      * <li>By executing the body of a {@code synchronized} statement
259      *     that synchronizes on the object.
260      * <li>For objects of type {@code Class,} by executing a
261      *     synchronized static method of that class.
262      * </ul>
263      * <p>
264      * Only one thread at a time can own an object's monitor.
265      *
266      * @throws  IllegalMonitorStateException  if the current thread is not
267      *               the owner of this object's monitor.
268      * @see        java.lang.Object#notifyAll()
269      * @see        java.lang.Object#wait()
270      */
271     public final native void notify();
272 
273     /**
274      * Wakes up all threads that are waiting on this object's monitor. A
275      * thread waits on an object's monitor by calling one of the
276      * {@code wait} methods.
277      * <p>
278      * The awakened threads will not be able to proceed until the current
279      * thread relinquishes the lock on this object. The awakened threads
280      * will compete in the usual manner with any other threads that might
281      * be actively competing to synchronize on this object; for example,
282      * the awakened threads enjoy no reliable privilege or disadvantage in
283      * being the next thread to lock this object.
284      * <p>
285      * This method should only be called by a thread that is the owner
286      * of this object's monitor. See the {@code notify} method for a
287      * description of the ways in which a thread can become the owner of
288      * a monitor.
289      *
290      * @throws  IllegalMonitorStateException  if the current thread is not
291      *               the owner of this object's monitor.
292      * @see        java.lang.Object#notify()
293      * @see        java.lang.Object#wait()
294      */
295     public final native void notifyAll();
296 
297     /**
298      * Causes the current thread to wait until either another thread invokes the
299      * {@link java.lang.Object#notify()} method or the
300      * {@link java.lang.Object#notifyAll()} method for this object, or a
301      * specified amount of time has elapsed.
302      * <p>
303      * The current thread must own this object's monitor.
304      * <p>
305      * This method causes the current thread (call it <var>T</var>) to
306      * place itself in the wait set for this object and then to relinquish
307      * any and all synchronization claims on this object. Thread <var>T</var>
308      * becomes disabled for thread scheduling purposes and lies dormant
309      * until one of four things happens:
310      * <ul>
311      * <li>Some other thread invokes the {@code notify} method for this
312      * object and thread <var>T</var> happens to be arbitrarily chosen as
313      * the thread to be awakened.
314      * <li>Some other thread invokes the {@code notifyAll} method for this
315      * object.
316      * <li>Some other thread {@linkplain Thread#interrupt() interrupts}
317      * thread <var>T</var>.
318      * <li>The specified amount of real time has elapsed, more or less.  If
319      * {@code timeout} is zero, however, then real time is not taken into
320      * consideration and the thread simply waits until notified.
321      * </ul>
322      * The thread <var>T</var> is then removed from the wait set for this
323      * object and re-enabled for thread scheduling. It then competes in the
324      * usual manner with other threads for the right to synchronize on the
325      * object; once it has gained control of the object, all its
326      * synchronization claims on the object are restored to the status quo
327      * ante - that is, to the situation as of the time that the {@code wait}
328      * method was invoked. Thread <var>T</var> then returns from the
329      * invocation of the {@code wait} method. Thus, on return from the
330      * {@code wait} method, the synchronization state of the object and of
331      * thread {@code T} is exactly as it was when the {@code wait} method
332      * was invoked.
333      * <p>
334      * A thread can also wake up without being notified, interrupted, or
335      * timing out, a so-called <i>spurious wakeup</i>.  While this will rarely
336      * occur in practice, applications must guard against it by testing for
337      * the condition that should have caused the thread to be awakened, and
338      * continuing to wait if the condition is not satisfied.  In other words,
339      * waits should always occur in loops, like this one:
340      * <pre>
341      *     synchronized (obj) {
342      *         while (&lt;condition does not hold&gt;)
343      *             obj.wait(timeout);
344      *         ... // Perform action appropriate to condition
345      *     }
346      * </pre>
347      * (For more information on this topic, see Section 3.2.3 in Doug Lea's
348      * "Concurrent Programming in Java (Second Edition)" (Addison-Wesley,
349      * 2000), or Item 50 in Joshua Bloch's "Effective Java Programming
350      * Language Guide" (Addison-Wesley, 2001).
351      *
352      * <p>If the current thread is {@linkplain java.lang.Thread#interrupt()
353      * interrupted} by any thread before or while it is waiting, then an
354      * {@code InterruptedException} is thrown.  This exception is not
355      * thrown until the lock status of this object has been restored as
356      * described above.
357      *
358      * <p>
359      * Note that the {@code wait} method, as it places the current thread
360      * into the wait set for this object, unlocks only this object; any
361      * other objects on which the current thread may be synchronized remain
362      * locked while the thread waits.
363      * <p>
364      * This method should only be called by a thread that is the owner
365      * of this object's monitor. See the {@code notify} method for a
366      * description of the ways in which a thread can become the owner of
367      * a monitor.
368      *
369      * @param      timeout   the maximum time to wait in milliseconds.
370      * @throws  IllegalArgumentException      if the value of timeout is
371      *               negative.
372      * @throws  IllegalMonitorStateException  if the current thread is not
373      *               the owner of the object's monitor.
374      * @throws  InterruptedException if any thread interrupted the
375      *             current thread before or while the current thread
376      *             was waiting for a notification.  The <i>interrupted
377      *             status</i> of the current thread is cleared when
378      *             this exception is thrown.
379      * @see        java.lang.Object#notify()
380      * @see        java.lang.Object#notifyAll()
381      */
382     public final native void wait(long timeout) throws InterruptedException;
383 
384     /**
385      * Causes the current thread to wait until another thread invokes the
386      * {@link java.lang.Object#notify()} method or the
387      * {@link java.lang.Object#notifyAll()} method for this object, or
388      * some other thread interrupts the current thread, or a certain
389      * amount of real time has elapsed.
390      * <p>
391      * This method is similar to the {@code wait} method of one
392      * argument, but it allows finer control over the amount of time to
393      * wait for a notification before giving up. The amount of real time,
394      * measured in nanoseconds, is given by:
395      * <blockquote>
396      * <pre>
397      * 1000000*timeout+nanos</pre></blockquote>
398      * <p>
399      * In all other respects, this method does the same thing as the
400      * method {@link #wait(long)} of one argument. In particular,
401      * {@code wait(0, 0)} means the same thing as {@code wait(0)}.
402      * <p>
403      * The current thread must own this object's monitor. The thread
404      * releases ownership of this monitor and waits until either of the
405      * following two conditions has occurred:
406      * <ul>
407      * <li>Another thread notifies threads waiting on this object's monitor
408      *     to wake up either through a call to the {@code notify} method
409      *     or the {@code notifyAll} method.
410      * <li>The timeout period, specified by {@code timeout}
411      *     milliseconds plus {@code nanos} nanoseconds arguments, has
412      *     elapsed.
413      * </ul>
414      * <p>
415      * The thread then waits until it can re-obtain ownership of the
416      * monitor and resumes execution.
417      * <p>
418      * As in the one argument version, interrupts and spurious wakeups are
419      * possible, and this method should always be used in a loop:
420      * <pre>
421      *     synchronized (obj) {
422      *         while (&lt;condition does not hold&gt;)
423      *             obj.wait(timeout, nanos);
424      *         ... // Perform action appropriate to condition
425      *     }
426      * </pre>
427      * This method should only be called by a thread that is the owner
428      * of this object's monitor. See the {@code notify} method for a
429      * description of the ways in which a thread can become the owner of
430      * a monitor.
431      *
432      * @param      timeout   the maximum time to wait in milliseconds.
433      * @param      nanos      additional time, in nanoseconds range
434      *                       0-999999.
435      * @throws  IllegalArgumentException      if the value of timeout is
436      *                      negative or the value of nanos is
437      *                      not in the range 0-999999.
438      * @throws  IllegalMonitorStateException  if the current thread is not
439      *               the owner of this object's monitor.
440      * @throws  InterruptedException if any thread interrupted the
441      *             current thread before or while the current thread
442      *             was waiting for a notification.  The <i>interrupted
443      *             status</i> of the current thread is cleared when
444      *             this exception is thrown.
445      */
446     public final void wait(long timeout, int nanos) throws InterruptedException {
447         if (timeout < 0) {
448             throw new IllegalArgumentException("timeout value is negative");
449         }
450 
451         if (nanos < 0 || nanos > 999999) {
452             throw new IllegalArgumentException(
453                                 "nanosecond timeout value out of range");
454         }
455 
456         if (nanos > 0) {
457             timeout++;
458         }
459 
460         wait(timeout);
461     }
462 
463     /**
464      * Causes the current thread to wait until another thread invokes the
465      * {@link java.lang.Object#notify()} method or the
466      * {@link java.lang.Object#notifyAll()} method for this object.
467      * In other words, this method behaves exactly as if it simply
468      * performs the call {@code wait(0)}.
469      * <p>
470      * The current thread must own this object's monitor. The thread
471      * releases ownership of this monitor and waits until another thread
472      * notifies threads waiting on this object's monitor to wake up
473      * either through a call to the {@code notify} method or the
474      * {@code notifyAll} method. The thread then waits until it can
475      * re-obtain ownership of the monitor and resumes execution.
476      * <p>
477      * As in the one argument version, interrupts and spurious wakeups are
478      * possible, and this method should always be used in a loop:
479      * <pre>
480      *     synchronized (obj) {
481      *         while (&lt;condition does not hold&gt;)
482      *             obj.wait();
483      *         ... // Perform action appropriate to condition
484      *     }
485      * </pre>
486      * This method should only be called by a thread that is the owner
487      * of this object's monitor. See the {@code notify} method for a
488      * description of the ways in which a thread can become the owner of
489      * a monitor.
490      *
491      * @throws  IllegalMonitorStateException  if the current thread is not
492      *               the owner of the object's monitor.
493      * @throws  InterruptedException if any thread interrupted the
494      *             current thread before or while the current thread
495      *             was waiting for a notification.  The <i>interrupted
496      *             status</i> of the current thread is cleared when
497      *             this exception is thrown.
498      * @see        java.lang.Object#notify()
499      * @see        java.lang.Object#notifyAll()
500      */
501     public final void wait() throws InterruptedException {
502         wait(0);
503     }
504 
505     /**
506      * Called by the garbage collector on an object when garbage collection
507      * determines that there are no more references to the object.
508      * A subclass overrides the {@code finalize} method to dispose of
509      * system resources or to perform other cleanup.
510      * <p>
511      * The general contract of {@code finalize} is that it is invoked
512      * if and when the Java&trade; virtual
513      * machine has determined that there is no longer any
514      * means by which this object can be accessed by any thread that has
515      * not yet died, except as a result of an action taken by the
516      * finalization of some other object or class which is ready to be
517      * finalized. The {@code finalize} method may take any action, including
518      * making this object available again to other threads; the usual purpose
519      * of {@code finalize}, however, is to perform cleanup actions before
520      * the object is irrevocably discarded. For example, the finalize method
521      * for an object that represents an input/output connection might perform
522      * explicit I/O transactions to break the connection before the object is
523      * permanently discarded.
524      * <p>
525      * The {@code finalize} method of class {@code Object} performs no
526      * special action; it simply returns normally. Subclasses of
527      * {@code Object} may override this definition.
528      * <p>
529      * The Java programming language does not guarantee which thread will
530      * invoke the {@code finalize} method for any given object. It is
531      * guaranteed, however, that the thread that invokes finalize will not
532      * be holding any user-visible synchronization locks when finalize is
533      * invoked. If an uncaught exception is thrown by the finalize method,
534      * the exception is ignored and finalization of that object terminates.
535      * <p>
536      * After the {@code finalize} method has been invoked for an object, no
537      * further action is taken until the Java virtual machine has again
538      * determined that there is no longer any means by which this object can
539      * be accessed by any thread that has not yet died, including possible
540      * actions by other objects or classes which are ready to be finalized,
541      * at which point the object may be discarded.
542      * <p>
543      * The {@code finalize} method is never invoked more than once by a Java
544      * virtual machine for any given object.
545      * <p>
546      * Any exception thrown by the {@code finalize} method causes
547      * the finalization of this object to be halted, but is otherwise
548      * ignored.
549      *
550      * @throws Throwable the {@code Exception} raised by this method
551      * @see java.lang.ref.WeakReference
552      * @see java.lang.ref.PhantomReference
553      * @jls 12.6 Finalization of Class Instances
554      */
555     protected void finalize() throws Throwable { }
556 }
Object的定义

相关文章: