Java實現程式碼-比較器
阿新 • • 發佈:2018-12-25
如下程式碼:
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) { List<company> list = new ArrayList<company>(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())); } }