装箱/拆箱 对象排序
Posted 冰逸101
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了装箱/拆箱 对象排序相关的知识,希望对你有一定的参考价值。
package one; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Comparator; import java.util.List; public class Sort22 { public static void main(String[] args) throws FileNotFoundException, IOException { List<Apple> list = new ArrayList<Apple>(); list.add(new Apple(1, "ehe", 1.1)); list.add(new Apple(2, "ehe", 1.1)); list.add(new Apple(3, "ehe", 1.1)); list.add(new Apple(4, "ehe", 1.1)); list.add(new Apple(5, "ehe", 1.1)); //排序规则 list.sort(new Comparator<Apple>() { @Override public int compare(Apple o1, Apple o2) { return (o1.getId()-o2.getId())*(-1); } }); System.out.println("*******************************************************************"); System.out.println("对象排序"); for (Apple x : list) { System.out.println(x); } System.out.println("********************************************************************"); //装箱 ObjectOutputStream oo= new ObjectOutputStream(new FileOutputStream("D:/1.txt"));//对象输出流 oo.writeObject(list); oo.flush(); oo.close(); System.out.println("对象输出到文件"); System.out.println("****************************************************************************"); //------------------------------------------------------------------------------------------------- //拆箱 List <Apple> read=null; try { ObjectInputStream oi= new ObjectInputStream(new FileInputStream("D:/1.txt"));//输入流 read =(List<Apple>)oi.readObject(); for(Apple x:read){ System.out.println(x); } oi.close(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
以上是关于装箱/拆箱 对象排序的主要内容,如果未能解决你的问题,请参考以下文章