//==============================================================
// Chart.java - Sample data object with Comparator implementation
//
// Java学习源代码检索系统 Ver 1.0 20031015 免费正式版
// 版权所有: 中国IT认证实验室(www.ChinaITLab.com)
// 程序制作: ChinaITLab网校教研中心
// 主页地址: www.ChinaITLab.com 中国IT认证实验室
// 论坛地址: bbs.chinaitlab.com
// 电子邮件: Java@ChinaITLab.com
//==============================================================
import java.util.Comparator;
public class Chart implements Comparable {
// Constants
final static int BYNUMBER = 1;
final static int BYNAME = 2;
final static int BYSCALE = 3;
public int number;
public String name;
public long scale;
public Chart(int number, String name, long scale) {
this.number = number;
this.name = name;
this.scale = scale;
}
public int compareTo(Object o) {
Chart other = (Chart)o;
return name.compareTo(other.name);
}
public String toString() {
return number + " " + name + " 1:" + scale;
}
// Comparator "factory" methods
public static final Comparator byNumber() {
return new ChartComparator(BYNUMBER);
}
public static final Comparator byName() {
return new ChartComparator(BYNAME);
}
public static final Comparator byScale() {
return new ChartComparator(BYSCALE);
}
// Private inner Comparator class
private static class ChartComparator implements Comparator {
private int compType; // Type of comparison to perform
// Constructor saves comparison type identifier
ChartComparator(int compType) {
this.compType = compType; // BYNUMBER, BYNAME, or BYSCALE
}
// Implement the Comparator interface's method
public int compare(Object o1, Object o2) {
Chart c1 = (Chart)o1; // Type cast objects to Charts
Chart c2 = (Chart)o2;
switch (compType) {
case BYNUMBER:
return (c1.number < c2.number ? -1 :
(c1.number == c2.number ? 0 : 1));
case BYNAME:
return c1.name.compareTo(c2.name);
case BYSCALE:
return (c1.scale < c2.scale ? -1 :
(c1.scale == c2.scale ? 0 : 1));
default:
return 0; // Satisfy compiler; can't happen
}
}
} // private inner class
} // Chart class
最近下载更多
zhaoyuzhang1991 LV10
2016年4月6日
AXIN LV36
2014年2月25日

最近浏览