标签:
Customer:
public class Customer implements Comparable{
private Integer customerId;
private String customerName;
public Integer getCustomerId() {
return customerId;
}
public void setCustomerId(Integer customerId) {
this.customerId = customerId;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public Customer(Integer customerId, String customerName) {
this.customerId = customerId;
this.customerName = customerName;
}
@Override
public String toString() {
return "Customer [customerId=" + customerId + ", customerName="
+ customerName + "]";
}
public Customer() {
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + customerId;
result = prime * result
+ ((customerName == null) ? 0 : customerName.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Customer other = (Customer) obj;
if (customerId != other.customerId)
return false;
if (customerName == null) {
if (other.customerName != null)
return false;
} else if (!customerName.equals(other.customerName))
return false;
return true;
}
//TreeSet类按照compareTo方法比较返回
//按id或name排序
@Override
public int compareTo(Object o) {
if(o instanceof Customer){
Customer c=(Customer) o;
//给整体添加‘-‘号改变正/逆序
// return this.customerId-c.customerId;
return this.customerName.compareTo(c.customerName);
}
return 0;
}
}
CustomerComparator:
import java.util.Comparator;
public class CustomerComparator implements Comparator{
@Override
public int compare(Object o1, Object o2) {
if(o1 instanceof Customer && o2 instanceof Customer){
Customer cust1=(Customer) o1;
Customer cust2=(Customer) o2;
return -cust1.getCustomerName().compareTo(cust2.getCustomerName());
}
return 0;
}
}
标签:
原文地址:http://www.cnblogs.com/jfl-xx/p/4707643.html