如下代码:
import java.util.*;
class company implements Comparable {
private String name;
private String technology;
private double marketValue;
private double salary;
private int city;
public company(String name, String technology, double marketValue, double salary, int city) {
super();
this.name = name;
this.technology = technology;
this.marketValue = marketValue;
this.salary = salary;
this.city = city;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name
* the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the technology
*/
public String getTechnology() {
return technology;
}
/**
* @param technology
* the technology to set
*/
public void setTechnology(String technology) {
this.technology = technology;
}
/**
* @return the marketValue
*/
public double getMarketValue() {
return marketValue;
}
/**
* @param marketValue
* the marketValue to set
*/
public void setMarketValue(double marketValue) {
this.marketValue = marketValue;
}
/**
* @return the salary
*/
public double getSalary() {
return salary;
}
/**
* @param salary
* the salary to set
*/
public void setSalary(double salary) {
this.salary = salary;
}
/**
* @return the city
*/
public int getCity() {
return city;
}
/**
* @param city
* the city to set
*/
public void setCity(int city) {
this.city = city;
}
@Override
public int compareTo(Object o) {
// TODO Auto-generated method stub
company comp = (company) o;
int result = comp.getSalary() > salary ? 1 : (comp.getSalary() == salary ? 0 : -1);
return result;
}
public String toString() {
return "\r\tnum:" + name + " name:" + name + "\r";
}
}
public class 比较器 {
public static void main(String[] args) {
Listlist = new ArrayList(10);
list.add(new company("xx", "11", 1, 12, 1));
list.add(new company("yy", "11", 1, 13, 1));
list.add(new company("zz", "11", 1, 12, 1));
Collections.sort(list); // 内部比较器:要排序的对象实现Comparable接口,可以对自身进行比较
System.out.println(Arrays.toString(list.toArray()));
}
}