static class MyInteger implements Comparable<MyInteger>{
Integer i;public MyInteger(int i){this.i=i;}@Overridepublic int compareTo(MyInteger o){// TODO Auto-generated method stubif (i>o.getI()){return 1;}else if (i==o.getI()){return 0;}elsereturn -1;}@Overridepublic String toString(){// TODO Auto-generated method stubreturn i.toString();}public Integer getI(){return i;}
}
public static void main(String[] args){
int[] a=new int[20];for (int i = 0; i < a.length; i++){a[i]=(int)(Math.random()*100);System.out.print(a[i]+" ");}findKMin(a,5);
}
public static void findKMin(int[] a, int k){
TreeSet<MyInteger> treeSet=new TreeSet<>();for (int i = 0; i < a.length; i++){MyInteger integer=new MyInteger(a[i]);treeSet.add(integer);}System.out.println();int i=0;Iterator<MyInteger> iterator=treeSet.iterator();while(i<k&&iterator.hasNext()){i++;System.out.print(" "+iterator.next().toString());}
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文:http://blog.csdn.net/lyric_315/article/details/47685809