Methods of java Object class (equals and toString)


Introduction: The content of the article is selected from Silicon Valley, JDK8, using the eclipse development environment, and mainly introduces the two most commonly used methods in the Object class: equals and toString methods.

Characteristics of the Object class

  • Object class has no attributes
  • The Object class has only a null parameter constructor

Regarding the methods of the Object class, as shown in the figure below
Insert picture description here
, some of the methods have return values, such as getClass()

package com.atguigu.java;

public class ObjectTest {
    
    
	public static void main(String[] args) {
    
    
		Order order = new Order();
		System.out.println(order.getClass());
		System.out.println(order.getClass().getSuperclass());
	}
}

class Order{
    
    
	
}

The result of the operation is

class com.atguigu.java.Order
class java.lang.Object

equals(Object obj)

equals(Object obj) is one of the most commonly used methods in the Object class.

The difference between the comparison operator == and equals()

The use of operator == (for basic data types)

  • The object on both sides of the operator == can be a basic data type or a reference data type
  • The operator == basic data type compares the value of the left and right variables
  • The operator == refers to the data category to compare whether the address values ​​stored in the left and right variables are equal
  • When using operator ==, you must ensure that the variable types on the left and right sides are the same (including automatic type promotion), otherwise the compiler will report an error

Compare the values ​​of basic data types as follows

package com.atguigu.java;

public class EqualsTest {
    
    
	public static void main(String[] args) {
    
    
		int i = 10;
		int j = 10;
		System.out.println(i == j);
		double c = 10.0;
		System.out.println(i == c);//自动类型提升
		char c1 = 10;
		System.out.println(i == c1);
		char c2 = 65;
		char c3 = 'A';
		System.out.println(c2 == c3);
//		boolean b = true;
		
//		System.out.println(b == i); //基本数据类型中,不能把boolean和其他类型进行比较,编译器会报错
	}
}

The result of the operation is

true
true
true
true

ps: In basic data types, boolean cannot be compared with other types, the compiler will report an error, but the operator == can be used to compare between Boolean and Boolean.

The use of operator == (for reference data types)

First create a Customer object

package com.atguigu.java;

public class Customer {
    
    
	private String name;
	private int age;
}

Click Alt+shift+s, open the Source item in the toolbar,
click Generate Getters and Setters, create a public method that calls private properties, and then click Generate Constructor Using Fields to construct an empty parameter constructor and a constructor with parameters, create The result is as follows

package com.atguigu.java;

public class Customer {
    
    
	private String name;
	private int age;
	public String getName() {
    
    
		return name;
	}
	public void setName(String name) {
    
    
		this.name = name;
	}
	public int getAge() {
    
    
		return age;
	}
	public void setAge(int age) {
    
    
		this.age = age;
	}
	public Customer(String name, int age) {
    
    
		super();
		this.name = name;
		this.age = age;
	}
	public Customer() {
    
    
		super();
	}
}

Then test in EqualsTest

		Customer cust1 = new Customer("Tom",21);
		Customer cust2 = new Customer("Tom",21);
		String str1 = new String("atguigu");
		String str2 = new String("atguigu");
		System.out.println(cust1 == cust2);
		System.out.println(str1 == str2);

The results of the operation are all false, because the operator == compares whether the address values ​​of the two stack space variables are equal. Here, two cust objects are new, pointing to different addresses in the heap space, so they are definitely not equal.
ps: String is a reference data type. Here str1 and str2 are also stored in two addresses that point to the string constant pool, so they are false.

Use of equals method

The equals method is a method of an object. Before using it, an object must be created before the method can be called. And generally the equals method should be rewritten in the subclass.

  • equals() method only applies to reference data types
  • If the equals method is not rewritten in the subclass, the equals method is equivalent to the operator ==.
  • Such as String, Date, File, wrapper classes, etc. have rewritten the equals() method in the Object class. After rewriting, the comparison is not whether the addresses of the two references are the same, but whether the "entity content" of the two objects is the same.

Test in the EqualsTest class, the code is as follows

		System.out.println(cust1.equals(cust2));
		System.out.println(str1.equals(str2));
		
		Date date1 = new Date(6441316161L);
		Date date2 = new Date(6441316161L);
		System.out.println(date1.equals(date2));

The result of the operation is

false
true
true

The reason why the first running result is false here is because we did not override the equals method in the Customer class, but instead called the equals method in the Object class. The equal method in the Object class is defined as

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

