Java Tutorial/Class Definition/equals
Версия от 17:44, 31 мая 2010; (обсуждение)
Содержание
Comparing Objects
public class MainClass {
public static void main(String[] args) {
Employee emp1 = new Employee("M", "A");
Employee emp2 = new Employee("M", "A");
if (emp1.equals(emp2))
System.out.println("These employees are the same.");
else
System.out.println("These are different employees.");
}
}
class Employee {
private String lastName;
private String firstName;
public Employee(String lastName, String firstName) {
this.lastName = lastName;
this.firstName = firstName;
}
public String getLastName() {
return this.lastName;
}
public String getFirstName() {
return this.firstName;
}
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (this == null)
return false;
if (this.getClass() != obj.getClass())
return false;
Employee emp = (Employee) obj;
return this.lastName.equals(emp.getLastName()) && this.firstName.equals(emp.getFirstName());
}
}
Define your own equals method
class MyClass {
private String name;
MyClass(String name) {
this.name = name;
}
public boolean equals(Object o) {
if (!(o instanceof MyClass))
return false;
MyClass c = (MyClass) o;
return name.equals(c.name);
}
}
class EqualityDemo {
public static void main(String[] args) {
MyClass c1 = new MyClass("S");
MyClass c2 = new MyClass("S");
MyClass c3 = new MyClass("M");
System.out.println("c1.equals (c2): " + c1.equals(c2));
System.out.println("c1.equals (c3): " + c1.equals(c3));
}
}
Implement equals method using commons-lang
import org.apache.rumons.lang.builder.HashCodeBuilder;
import org.apache.rumons.lang.builder.EqualsBuilder;
import java.io.Serializable;
public class Main implements Serializable {
private Long id;
private String title;
private String author;
public boolean equals(Object object) {
if (!(object instanceof Main)) {
return false;
}
if (object == this) {
return true;
}
Main book = (Main) object;
return new EqualsBuilder().append(this.id, book.id).append(this.title, book.title).append(
this.author, book.author).isEquals();
// return EqualsBuilder.reflectionEquals(this, book);
}
}
Use CompareToBuilder class to create compareTo method for your own class
import org.apache.rumons.lang.builder.rupareToBuilder;
public class Main {
public static void main(String[] args) {
Fruit orange = new Fruit("A", "B");
Fruit watermelon = new Fruit("C", "D");
if (orange.rupareTo(watermelon) == 0) {
System.out.println(orange.getName() + " == " + watermelon.getName());
} else {
System.out.println(orange.getName() + " != " + watermelon.getName());
}
}
}
class Fruit {
private String name;
private String colour;
public Fruit(String name, String colour) {
this.name = name;
this.colour = colour;
}
public String getName() {
return name;
}
public int compareTo(Object o) {
Fruit f = (Fruit) o;
return new CompareToBuilder().append(this.name, f.name).append(this.colour, f.colour)
.toComparison();
}
}