1. 程式人生 > >java bean類基本方法重寫

java bean類基本方法重寫

類基本方法(toString、hashCode、equals、compareTo)重寫

使用jar包為 apache的commons集lang包

1. toString()

實現一

public class Person {
   String name;
   int age;
   boolean smoker;

   ...

   public String toString() {
     return new ToStringBuilder(this).
       append("name", name).
       append("age", age).
       append("smoker"
, smoker). toString(); } }

實現二

public String toString() {
   return ToStringBuilder.reflectionToString(this);
 }

2. hashCode()

public class Person {
  String name;
  int age;
  boolean smoker;
  ...
  public int hashCode() {
    // you pick a hard-coded, randomly chosen, non-zero, odd number
// ideally different for each class return new HashCodeBuilder(17, 37). append(name). append(age). append(smoker). toHashCode(); } }

3. equals(Object obj)

public boolean equals(Object obj) {
  if (obj == null) { return false; }
  if (obj == this) { return true
; } if (obj.getClass() != getClass()) { return false; } MyClass rhs = (MyClass) obj; return new EqualsBuilder() .appendSuper(super.equals(obj)) .append(field1, rhs.field1) .append(field2, rhs.field2) .append(field3, rhs.field3) .isEquals(); }

4. compareTo(Object o)

public int compareTo(Object o) {
    MyClass myClass = (MyClass) o;
    return new CompareToBuilder()
      .appendSuper(super.compareTo(o)
      .append(this.field1, myClass.field1)
      .append(this.field2, myClass.field2)
      .append(this.field3, myClass.field3)
      .toComparison();
  }