首页 > 代码库 > 装箱/拆箱 对象排序

装箱/拆箱 对象排序

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();
        }
                                                                                                                
    }
}

 

装箱/拆箱 对象排序