使用CompareToBuilder类库创建compareTo方法

import org.apache.commons.lang.builder.CompareToBuilder;   
  
public class Main {   
  public static void main(String[] args) {   
    Fruit orange = new Fruit("A", "B");   
    Fruit watermelon = new Fruit("C", "D");   
  
    if (orange.compareTo(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();   
  }   
}   

你可能感兴趣的:(apache,C++,c,C#,F#)