码迷,mamicode.com
首页 > 编程语言 > 详细

java比较器Comparator 使用

时间:2015-08-16 19:38:08      阅读:110      评论:0      收藏:0      [点我收藏+]

标签:

PresonDemo

package cn.stat.p5.person.demo;

public class PresonDemo implements Comparable  {

    private String name;
    private int age;
    
    /**
     * @param args
     */

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public void outPrint()
    {
        
        System.out.println(this.age+".."+this.name);
    }
    public PresonDemo(String name, int age) {
    
        this.name = name;
        this.age = age;
    }
    //TreeSet();为空时,实列类内部比较器
    @Override
    public int compareTo(Object o) {
        // TODO Auto-generated method stub
        PresonDemo p=(PresonDemo)o;
        if(p.age<this.age)
            return 1;
        if(p.age>this.age)
            return-1;
        return 0;
    }

}

 

比较器CompartorbyName

/**
 * 根据名子比较返回顺序
 */
package cn.stat.p6.arraylist.demo;

import java.util.Comparator;

import cn.stat.p5.person.demo.PresonDemo;

/**
 * @author Administrator
 *
 */
public class CompartorbyName implements Comparator {

    /* (non-Javadoc)
     * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
     */
    @Override
    public int compare(Object o1, Object o2) {
        // TODO Auto-generated method stub
        PresonDemo p1=(PresonDemo)o1;
        PresonDemo p2=(PresonDemo)o2;
        int temp=p1.getName().compareTo(p2.getName());
        return temp==0?p1.getAge()-p2.getAge():temp;
    }

}

TreeSetDemo

package cn.stat.p6.arraylist.demo;
import cn.stat.p5.person.demo.PresonDemo;
import java.util.Iterator;
import java.util.TreeSet;
import java.util.ArrayList;





public class TreeSetDemo {
 
    public static void main(String[] args) {
        TreeSet ts=new TreeSet(new CompartorbyName()); //比较器   
        
        ts.add(new PresonDemo("list1",2));    
        ts.add(new PresonDemo("list9",2));    
        ts.add(new PresonDemo("list7",2));    
        ts.add(new PresonDemo("list4",2));    
        ts.add(new PresonDemo("list5",2));    
        Iterator<PresonDemo> it=ts.iterator();
        while(it.hasNext())
        {
            PresonDemo p=(PresonDemo)it.next();
            System.out.println(p.getName()+"  "+p.getAge());
            
        }
    }
}

 

java比较器Comparator 使用

标签:

原文地址:http://www.cnblogs.com/zywf/p/4734694.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!