package com.conatructor; 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.Collections; import java.util.Comparator; import java.util.List; public class Box { public static void main(String[] args) { //装箱 List<Apple> al = new ArrayList<Apple>(); al.add(new Apple("app1",19.3,25.4)); al.add(new Apple("app2",20.7,25.8)); al.add(new Apple("app3",22.5,25.6)); Collections.sort(al, new Comparator<Apple>() { @Override public int compare(Apple o1, Apple o2) { double c =o1.getheight()-o2.getheight(); if(c>0) return 1;//正序 else if(c<0) return -1;//倒序 else return 0; } }); try { ObjectOutputStream oo = new ObjectOutputStream(new FileOutputStream("D:/1.txt")); oo.writeObject(al); oo.flush(); oo.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } //拆箱 // List<Apple> read= null; // try { // ObjectInputStream oi = new ObjectInputStream(new FileInputStream("D:/1.txt")); // try { // read =(List<Apple>) oi.readObject(); // } catch (ClassNotFoundException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } catch (FileNotFoundException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } for(Apple x:al) { System.out.println(x); } } }