It can be seen that calling the equals method in the Object class is equivalent to the operator ==, and the result is definitely false

ps: running

System.out.println(cust1.equals(cust2));

Here is an application of polymorphism, because the formal parameters defined by the equals method are of type Object. Here we pass in a subclass of the Object class, but the equals method has not been overridden.

Running System.out.println(str1.equals(str2)); returns true because we have overridden the equals method in the string class, calling the method of the subclass to compare the entity content instead of the address value .
Running System.out.println(date1.equals(date2)); returns true in the same way, but we don’t have a custom Date class here, we need to import it from the java standard library, here is a shortcut key

ctrl+shift+o

Import java.util.Date

Normally, the equals method is used to compare the content of entities, so the equals method of Object cannot be used. An equals method must be rewritten in the subclass. Here we rewrite an equals method in the Customer object. The
code is as follows

	@Override
	public boolean equals(Object obj) {
    
    
		if(this == obj){
    
    
			return true;
		}
		if(obj instanceof Customer){
    
    
			Customer cust = (Customer)obj;
			return cust.age == this.age && this.name.equals(cust.name);
		}else{
    
    
			return false;
		}
	}

Run System.out.println(cust1.equals(cust2)); the result is true.
ps: After all, manual rewriting is too cumbersome. In the eclipse environment, click source in the toolbar or press Alt+shift+s, and then click Generate harsCode() and equals(), it will automatically rewrite an equals() and hashCode( ) Method, here we just need equals(), the code is as follows:

//	@Override
//	public int hashCode() {
    
    
//		final int prime = 31;
//		int result = 1;
//		result = prime * result + age;
//		result = prime * result + ((name == null) ? 0 : name.hashCode());
//		return result;
//	}
	@Override
	public boolean equals(Object obj) {
    
    
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Customer other = (Customer) obj;
		if (age != other.age)
			return false;
		if (name == null) {
    
    
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}

ps: Compared with the manual rewriting method, the automatic rewriting method has better code robustness. It follows the principle of equals method.
Insert picture description here
Picture sourced from Shang Silicon Valley courseware PPT

Use of toString() method

Pay the code first, create a ToStringTest class

package com.atguigu.java;

public class ToStringTest {
    
    

	
	public static void main(String[] args) {
    
    
		Customer cust1 = new Customer("Tom",21);
		System.out.println(cust1);
		System.out.println(cust1.toString());
	}
}

It is found that the results of the operation are all the virtual address values ​​calculated by the hash table.

com.atguigu.java.Customer@15db9742
com.atguigu.java.Customer@15db9742

Explain that when System.out.println(cust1.toString()); is executed , click the toString method to view its source code

 public String toString() {
    
    
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
     }

And when calling System.out.println(cust1);, the parameter list is a reference to the object, here is a kind of println overload method, when you click into println

    public void println(Object x) {
    
    
       String s = String.valueOf(x);
       synchronized (this) {
    
    
           print(s);
           newLine();
       }
   }

Then click valueOf to view the source code

    public static String valueOf(Object obj) {
    
    
       return (obj == null) ? "null" : obj.toString();
   }

It was found that toString() was called at the end, because we did not rewrite toString at this time, and toString here is a method in the Object class.

Similar to the equals method, such as String, Date, File, wrapper classes, etc. all override the toString() method in the Object class. After rewriting, the output is generally the physical content of the object instead of the address value. Add follow-up code to the ToStringTest class

   	String str = new String("mm");
   	System.out.println(str);
   	Date date = new Date(3565112656L);
   	System.out.println(date);

The result of the operation is

mm
Wed Feb 11 14:18:32 CST 1970

The output is the entity content rather than the address value, so the String type and Date type actually override the toString method. Similar to equals rewriting, automatic rewriting is also supported in the eclipse environment.

If we want to rewrite the toString method in the Customer class, just open the source in the toolbar in the Customer class or click the shortcut key, then click Generate toString, and finally click the two properties in the Customer class, and the print will be automatically generated The toString method of the property in the class. (You can also click the method in the Customer class, and the toString method of the method in the print class will be automatically generated)

	@Override
	public String toString() {
    
    
		return "Customer [name=" + name + ", age=" + age + "]";
	}

Run again at this time

		System.out.println(cust1);
		System.out.println(cust1.toString());

The result is

Customer [name=Tom, age=21]
Customer [name=Tom, age=21]

You can print out the attribute values ​​in the entity content.

Guess you like

Origin blog.csdn.net/Meloneating/article/details/113806664