Java自定义类型的排序
2015-06-05 14:11
281 查看
首先说一下排序的返回值的含义。对于参与比较的两个Object,o1和o2,如果函数的返回值为正值,把o1排在o2后面;返回值为负值,把o1排在o2前面。如果返回值是0,按照容器之前的顺序排列。在compareTo中,this相当于o1,传入的Object相当于o2
第一种方法:对于要排序的类实现Comparable接口,适用于只需要一种排序方式的情况。
第二种方法:覆盖Comparator中的compare方法,适用于需要多种排序方式的情况。
转载自:/article/8260267.html
第一种方法:对于要排序的类实现Comparable接口,适用于只需要一种排序方式的情况。
package sort; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; //采用实现Comparable接口的方法实现排序 class S1 implements Comparable{ int x; int y; S1(int x, int y){ this.x = x; this.y = y; } //实现排序方法。先比较x,如果相同比较y @Override public int compareTo(Object o) { S1 obj = (S1) o; if(x != obj.x) { return x - obj.x; } return y - obj.y; } //重写toStirng方法,改变println时的显示效果 public String toString(){ return "("+x+", "+y+")"; } } public class Sort1 { public static void main(String[] args) { List<S1> s1Set = new ArrayList<S1>(); S1 s1 = new S1(3,5); S1 s2 = new S1(2,5); S1 s3 = new S1(2,2); s1Set.add(s1); s1Set.add(s2); s1Set.add(s3); //对容器进行排序的函数 Collections.sort(s1Set); Iterator it = s1Set.iterator(); while(it.hasNext()) { System.out.println(it.next()); } } }
第二种方法:覆盖Comparator中的compare方法,适用于需要多种排序方式的情况。
package sort; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; class S2{ int x; int y; S2(int x, int y){ this.x = x; this.y = y; } //重写toStirng方法,改变println时的显示效果 public String toString(){ return "("+x+", "+y+")"; } } public class Sort2 { public static void main(String[] args) { List<S2> s2Set = new ArrayList<S2>(); S2 s1 = new S2(3,5); S2 s2 = new S2(4,5); S2 s3 = new S2(4,2); s2Set.add(s1); s2Set.add(s2); s2Set.add(s3); //对容器进行排序的函数 Collections.sort(s2Set,c); Iterator it = s2Set.iterator(); while(it.hasNext()) { System.out.println(it.next()); } } static Comparator<S2> c = new Comparator(){ public int compare(Object a0, Object a1) { S2 s1 = (S2) a0; S2 s2 = (S2) a1; if(s1.x != s2.x) { return s1.x - s2.x; } else { return s1.y - s2.y; } } }; }
转载自:/article/8260267.html
相关文章推荐
- java弹球
- Spring 监听ContextLoaderListener
- 【汇总】eclipse相关问题
- spring security3的filter链
- Java偏向锁
- Spring+Quartz实现定时任务的配置方法(插曲)
- 20150605面试汇总--jdk常用package
- eclipse tab空格设置
- Struts2学习笔记1
- 用java抓取cnproxy代理服务器地址
- 在Spring3中使用注解(@Scheduled)创建计划任务
- struts2 .do .action等后缀访问问题
- Maven的Setting.xml配置默认JDK,本地仓库,repositories
- java环境变量 maven 环境变量配置
- 06-图6. 公路村村通(30) java
- struts2入门实例
- Eclipse快捷键 10个最有用的快捷键
- 一个不错的地址:包含spring框架、其他框架 等java相关的
- J2SE使用JAVA原生代码直接调用WebService Result
- Java语言描述:分支限界法之单源最短路径问题(全网独家)