手机
当前位置:查字典教程网 >编程开发 >Java >java 对象数组排序
java 对象数组排序
摘要:废话不多说直接奉上代码先:importjava.util.*;importjava.io.*;publicclassMain{statici...

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

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按照什么规则来比较两个对象的大小。

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

【java 对象数组排序】相关文章:

java 重定义数组的实现方法(与VB的ReDim相像)

java equals函数用法详解

java中的key接口解析

java 序列化对象 serializable 读写数据的实例

java冒泡排序算法代码

java随机字符补充版

java控制Pdf自动打印的小例子

Java 位图法排序的使用方法

java字符串替换排序实例

java连接mysql数据库乱码的解决方法

精品推荐
分类导航