> Java > java지도 시간 > 본문

Java의 Collections.sort 정렬 예에 대한 자세한 설명

Y2J
풀어 주다: 2017-05-02 11:57:32
원래의
2377명이 탐색했습니다.

Comparator는 Compare()와 Equals() 두 가지 메서드를 재정의할 수 있는 인터페이스입니다. 다음으로 이 글에서는 Java의 Collections.sort 정렬을 소개합니다.

Comparator 가격 비교 기능을 위해 Compare()와 Equals() 두 가지 메소드를 재정의할 수 있는 인터페이스입니다. null인 경우 a, b, c, d, e, f와 같은 요소의 기본 순서가 사용됩니다. g. a, b, c, d, e, f, g 입니다. 물론 숫자도 이와 같습니다.

compare(a,b) 메서드: 첫 번째 매개변수가 두 번째 매개변수보다 작거나 같거나 큰지에 따라 음의 정수, 0 또는 양의 정수를 반환합니다.

equals(obj) 메서드: 지정된 객체가 비교기이기도 하고 이 비교기와 동일한 순서를 적용하는 경우에만 true를 반환합니다.

Collections.sort(list, new PriceComparator());의 두 번째 매개변수는 int 값을 반환합니다. 이는 목록을 정렬할 순서를 정렬 메서드에 알려주는 플래그와 같습니다.

구체적인 구현 코드 방법은 다음과 같습니다.

Book 엔터티 클래스:

package com.tjcyjd.comparator; 
import java.text.DecimalFormat; 
import java.text.SimpleDateFormat; 
import java.util.GregorianCalendar; 
import java.util.Iterator; 
import java.util.TreeMap; 
/** 
 * 书实体类 
 * 
 * @author yjd 
 * 
 */ 
public class Book implements Comparable { // 定义名为Book的类,默认继承自Object类 
  public int id;// 编号 
  public String name;// 名称 
  public double price; // 价格 
  private String author;// 作者 
  public GregorianCalendar calendar;// 出版日期 
  public Book() { 
    this(0, "X", 0.0, new GregorianCalendar(), ""); 
  } 
  public Book(int id, String name, double price, GregorianCalendar calender, 
      String author) { 
    this.id = id; 
    this.name = name; 
    this.price = price; 
    this.calendar = calender; 
    this.author = author; 
  } 
  // 重写继承自父类Object的方法,满足Book类信息描述的要求 
  public String toString() { 
    String showStr = id + "\t" + name; // 定义显示类信息的字符串 
    DecimalFormat formatPrice = new DecimalFormat("0.00");// 格式化价格到小数点后两位 
    showStr += "\t" + formatPrice.format(price);// 格式化价格 
    showStr += "\t" + author; 
    SimpleDateFormat formatDate = new SimpleDateFormat("yyyy年MM月dd日"); 
    showStr += "\t" + formatDate.format(calendar.getTime()); // 格式化时间 
    return showStr; // 返回类信息字符串 
  } 
  public int compareTo(Object obj) {// Comparable接口中的方法 
    Book b = (Book) obj; 
    return this.id - b.id; // 按书的id比较大小,用于默认排序 
  } 
  public static void main(String[] args) { 
    Book b1 = new Book(10000, "红楼梦", 150.86, new GregorianCalendar(2009, 
        01, 25), "曹雪芹、高鄂"); 
    Book b2 = new Book(10001, "三国演义", 99.68, new GregorianCalendar(2008, 7, 
        8), "罗贯中 "); 
    Book b3 = new Book(10002, "水浒传", 100.8, new GregorianCalendar(2009, 6, 
        28), "施耐庵 "); 
    Book b4 = new Book(10003, "西游记", 120.8, new GregorianCalendar(2011, 6, 
        8), "吴承恩"); 
    Book b5 = new Book(10004, "天龙八部", 10.4, new GregorianCalendar(2011, 9, 
        23), "搜狐"); 
    TreeMap tm = new TreeMap(); 
    tm.put(b1, new Integer(255)); 
    tm.put(b2, new Integer(122)); 
    tm.put(b3, new Integer(688)); 
    tm.put(b4, new Integer(453)); 
    tm.put(b5, new Integer(40)); 
    Iterator it = tm.keySet().iterator(); 
    Object key = null, value = null; 
    Book bb = null; 
    while (it.hasNext()) { 
      key = it.next(); 
      bb = (Book) key; 
      value = tm.get(key); 
      System.out.println(bb.toString() + "\t库存:" + tm.get(key)); 
    } 
  } 
}
로그인 후 복사

사용자 정의 비교기 및 테스트 클래스:

package com.tjcyjd.comparator; 
import java.util.ArrayList; 
import java.util.Collections; 
import java.util.Comparator; 
import java.util.GregorianCalendar; 
import java.util.Iterator; 
import java.util.List; 
public class UseComparator { 
  public static void main(String args[]) { 
    List<Book> list = new ArrayList<Book>(); // 数组序列 
    Book b1 = new Book(10000, "红楼梦", 150.86, new GregorianCalendar(2009, 
        01, 25), "曹雪芹、高鄂"); 
    Book b2 = new Book(10001, "三国演义", 99.68, new GregorianCalendar(2008, 7, 
        8), "罗贯中 "); 
    Book b3 = new Book(10002, "水浒传", 100.8, new GregorianCalendar(2009, 6, 
        28), "施耐庵 "); 
    Book b4 = new Book(10003, "西游记", 120.8, new GregorianCalendar(2011, 6, 
        8), "吴承恩"); 
    Book b5 = new Book(10004, "天龙八部", 10.4, new GregorianCalendar(2011, 9, 
        23), "搜狐"); 
    list.add(b1); 
    list.add(b2); 
    list.add(b3); 
    list.add(b4); 
    list.add(b5); 
    // Collections.sort(list); //没有默认比较器,不能排序 
    System.out.println("数组序列中的元素:"); 
    myprint(list); 
    Collections.sort(list, new PriceComparator()); // 根据价格排序 
    System.out.println("按书的价格排序:"); 
    myprint(list); 
    Collections.sort(list, new CalendarComparator()); // 根据时间排序 
    System.out.println("按书的出版时间排序:"); 
    myprint(list); 
  } 
  // 自定义方法:分行打印输出list中的元素 
  public static void myprint(List<Book> list) { 
    Iterator it = list.iterator(); // 得到迭代器,用于遍历list中的所有元素 
    while (it.hasNext()) {// 如果迭代器中有元素,则返回true 
      System.out.println("\t" + it.next());// 显示该元素 
    } 
  } 
  // 自定义比较器:按书的价格排序 
  static class PriceComparator implements Comparator { 
    public int compare(Object object1, Object object2) {// 实现接口中的方法 
      Book p1 = (Book) object1; // 强制转换 
      Book p2 = (Book) object2; 
      return new Double(p1.price).compareTo(new Double(p2.price)); 
    } 
  } 
  // 自定义比较器:按书出版时间来排序 
  static class CalendarComparator implements Comparator { 
    public int compare(Object object1, Object object2) {// 实现接口中的方法 
      Book p1 = (Book) object1; // 强制转换 
      Book p2 = (Book) object2; 
      return p2.calendar.compareTo(p1.calendar); 
    } 
  } 
}
로그인 후 복사

위 내용은 Java의 Collections.sort 정렬 예에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!