您的位置:首页 > 编程语言 > Java开发

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

2014-09-04 14:19 218 查看
首先说一下排序的返回值的含义。对于参与比较的两个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;
}
}
};

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