equal 和== 详解

首先试比较下例:

String A=new String(“hello”);

String B=new String(“hello”);

A==B(此时程序返回为FALSE)

因为此时AB中存的是不同的对象引用。 

附加知识:

字符串类为JAVA中的特殊类,String中为final类,一个字符串的值不可重复。因此在JAVA VM(虚拟机)中有一个字符串池,专门用来存储字符串。如果遇到String a=”hello”时(注意没有NEW,不是创建新串),系统在字符串池中寻找是否有”hello”,此时字符串池中没有”hello”,那么系统将此字符串存到字符串池中,然后将”hello”在字符串池中的地址返回a。如果系统再遇到String b=”hello”,此时系统可以在字符串池中找到 “hello”。则会把地址返回b,此时a与b为相同。

String a=”hello”;

System.out.println(a==”hello”);

系统的返回值为true

故如果要比较两个字符串是否相同(而不是他们的地址是否相同)。可以对a调用equal:

System.out.println(a.equal(b));

equal用来比较两个对象中字符串的顺序。 

a.equal(b)是a与b的值的比较。

注意下面程序:

student a=new student(“LUCY”,20);

student b=new student(“LUCY”,20);

System.out.println(a==b);

System.out.println(a.equal(b));

此时返回的结果均为false。

因为Student继承的是Object的equals()方法,此时toString()等于== 

为了实现对象的比较需要覆盖equals(加上这个定义,返回ture或false)

以下为实现标准equals的流程:

public boolean equals(Object o){

  if (this==o) return trun;  //此时两者相同
  if (o==null) return false;

  if (! o instanceof strudent) return false;  //不同类

  studeng s=(student)o; //强制转换

  if (s.name.equals(this.name)&&s.age==this.age) return true;

else return false;

}


你可能感兴趣的:(equal 和== 详解)