1:
package com.aff.equals; public class TestOrder { public static void main(String[] args) { Order o1 = new Order(1001, "AA"); Order o2 = new Order(1001, "AA"); System.out.println(o1 == o2);// false System.out.println(o1.equals(o2));// false--->true 重写equals方法后 } } class Order { private int orderId; private String orderName; public int getOrderId() { return orderId; } public void setOrderId(int orderId) { this.orderId = orderId; } public String getOrderName() { return orderName; } public void setOrderName(String orderName) { this.orderName = orderName; } public Order(int orderId, String orderName) { super(); this.orderId = orderId; this.orderName = orderName; } //比较两个order对象的属性是否完全相同,相同的话返回true public boolean equals(Object obj) { if (this == obj) { return true; } else if (obj instanceof Order) { Order o1 = (Order) obj; return this.orderId == o1.orderId && this.orderName.equals(o1.orderName); } else { return false; } } }
输出结果:
false
true
2:
package com.aff.equals; public class TestMyDate { public static void main(String[] args) { MyDate m1 = new MyDate(12, 3, 2012); MyDate m2 = new MyDate(12, 3, 2012); if (m1 == m2) { System.out.println("m1==m2"); } else { System.out.println("m1!=m2"); } // boolean java.lang.Object.equals(Object obj) // 调用的为Object里面的equals方法,需要重写equals方法 if (m1.equals(m2)) { System.out.println("m1 is equals m2"); } else { System.out.println("m1 is not equal to m2"); } } } class MyDate { private int day; private int month; private int year; public MyDate(int day, int month, int year) { super(); this.day = day; this.month = month; this.year = year; } public int getDay() { return day; } public void setDay(int day) { this.day = day; } public int getMonth() { return month; } public void setMonth(int month) { this.month = month; } public int getYear() { return year; } public void setYear(int year) { this.year = year; } //手动写的 public boolean equals(Object obj) { if (this == obj) { return true; } else if (obj instanceof MyDate) { MyDate m = (MyDate) obj; return this.day == m.day && this.month == m.month && this.year == m.year; } else { return false; } } }
输出结果:
m1!=m2
m1 is equals m2