java学习(123):treeset排序集合
生活随笔
收集整理的這篇文章主要介紹了
java学习(123):treeset排序集合
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
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("調(diào)用排序方法");if(g1.getPrice()>g2.getPrice()){return -1;}else if(g1.getPrice()<g2.getPrice()){return 1;}return 0;}
}
測(cè)試類
import java.util.TreeSet;public class test63 {public static void main(String[] args){TreeSet tree=new TreeSet(new GoodsSorts());//創(chuàng)建一個(gè)采用默認(rèn)樹形自然排序的對(duì)象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("第一個(gè)"+((Goods)tree.first()).getName());System.out.println("最后一個(gè)"+((Goods)tree.last()).getName());} }運(yùn)行結(jié)果
總結(jié)
以上是生活随笔為你收集整理的java学习(123):treeset排序集合的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: ntsd的两个技巧
- 下一篇: java学习(81):静态代码块