Collections 给数组排序

本文介绍了一个使用Java实现的VO类及自定义比较器MyComparator,通过实现Comparator接口并重写compare方法来完成对VO对象列表的排序。示例中展示了如何使用Collections.sort方法结合自定义比较器对包含字符和整数的VO对象进行排序。
public class VO {
	private char key;
	private int value;
	public VO(char key, int value) {
		super();
		this.key = key;
		this.value = value;
	}
	public int getValue() {
		return value;
	}
	public char getKey() {
		return key;
	}	
}

 

import java.util.Comparator;

public class MyComparator  implements Comparator<VO> {

	public int compare(VO vo1, VO vo2) {
		// TODO Auto-generated method stub
		if(vo1.getValue()<vo2.getValue()){
		        return -1;
		}else if(vo1.getValue()==vo2.getValue()){
			return 0;
		}else{
			return 1;
		}
	}
}

 

 

package auto;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.ArrayList;

public class CollectionsTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
//		List<Integer> list=new ArrayList<Integer>();  //基本数据的比较
//		list.add(3);
//		list.add(2);
//		list.add(1);
//		Collections.sort(list);
//		for(Integer i:list){
//			System.out.print(i);  //123
//		}
		
		
//		VO vo=new VO('a',3);
//		VO vo2=new VO('b',5);
//		VO vo3=new VO('c',1);
//		List<VO> list=new ArrayList<VO>(); 
//		list.add(vo);
//		list.add(vo2);
//		list.add(vo3);
//		Collections.sort(list);                   //此方法不能用于比较对象参数
//		for(VO temp:list){
//			System.out.print(temp.getValue()); 

		
		
		VO vo=new VO('a',3);
		VO vo2=new VO('b',5);
		VO vo3=new VO('c',1);
		List<VO> list=new ArrayList<VO>(); 
		list.add(vo);
		list.add(vo2);
		list.add(vo3);
		MyComparator m=new MyComparator();           //MyComparator实习了Comparator<VO>借口,覆写其中的
		                                             //compare方法 ,用于比较数组中的参数
		Collections.sort(list, m);               
		for(VO temp:list){
			System.out.print(temp.getKey()); 
			System.out.print(temp.getValue()); 
	}

}
}  //c1a3b5  实现了排序
 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值