import java.util.Comparator;public class GoodsSorts implements Comparator {public int compare(Object o1,Object o2){Goods g1=(Goods)o1;Goods g2=(Goods)o2;System.out.println("调用排序方法");if(g1.getPrice()>g2.getPrice()){return -1;}else if(g1.getPrice()<g2.getPrice()){return 1;}return 0;}
}
测试类
import java.util.TreeSet;public class test63 {public static void main(String[] args){TreeSet tree=new TreeSet(new GoodsSorts());//创建一个采用默认树形自然排序的对象Goods g0=new Goods();g0.setName("剃须刀");g0.setPrice(2000.0);Goods g1=new Goods();g1.setName("西瓜");g1.setPrice(7000.0);Goods g2=new Goods();g2.setName("小刀");g2.setPrice(3000.0);Goods g3=new Goods();g3.setName("矿泉水");g3.setPrice(4000.0);tree.add(g3);tree.add(g2);tree.add(g1);tree.add(g0);for(Object o:tree){System.out.println(((Goods)o).getName()+"\t"+((Goods)o).getPrice());}System.out.println("第一个"+((Goods)tree.first()).getName());System.out.println("最后一个"+((Goods)tree.last()).getName());}
}
运行结果