Problems
1) Inspect all the properties of equals method:
package certification.collections;
class WrongMoney {
}
class Money extends Object {
private int id;
private String currency;
public Money(int id, String currency) {
super();
this.id = id;
this.currency = currency;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (null != obj) {
if (obj instanceof Money) {
Money money = (Money) obj;
if (this.getId() == money.getId() && this.getCurrency().equals(money.getCurrency())) {
return true;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
}
}
public class TestEquals {
public static void main(String[] args) {
Money m1 = new Money(1, "INR");
Money m2 = new Money(1, "INR");
Money m3 = new Money(1, "INR");
WrongMoney wrongMoney = new WrongMoney();
if (m1.equals(m2)) {
System.out.println("They are same");
} else {
System.out.println("Not same");
}
if (m1.equals(wrongMoney)) {
System.out.println("They are same");
} else {
System.out.println("Not same");
}
if (m1.equals(m1)) {
System.out.println("my equals is reflexive");
}
if (m1.equals(m2) && m2.equals(m1)) {
System.out.println("my equals is symmetric");
}
if (m1.equals(m2) && m2.equals(m3)) {
if (m1.equals(m3)) {
System.out.println("my equals is transitive");
}
}
}
}
Last updated