Customer:
1 public class Customer implements Comparable{ 2 private Integer customerId; 3 private String customerName; 4 5 public Integer getCustomerId() { 6 return customerId; 7 } 8 public void setCustomerId(Integer customerId) { 9 this.customerId = customerId; 10 } 11 public String getCustomerName() { 12 return customerName; 13 } 14 public void setCustomerName(String customerName) { 15 this.customerName = customerName; 16 } 17 public Customer(Integer customerId, String customerName) { 18 this.customerId = customerId; 19 this.customerName = customerName; 20 } 21 @Override 22 public String toString() { 23 return "Customer [customerId=" + customerId + ", customerName=" 24 + customerName + "]"; 25 } 26 public Customer() { 27 } 28 @Override 29 public int hashCode() { 30 final int prime = 31; 31 int result = 1; 32 result = prime * result + customerId; 33 result = prime * result 34 + ((customerName == null) ? 0 : customerName.hashCode()); 35 return result; 36 } 37 @Override 38 public boolean equals(Object obj) { 39 if (this == obj) 40 return true; 41 if (obj == null) 42 return false; 43 if (getClass() != obj.getClass()) 44 return false; 45 Customer other = (Customer) obj; 46 if (customerId != other.customerId) 47 return false; 48 if (customerName == null) { 49 if (other.customerName != null) 50 return false; 51 } else if (!customerName.equals(other.customerName)) 52 return false; 53 return true; 54 } 55 //TreeSet类按照compareTo方法比较返回 56 //按id或name排序 57 @Override 58 public int compareTo(Object o) { 59 if(o instanceof Customer){ 60 Customer c=(Customer) o; 61 //给整体添加'-'号改变正/逆序 62 // return this.customerId-c.customerId; 63 return this.customerName.compareTo(c.customerName); 64 } 65 return 0; 66 } 67 }
CustomerComparator:
1 import java.util.Comparator; 2 public class CustomerComparator implements Comparator{ 3 @Override 4 public int compare(Object o1, Object o2) { 5 if(o1 instanceof Customer && o2 instanceof Customer){ 6 Customer cust1=(Customer) o1; 7 Customer cust2=(Customer) o2; 8 return -cust1.getCustomerName().compareTo(cust2.getCustomerName()); 9 } 10 return 0; 11 } 12 }