Java study notes - [== and equals the difference] Grammar

[Java Grammar 7] == and equals the difference

1, the role ==

1) at both ends of the equal sign is the basic data type of the variable , the function as the comparison values are both equal to
2) at both ends of the equal sign is a reference type variable , the effect of both the comparison stored in the stack is the same address

public class Test{
	
	public static void main(String[] args){		
		
		int age1 = 51;
		int age2 = 51;
		System.out.println(age1 == age2);//输出为true,两端变量为基础数据类型,且值相等

		String name1 = "张三";
		String name2 = "张三";
		String name3 = new String("张三");
		System.out.println(name1 == name2);//输出为true,两端变量为引用类型,且地址相同(常量池概念,详见Java语法篇6)
		System.out.println(name1 == name3);//输出为true,两端变量为引用类型,且地址不相同(详见Java语法篇6)

	}

}

2.Object equals in the role of

1) Object of the source equals
public boolean equals(Object obj){
	return (this == obj);
}
2) equals the effect of the Object

Observation source found, return the result value of this == obj, since both ends of the equal sign is a reference type, it equals the address comparison is the same

3.String class overrides the equals method

1) String class equals role

Compare the contents of two strings are equal

public class Test{
	
	public static void main(String[] args){		

		String name1 = "Tim";
		String name2 = "Tim";
		
		System.out.println(name1.equals(name2));
		System.out.println(name1.equals(new Test()));//也可以传递一个Test类,因为Test也是Object的子类,详见equals源码的参数列表
		
		String name3 = new String("Tim");
		System,out,println(name1.equals(name3));

	}

}
2) source equals method String class rewritable
public boolean equals(Object anObject){	//anObject变量储存的是上转型对象的地址
	if(this == anObject){	//比较地址是否相同
		return true;	//地址相同则此时内容必然相同
	}
	if(anObject instanceof String){	//判断anObject变量所指向对象是否为String类型
		String anotherString = (String)anObject;	//将anObject上转型对象下转型成String类
		int n = value.length;	//调用equals 方法的 String 对象的 每个字符组成的char类型数组的长度
		if(n == anotherString.value.length){	//anotherString.value.length: 每个字符组成的char类型数组的长度
			char v1[] = value;	//调用equals 方法的 String 对象的 每个字符组成的char类型数组
			char v2[] = anotherString.value;	//anObject所对应的 字符串的 字符构成的char类型数组
			int i = 0;
			while(n-- != 0){	//对应字符进行比较
				if(v1[i] != v2[i])
				return false;	//对应字符不同,则两个字符串必然不同
				i++;
			}
			return true;	//antObject指向的对象类型为String类型 且两个字符串长度相同 且对应字符都相同,则两个字符串必然相同
		}
	}
	return false; //1.anObject指向的对象不是String类型则必然不相同	2.两个长度不同则内容必然不相同
}

Finish

Released seven original articles · won praise 3 · Views 155

Guess you like

Origin blog.csdn.net/FishFinger1214/article/details/104899704