import java.util.Comparator;
/**
*
* @author daniel zhou
*
*/
public class MyComparator implements Comparator<Integer>{
@Override
public int compare(final Integer o1, final Integer o2) {
final Integer x=(Integer)o1;
final Integer y=(Integer)o2;
if (x>y) {
return 1;
}else{
return 0;
}
}
} 或者将比较器写为一个内部类也是可以的,代码如下:/**
*
*/
package math;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Random;
/**
* @author daniel zhou
*
*/
public class RandomTest {
/**
* Create 100 random numbers, get min & max number, sun up the number of >50
* @param args
*/
public static void main(String[] args) {
//create 100 random number
ArrayList<Integer> arraylist=new ArrayList<Integer>();
Random rand=new Random();
int total_50=0;
for (int i = 0; i < 100; i++) {
int num=rand.nextInt(100);
arraylist.add(Integer.valueOf(num));
//get number of >50
if(num>50)total_50++;
}
System.out.println("numbers of >50 is: "+total_50);
//sort the arraylist
Comparator<Integer> comp=new MyComparator();
Collections.sort(arraylist, comp);
//out min & max
System.out.println("Min number is: "+arraylist.get(0));
System.out.println("Max number is: "+arraylist.get(99));
}
public static class MyComparator implements Comparator<Integer>{
@Override
public int compare(final Integer o1, final Integer o2) {
final Integer x=(Integer)o1;
final Integer y=(Integer)o2;
if (x>y) {
return 1;
}else{
return 0;
}
}
}
}
本文出自 “专注J2EE系列规范下的开源技术” 博客:http://danni505.blog.51cto.com/15547/204020
标签: 每日, 系列, Java
百鸣[Baiming.org]欢迎您~