TreeSet,compare方法重写

TreeSet带有排序功能,实现TreeSet,对所添加的对象要重写compareTo(),equals和hashCode.

此例重写compareTo()

import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Administrator
 */
public class CompareTest {
    public static void main(String[] args){
        Set dog = new TreeSet<Dog>();
        dog.add(new Dog(3, "huahua"));
        dog.add(new Dog(5, "baibai"));
        dog.add(new Dog(8, "xiaohu"));

        for(Iterator it = dog.iterator();it.hasNext();){
            System.out.println(it.next());
        }
    }

}
class Dog implements Comparable<Object>{
    int age;
    String name;

    public Dog(int age, String name) {
        this.age = age;
        this.name = name;
    }

    public int compareTo(Object o) {
        Dog d = (Dog)o;
        if (d.age<=this.age)
        return 1;
        else return 0;


    }
    @Override
    public String toString(){
       return this.name+this.age;
    }
}

转载于:https://www.cnblogs.com/sail_out_to_sea/archive/2010/10/30/1865013.html

猜你喜欢

转载自blog.csdn.net/weixin_34290096/article/details/93413366
今日推荐