在Object這個類別裡面equals方法預設的實作是當前物件參考和你要比較的物件的參考是不是同一個物件。 equals方法的回傳值是boolean j2sdk提供了一些類,如:String Data等重寫了equals方法範例程式:
Java程式碼
public class TestEquals { public static void main(String[] args) { Cat c1 = new Cat(1, 2, 3); Cat c2 = new Cat(1, 2, 6); System.out.println(c1 == c2); //false System.out.println(c1.equals(c2)); //false String s1 = new String("hello"); String s2 = new String("hello"); String m1 = "hello"; String m2 = "hello"; System.out.println(s1 == s2); //false System.out.println(m1 == m2); //true System.out.println(s1.equals(s2)); //true } } //实体类 class Cat { int color; int height, weight; public Cat(int color, int height, int weight) { this.color = color; this.height = height; this.weight = weight; } //重写equals方法 public boolean equals(Object obj) { if(obj == null) return false; else { if(obj instanceof Cat) { Cat c = (Cat)obj; if(c.color == this.color && c.height == this.height && c.weight == this.weight) { return true; } } } return false; } }
化用相關文章類型PHP中文網!