Home PC Games Linux Windows Database Network Programming Server Mobile  
  Home \ Programming \ The difference between equals and == in Java     - To install OwnCloud 7.0.4 under Ubuntu (Linux)

- CentOS 7 Change Hostname (Linux)

- CentOS system Amoeba + MySQL Master-slave configuration (Database)

- Linux Firewall Builder shorewall (Linux)

- How to monitor Linux system performance Nmon (Linux)

- Python 2.7 installed on CentOS 6.5 (Linux)

- CentOS7 minimized installation can not find the 'ifconfig' command - Repair Tips (Linux)

- Installation Docker FAQ on Ubuntu (Linux)

- To establish a secure and reliable Linux operating system (Linux)

- Linux operating process information (Linux)

- Debian (Wheezy) were installed wxPython GUI development (Linux)

- Android Studio 1.0.2 set the memory size (Linux)

- Formatted output printf command (Programming)

- Linux basic introductory tutorial ---- regex basis (Linux)

- Gentoo: startx appeared Failed to load module Problem Solving (Linux)

- Jump table (skiplist) of code (Programming)

- Binder began to talk about inter-process communication mechanism from Android AIDL (Programming)

- To configure parameter configuration and software installation and uninstallation under Linux (Linux)

- Oracle LONG RAW BLOB CLOB type of presentation (Database)

- Java rewrite the hashcode method (Programming)

  The difference between equals and == in Java
  Add Date : 2017-08-31      
  The difference between equals and == in Java is the type of stack that is stored in memory, and the reference type of variable is simply the address where the reference type variable is stored on the stack, which itself is stored in the heap.
== operation is the value of the two variables are equal, for the reference variable represents the two variables stored in the heap address is the same, that is, the contents of the stack are the same.
The equals operation indicates whether the two variables are references to the same object, that is, whether the contents of the heap are the same.

== Comparison of the two objects address, and equals is the comparison of the contents of two objects.
Obviously, when equals is true, == is not necessarily true;
First, String equals and ==

Java code
Public class TestString {
    Public static void main (String [] args) {
        String s1 = "Monday";
        String s2 = "Monday";
Above this procedure, in the end there are several objects?
To detect it, a little change procedures

Java code
Public class TestString {
    Public static void main (String [] args) {
        String s1 = "Monday";
        String s2 = "Monday";
        If (s1 == s2)
            System.out.println ( "s1 == s2");
            System.out.println ( "s1! = S2");
Compile and run the program, output: s1 == s2
Description: s1 and s2 reference the same String object - "Monday"!

And then a little change in the program, there will be more strange discovery:

Java code
Public class TestString {
    Public static void main (String [] args) {
        String s1 = "Monday";
        String s2 = new String ( "Monday");
        If (s1 == s2)
            System.out.println ( "s1 == s2");
            System.out.println ( "s1! = S2");
        If (s1.equals (s2))
            System.out.println ( "s1 equals s2");
            System.out.println ( "s1 not equals s2");
We create s2 with the new operator
Program output:
S1! = S2
S1 equals s2
Description: s1 s2 refers to two "Monday" String objects, respectively

3. String buffer pool

Originally, the program will create a string buffer when running
When using s2 = "Monday" expression is to create a string, the program will first
In this String buffer pool to find the same value of the object, in the first program, s1 first
Into the pool, so s2 was created when the program found with the same value of s1
Reference s2 to the object referenced by s1 "Monday"
The second paragraph of the procedure, the use of the new operator, he told the procedure to understand:
"I want a new! Do not old!" So a new "Monday" Sting object was created
Built in memory. Their values are the same, but the locations are different, one swimming in the pool
One rests on the shore. Oh, really a waste of resources, obviously the same must have to do it separately?
Change the program again:

Java code
Public class TestString {
    Public static void main (String [] args) {
        String s1 = "Monday";
        String s2 = new String ( "Monday");
        S2 = s2.intern ();
        If (s1 == s2)
            System.out.println ( "s1 == s2");
            System.out.println ( "s1! = S2");
        If (s1.equals (s2))
            System.out.println ( "s1 equals s2");
            System.out.println ( "s1 not equals s2");
This time to join: s2 = s2.intern ();
Program output:
S1 == s2
S1 equals s2

The original, (java.lang.String intern () method
The return value of the "abc" .intern () method is also the string "abc", which appears to appear to be of little use. But in fact, it did a little trick:
If there is, it returns the string in the pool; if it does not exist, it adds "abc" to the string pool, and then returns a reference to it as a reference to the string pool. .
The better way:
String all intern () to the buffer pool go
It is best to use the new time on this operation
String s2 = new String ( "Monday"). Intern ();
Then you can use == compare the value of the two strings

Second, the simple data types and packaging in the equals and ==
Java provides a wrapper class for each simple data type, and each primitive data type can be encapsulated as an object type.
In addition to int (Integer) and char (Character), the remaining types of capital letters that capsulate the type of type name. Double (Double), float (Float), long (Long), short (Short), byte (Byte), boolean (Boolean).
To int and Integer as an example
Java and int Integer distinction between the following:
1.int is the basic data type, the default value can be 0;
2.Integer is int encapsulated class, the default value is null;
3.int and Integer can represent a certain value;
4.int and Integer can not be interoperable, because they are two different data types;
Int a1 = 1;
Int a2 = 1;
Integer b1 = new Integer (1);
Integer b2 = new Integer (1);
A1 == a2 This is established, it is very simple, all know
A1 == b1 This is not true. The value of the expression is false, they are different data types (in jdk1.5 above version is true)
B1 == b2 This expression is not true. The expression value is false, although the same data type, but they are two objects, == comparison of two objects address, their address is not equal, the content Are equal to 1;
B1.equals (b2) == true This is true, the expression value is true. The same data type, two objects, different addresses, the same content, quals is the comparison of two objects, so established.
(A.equals (b), because equals comparison of two objects, so a, b can not be the basic data types, otherwise a compiler error.) (In jdk1.5 above, b can be the basic data types , A can not)
Similarly, the other types of packages and the basic type is also true.
The difference between equals and == in java
== Comparison of the two objects address, and equals is the comparison of the contents of two objects.
In versions above jdk1.5, primitive types and wrappers can be converted automatically, similar to String objects and string constants.

Java code
Integer i1 = 123;
      Integer i2 = 123;
      Int i = 123;
      Integer i3 = new Integer (123);
      Integer i4 = new Integer (123);
      System.out.println ( "i1 == i2 =" + (i1 == i2));
      System.out.println ( "i1.equals (i2) =" + (i1.equals (i2)));
      System.out.println ();
      System.out.println ( "i3 == i4 =" + (i3 == i4));
      System.out.println ( "i3.equals (i4) =" + (i3.equals (i4)));
      System.out.println ();
      System.out.println ( "i2 == i4 =" + (i2 == i4));
      System.out.println ( "i2.equals (i4) =" + (i2.equals (i4)));
      System.out.println ();
      System.out.println ( "i == i2 =" + (i == i2));
      System.out.println ( "i1.equals (i) =" + (i1.equals (i)));
      System.out.println ();
      System.out.println ( "i == i4 =" + (i == i4));
      System.out.println ( "i4.equals (i) =" + (i4.equals (i)));
      I1 == i2 = true
    I1.equals (i2) = true
    I3 == i4 = false
    I3.equals (i4) = true
    I2 == i4 = false
    I2.equals (i4) = true
    I == i2 = true
    I1.equals (i) = true
    I == i4 = true
    I4.equals (i) = true
Third, how to use other types of equals and ==
API in most of the class rewrite the equals method, there is no rewrite of the general is to write their own class,
If your own definition of a category, compared with the definition of class equals and == is the same, are more handle address,
Because the custom class is inherited from the object, and the object of equals is to use == to achieve, you can see the source code.

Fourth, java where the relationship between equals and hashCode
Just to maintain the hashCode method of conventional agreements, it is required to use equals to compare the two objects hashCode the same.
Both equals () and hashCode () come from java.lang.Object. You can of course override.

Such as a.equals (b). Only when a memory address equal to the only return true. Of course, such as String and other classes have been rewritten on this method, the comparison is no longer a memory address.
The hashCode () value is also associated with the memory address, so the hashCode is equal only if the memory addresses are equal.

Similarly, many classes have rewritten this method, or String as an example:

Java code
Public int hashCode () {
Int h = hash;
If (h == 0) {
      Int off = offset;
      Char val [] = value;
      Int len = count;
      For (int i = 0; i < len; i ++) {
        H = 31 * h + val [off ++];
      Hash = h;
  Return h;
It is not associated with the memory address. This is done to ensure that the equals comparison returns true for the two objects, their hashCode is the same.

Therefore, when the general rewriting equals will override hashCode ().
Of course, this is equivalent to an agreement, an agreement you do not do wrong.

Five, hashCode
In general, you do not need to understand the use of hashcode, but when you use hashmap, hashset and other collection classes should pay attention to the next hashcode.

You want to take a key object hashmap value, hashmap work method is,
Through the object you pass the hashcode to find the address in memory,
When you find this address and then through the equals method to compare the contents of this address is the same as you put the original, as to remove the value.

So here to match the two parts, hashcode and equals
But if you say a new object as a key to get value is never get the results,
Because each new an object, the object of the hashcode is always different, so we have to rewrite the hashcode,
You can make your hashcode is a constant in the object, so you can always through your object to find the hashcode address of the key,
Then you have to rewrite your equals method, so that the contents of memory are equal.
- Redis-- persistence articles (Database)
- Installation and Configuration Munin monitoring server on Linux (Server)
- The Java development environment to build under Ubuntu 14.04 (Linux)
- The SVN installation, configuration and start - up under Linux (CentOS 6.5) (Server)
- MySQL bulk insert data script (Database)
- Change the kernel boot sequence after CentOS 7 kernel upgrade (Linux)
- Java reflection summary (Programming)
- CentOS 6.5 Linux System Customization and Packaging Quick Implementation Script (Linux)
- Java Timer (regular calling, to achieve a fixed time to perform) (Programming)
- Unable to solve the official version of Android Studio online update problem (Linux)
- Axel install plug under CentOS 5/6 acceleration yum downloads (Linux)
- Linux cd command Detailed (Linux)
- OpenWRT environment to build (Linux)
- Bash environment is automatically install and initialize oh-my-zsh & autojump zsh (Linux)
- Linux regex awk Comments (Linux)
- How to add any of a Linux distribution beautiful fonts (Linux)
- Observation network performance tools for Linux (Linux)
- Physical backup and recovery SYSTEM table space (Database)
- Nginx Keepalived Nginx monitoring scripts (Server)
- Google open source TCP team repaired the Linux kernel TCP flaw (Linux)
  CopyRight 2002-2022 newfreesoft.com, All Rights Reserved.