首页>代码>java LIST用法实例>/c15/ComparatorDemo/Chart.java
//==============================================================
// 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日
最近浏览更多
udryhefb 2023年6月12日
暂无贡献等级
heqian  LV16 2022年12月5日
ewan007  LV29 2022年7月8日
liuwenlong  LV20 2019年12月19日
xp95323  LV14 2019年11月30日
只要有你  LV8 2019年10月3日
dongzhan  LV12 2019年3月11日
fly666  LV11 2018年9月27日
agaciki123  LV12 2018年9月19日
xp9522  LV9 2018年8月13日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友