Java容器排序的方法
来源:互联网 发布:网络杀机 百度云 编辑:程序博客网 时间:2024/06/07 05:58
转自:http://blog.csdn.net/shirenfeigui/article/details/39051741
首先说一下排序的返回值的含义。对于参与比较的两个Object,o1和o2,如果函数的返回值为正值,把o1排在o2后面;返回值为负值,把o1排在o2前面。如果返回值是0,按照容器之前的顺序排列。在compareTo中,this相当于o1,传入的Object相当于o2
第一种方法:对于要排序的类实现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;
- }
- }
- };
- }
阅读全文
0 0
- Java容器排序的方法
- java容器的排序
- java的容器排序
- java自定义容器排序的两种方法
- Java容器Treeset的两种排序方法
- Collections容器的排序方法
- java 容器排序
- Java 容器排序
- JAVA排序的方法
- java的排序方法
- java排序的方法
- java-容器-collection的sort方法
- Java中Map容器的遍历方法
- java-容器-collection的sort方法
- 对容器的排序
- set容器的排序
- STL 容器的排序
- 容器的排序-1
- 使用OpenCL+OpenCV实现图像卷积(三)
- MultiSplitPane 拖拽到边缘反弹问题解决
- 递归的java简单实现
- php_文件操作
- unity响应键盘的组合键
- Java容器排序的方法
- live555 linux 编译
- 蓝桥杯 ALGO-147 算法训练 4-3水仙花数
- Ubuntu简单命令集
- 蓝桥杯 ALGO-146 算法训练 4-2找公倍数
- Nginx 常用模块
- 蓝桥杯 ALGO-145 算法训练 4-1打印下述图形
- 香港独立服务器出现访问速度慢的几大原因及简单的处理
- 蓝桥杯 ALGO-141 算法训练 P1102