欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java中实现Comparator接口和用法实例(简明易懂)

程序员文章站 2024-03-04 16:14:59
在java中,如果要对集合对象或数组对象进行排序,需要实现comparator接口以达到我们想要的目标。 接下来我们模拟下在集合对象中对日期属性进行排序 一、实体类st...

在java中,如果要对集合对象或数组对象进行排序,需要实现comparator接口以达到我们想要的目标。

接下来我们模拟下在集合对象中对日期属性进行排序

一、实体类step

package com.ljq.entity;


/**
 * 运号单流程
 * 
 * @author administrator
 * 
 */
public class step{
  /** 处理时间 */
  private string accepttime = "";
  /** 快件所在地点 */
  private string acceptaddress = "";

  public step() {
    super();
  }

  public step(string accepttime, string acceptaddress) {
    super();
    this.accepttime = accepttime;
    this.acceptaddress = acceptaddress;
  }

  public string getaccepttime() {
    return accepttime;
  }

  public void setaccepttime(string accepttime) {
    this.accepttime = accepttime;
  }

  public string getacceptaddress() {
    return acceptaddress;
  }

  public void setacceptaddress(string acceptaddress) {
    this.acceptaddress = acceptaddress;
  }

}

二、实现comparator接口

package com.ljq.entity;

import java.util.comparator;
import java.util.date;

import com.ljq.util.utiltool;

/**
 * 对step类进行排序
 * 
 * @author administrator
 *
 */
public class stepcomparator implements comparator<step>{

  /**
   * 如果o1小于o2,返回一个负数;如果o1大于o2,返回一个正数;如果他们相等,则返回0;
   */
  @override
  public int compare(step o1, step o2) {
    date accepttime1=utiltool.strtodate(o1.getaccepttime(), null);
    date accepttime2=utiltool.strtodate(o2.getaccepttime(), null);
    
    //对日期字段进行升序,如果欲降序可采用before方法
    if(accepttime1.after(accepttime2)) return 1;
    return -1;
  }

}

三、测试

package junit;

import java.util.collection;
import java.util.collections;
import java.util.list;

import org.junit.test;


public class stepcomparatortest {

  @test
  public void sort() throws exception{
    list<step> steps=new arraylist<step>;
    //对集合对象进行排序
     stepcomparator comparator=new stepcomparator();
    collections.sort(steps, comparator);
    if(steps!=null&&steps.size()>0){
      for(step step:steps){
        system.out.println(step.getacceptaddress());
        system.out.println(step.getaccepttime());
      }
    }

  }
}