Briefly distinguish on java of equals and ==

1 == Comparison sides are the same,
A comparison when the object on the basis of the type, if the values are equal, returns true, otherwise to false;.
. B when the object is a reference type of comparison, the comparison is a reference type ( object) address, if the two addresses are the same (that is, the same object) returns true, otherwise false;

Comparative 2.equals sides are the same,
A. First, equals method of Object already defined and implemented in the base class, which is the comparison of two objects d hashcode (at the address) is the same, if the same return ture, otherwise false.
b. In general, the normal default inherit the Object class, the class's equals and Object function is the same, but due to various specific meaning, Object equals the ratio of the mode can not meet the demand ratio, so that we may need override equals method, but in java String class to override the equals method of the Object class.
c.String class equals comparison is whether the other two string contents (value attribute) of the sequence of characters, if the same return ture, otherwise it is false.

As an example of how to override the equals of: Joe Smith Joe Smith students in 101 classes, and now he go after the 102 class called Zhang renamed IV. As a student class is that they are the same person, we judge the criteria [ID number or student number (Student ID premise unchanged)]. At this time, it equals student class method than when it can not be compared to the address. But their ID number, this is the only constant.

Code Description:

	public static void main(String[] args) {
		
		Object obj1 = new Object();
		Object obj2 = new Object();
		System.out.println(obj1 == obj2);//false,地址不一样不是同一个对象
		System.out.println(obj1.equals(obj2));//false,Object比较的是两个对象的地址
		
		Person2 person = new Person2("张三",11,1);
		Person2 person2 = new Person2("小张",11,1);
		System.out.println(person == person2);//false,不是同一个对象,但是业务意义上是同一个人,所以需要改写equals
		System.out.println(person.equals(person2));//true,id相同,则认为两个人对象内容相同
		
		String s1 = new String("李四");
		String s2 = new String("李四");
		System.out.println(s1==s2);//false,两个字符串不是同一个对象
		System.out.println(s1.equals(s2));//true,两个字符串内容相同,因为String类改写了Object的equals方法,以内容是否相同为最终标准

	}
	
class Person2{
	int id;
	String name;
	int age;
	
	public Person2() {};
	public Person2(String name,int age,int id) {
		this.age = age;
		this.name = name;
		this.id = id;
	}
	
	public boolean equals(Object obj) {//重写equals方法
		if(obj == null) {
			return false;
		}else{
			if(obj instanceof Person2) {
				Person2 c = (Person2) obj;
				if(c.id == this.id) {
					return true;
				}
			}
		}
		return false;
	}
	public String toString() {
		return name+",age:"+age;
	}

Output:
false
false
false
to true
false
to true

Published 37 original articles · won praise 29 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_42755868/article/details/103031657