java 排序的容器_java自定义容器排序的两种方法

首先说一下排序的返回值的含义。对于参与比较的两个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 s1Set = new ArrayList();

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 s2Set = new ArrayList();

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 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;

}

}

};

}

原文:http://blog.csdn.net/shirenfeigui/article/details/39051741

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值