java 对象数组排序


废话不多说直接奉上代码先:

import java.util.*;
import java.io.*;

public class Main{
static int [] dp = new int [1010];
public static void main(String [] args)throws IOException{
Mouse [] mice = new Mouse [1010];
FileReader fr=new FileReader("in.txt");  //读取文件
BufferedReader read = new BufferedReader(fr);
String str = "";
int n=1;
while((str = read.readLine())!=null){
String [] s= str.split(" ");
mice[n] = new Mouse();  //对象实例化,很重要
mice[n].weight = Integer.parseInt(s[0]);
mice[n].speed =Integer.parseInt(s[1]);
n++;
}
System.out.println(n);
Arrays.sort(mice,1,n);  //sort(int start,int end) 包括start索引,不包括end索引
for(int i=1;i<n;i++){
System.out.println(mice[i].weight+" "+mice[i].speed);
}
}
}
class Mouse implements Comparable{  //实现Comparable接口
int weight;
int speed;
public int compareTo(Object o){   //重写compareTo方法
Mouse m=(Mouse)o;
return weight>m.weight?1:(weight==m.weight?0:-1);
}
}

另附上Arrays.sort用法:

      1. 数字排序 int[] intArray = new int[] { 4, 1, 3, -23 };

  Arrays.sort(intArray);
  输出: [-23, 1, 3, 4]

  2. 字符串排序,先大写后小写 String[] strArray = new String[] { "z", "a", "C" };

  Arrays.sort(strArray);
  输出: [C, a, z]

  3. 严格按字母表顺序排序,也就是忽略大小写排序 Case-insensitive sort

  Arrays.sort(strArray, String.CASE_INSENSITIVE_ORDER);
  输出: [a, C, z]

  4. 反向排序, Reverse-order sort

  Arrays.sort(strArray, Collections.reverseOrder());
  输出:[z, a, C]

  5. 忽略大小写反向排序 Case-insensitive reverse-order sort

  Arrays.sort(strArray, String.CASE_INSENSITIVE_ORDER);
  Collections.reverse(Arrays.asList(strArray));
  输出: [z, C, a]

  6、对象数组排序

  要对一个对象数组排序 ,则要自己实现java.util.Comparator接口
  例子:
  Common_User[] userListTemp=new Common_User[temp.size()];
  Arrays.sort(userListTemp, new PinyinComparator());
  PinyinComparator 实现了Comparator接口,重写了compare方法,来告诉Arrays按照什么规则来比较两个对象的大小。

以上所述就是本文的全部内容了,希望大家能够喜欢。


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3