利用HashMap存取对象并获得键值集合

1.HashMap 已实现的接口

Serializable, Cloneable, Map<K,V>

2.方法摘要

 

相关代码

/**
     * 
     * @param ha
     *            write(HashMap<String,Customer> ha) 传来HashMap对象列表 将对象写入文件中
     */
    public static void write(HashMap<String, Customer> ha) {
        ;
        try {
            ObjectOutputStream oos = new ObjectOutputStream(
                    new FileOutputStream("e:/db/db.dat"));
            oos.writeObject(ha);
            oos.close();
        } catch (FileNotFoundException e) {
                   e.printStackTrace();
        } catch (IOException e) {
                  e.printStackTrace();
        }
    }

    /**
     * @param id
     * @return ReadCustomer(String id) 方法 通过HashMap 关键字 读取对象 并且返回对象
     */
    public static Customer readCustomer(String mark) {
        HashMap<String, Customer> hm = new HashMap<String, Customer>();
        Customer c = new Customer();
        try {
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
                    "e:/db/db.dat"));
            hm = (HashMap<String, Customer>) ois.readObject();
            c = hm.get(mark);
            ois.close();

        } catch (FileNotFoundException e) {
                      e.printStackTrace();
        } catch (IOException e) {
                        e.printStackTrace();
        } catch (ClassNotFoundException e) {
                      e.printStackTrace();
        }
        return c;
    }
/**
     * writeCustomer(Customer cus) 将对象写入HashMap 列表中并通过write()方法将对象写入文件中
     * 
     * @param account
     */
    public static void writeCustomer(Customer cus) {
        HashMap<String, Customer> m = new HashMap<String, Customer>();

        try {
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
                    "e:db/db.dat"));
            m = (HashMap<String, Customer>) ois.readObject();
            m.put(cus.getMark(), cus);
            write(m);
            ois.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        Util.stay();
    }

 

posted @ 2014-10-20 15:58  Dream露  阅读(1456)  评论(0编辑  收藏  举报