实现Comparable接口,进行排序
import
java.util.ArrayList;importjava.util.Collections;importjava.util.List;publicclassBookimplementsComparable{/*编写一个类Book,具有name,price,press,author属性.然后创建5个对象放入ArrayList中,并实现按照price大小排序(使用Comparable接口排序),然后遍历ArrayList输出每个Book对象。*/privateStringname;privatefloatprice;privateStringpress;privateStringauthor;//构造方法publicBook(Stringname,floatprice,Stringpress,Stringauthor){this.name=name;this.price=price;this.press=press;this.author=author;System.out.println(name.toString());}@SuppressWarnings("unchecked")publicstaticvoidmain(String[]args){List<Book>list=newArrayList<Book>();Bookb1=newBook("java1",25f,"不错的书","LY1");Bookb2=newBook("java2",26f,"不错的书","LY2");Bookb3=newBook("java3",50f,"不错的书","LY3");Bookb4=newBook("java4",20f,"不错的书","LY4");Bookb5=newBook("java5",15f,"不错的书","LY5");list.add(b1);list.add(b2);list.add(b3);list.add(b4);list.add(b5);Collections.sort(list);for(inti=0;i<list.size();i++){Bookbook=(Book)list.get(i);System.out.println(book);}}//重写publicintcompareTo(Objectobj){Bookp=(Book)obj;if(p.price>this.price){return1;}elseif(p.price<this.price){return-1;}else{return0;}}//重写toString方法publicStringtoString(){//这上是重写了本类的toString方法,对系统自带的其它字段的toString方法无效return"书名:"+this.name+",价格:"+this.price+",说明:"+this.press+",作者:"+this.author;}}//.sort(List)方法,当然还可能使用java.util.Arrays.sort(数组),那样就必须把//list转化为数组,由于本例使用Collections.sort(List)已经足够,另一方法,大家可//以尝试自已使用.精彩推荐
热门阅读
相关文章
100多款砂锅、干锅的制作方法,用来开个小店足够了!
梦想起航
阅读86
2021-01-14
《六韬》的版本流传情况
羡慕别人
阅读182
2021-01-14
史上最全的痤疮防治手册
有梦去努力
阅读111
2021-01-14
老中医私藏的一个方子,一味中药就能赶走全身湿气
海枯石烂
阅读81
2021-01-14
审计调整怎么做
奋斗呐
阅读195
2021-01-14
失恋后,“小娇羞”或是“女汉子”,都对恢复没帮助
sunset
阅读60
2021-01-14
抗“痘”不留痕——痤疮的分级诊疗
旧夏浅入梦
阅读185
2021-01-14
早课堂1013 || 期末复习期间,这样奖励孩子,孩子学得更有劲儿!
尘世人间
阅读180
2021-01-14