博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java自定义容器排序的两种方法
阅读量:4067 次
发布时间:2019-05-25

本文共 1917 字,大约阅读时间需要 6 分钟。

首先说一下排序的返回值的含义。对于参与比较的两个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://kymji.baihongyu.com/

你可能感兴趣的文章
OS + Unix IBM Aix basic / topas / nmon / filemon / vmstat / iostat / sysstat/sar
查看>>
monitorServer nagios / cacti / tivoli / zabbix / SaltStack
查看>>
my ReadMap subway / metro / map / ditie / gaotie / traffic / jiaotong
查看>>
OS + Linux DNS Server Bind
查看>>
web test flow
查看>>
web test LoadRunner SAP / java / Java Vuser / web_set_max_html_param_len
查看>>
OS + UNIX AIX command
查看>>
OS + UNIX AIX performance
查看>>
OS + UNIX AIX Tools
查看>>
my ReadBook_liutongjingjixue / circulation economics
查看>>
my ReadBook_wangluoyingxiaoyucehua / network marketing / wangluoyingxiao
查看>>
db base database
查看>>
Spring2.5+MINA2搭建Socket Server
查看>>
jcharts画线图,饼图和柱状图
查看>>
监控服务器端口,Down掉会自动重启,并发送邮件 Linux Shell
查看>>
Git提交错误:RPC failed; result=22, HTTP code = 411
查看>>
Druid使用ConfigFilter
查看>>
Elicpse使用技巧-打开选中文件文件夹或者包的当前目录
查看>>
eclips 运行项目内存不足的解决方案
查看>>
linux 挂载盘阵 smb
查看>>