Collections 给数组排序

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  实现了排序
 

 

 

你可能感兴趣的:(java,C++,c,C#)