关于equals()和==的使用区别
一、基本使用方法说明
[1]对于String类而言,==是用来比较栈中的内存地址的,而equals是用来比较两个字符串所包含的内容是否相同。
[2]对于非String类而言,==与equals()都是用来比较内存地址的。
s1 = new String("abc"); Student s1 = new Student("abc");
s2 = new String("abc"); Student s2 = new Student("abc");
s3 = "abc";
s4 = "abc";
s3 == s4为true
s1 == s2为false; s1 ==s2 为false
s1equals()s2为true s1 equals()s2为false
解释:对于两个类来说,s1与s2均为新创建的对象,因此变量地址是不一样的,而变量内容是一样的。
对于String类而言,类中重写了equals()方法,用于比较字符串的内容。
但如果在student类中加上s1 = s2,则输出结果均为false,因为此时两个地址相同
对于s3和s4而言,两者均为"abc"创造的对象,所以地址相同
二、具体运用环境
1、java中的八种基本类型比较大小只能使用==,不能使用equals();编译出错
public class TestEquals {
public static void main(String[] args)
{
int a = 3;
int b = 4;
int c = 3;
System.out.println(a == b);//结果是false
System.out.println(a == c);//结果是true
System.out.println(a.equals(c));//错误,编译不能通过,equals方法
//不能运用与基本类型的比较
2、对于基本类型的包装类型,如Boolean、Character、Byte、Shot、Integer、Long、Float、Double,他们的用法与String类一样,==用来比较地址,而equals()用来比较内容
public class TestEquals {
public static void main(String[] args)
{
Integer n1 = new Integer(30);
Integer n2 = new Integer(30);
Integer n3 = new Integer(31);
System.out.println(n1 == n2);//结果是false
System.out.println(n1 == n3);// 结果显示false
System.out.println(n1.equals(n2));//结果是true
System.out.println(n1.equals(n3));//结果是false
}
}
其他的Double、Character、Float等也一样
3、