public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String) anObject;
int n = value.length;
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}
這還有一個擴展的程序
public class EqualsTest
{
public static void main(String[] args)
{
Student s1 = new Student("zhangsan");
Student s2 = new Student("zhangsan");
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));
}
}
class Student
{
String name;
public Student(String name)
{
this.name = name;
}
public boolean equals(Object anObject)
{
if(this == anObject)
{
return true;
}
if(anObject instanceof Student)
{
Student student = (Student)anObject;
if(student.name.equals(this.name))
{
return true;
}
}
return false;
}
}
package com.answer;
public class Student {
public static void main(String[] args) {
Student s1 = new Student("zhangsan");
Student s2 = new Student("zhangsan");
System.out.println(s1 == s2); // == 比較的是內存結果
System.out.println("調用equal方法前");
System.out.println(s1.equals(s2)); // 根據重寫的equal方法進行判斷
System.out.println("調用equal方法後");
System.out.println(s1);
System.out.println(s2); // 觀察輸出 內存地址不同
}
String name;
public Student(String name)
{
this.name = name;
}
public boolean equals(Object anObject)
{
System.out.println("調用equal方法");
// this 在這裡是s1 與 s2 內存地址不同 不成立
if(this == anObject)
{
return true;
}
// s2是Student類的對象 if條件成立
if(anObject instanceof Student)
{
// 類型轉換
Student student = (Student)anObject;
// 都等於zhangsan 返回true
if(student.name.equals(this.name))
{
return true;
}
}
return false;
}
}
運行結果: