001/*
002  GRANITE DATA SERVICES
003  Copyright (C) 2011 GRANITE DATA SERVICES S.A.S.
004
005  This file is part of Granite Data Services.
006
007  Granite Data Services is free software; you can redistribute it and/or modify
008  it under the terms of the GNU Library General Public License as published by
009  the Free Software Foundation; either version 2 of the License, or (at your
010  option) any later version.
011
012  Granite Data Services is distributed in the hope that it will be useful, but
013  WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
014  FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License
015  for more details.
016
017  You should have received a copy of the GNU Library General Public License
018  along with this library; if not, see <http://www.gnu.org/licenses/>.
019*/
020
021package org.granite.collections;
022
023import java.io.Externalizable;
024import java.io.IOException;
025import java.io.ObjectInput;
026import java.io.ObjectOutput;
027import java.io.Serializable;
028import java.util.HashMap;
029import java.util.Map;
030
031/**
032 * @author Franck WOLFF
033 */
034public class BasicMap<K, V> extends HashMap<K, V> implements Externalizable, Serializable {
035
036    public BasicMap() {
037        super();
038    }
039
040    public BasicMap(Map<K, V> map) {
041        super(map);
042    }
043
044    @SuppressWarnings("unchecked")
045    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
046        Object[] pairs = (Object[])in.readObject();
047        if (pairs != null) {
048            for (Object pair : pairs)
049                put((K)((Object[])pair)[0], (V)((Object[])pair)[1]);
050        }
051    }
052
053    public void writeExternal(ObjectOutput out) throws IOException {
054        Object[] outObjectArray = new Object[size()];
055
056        int index = 0;
057        for (Map.Entry<K, V> entry : entrySet())
058            outObjectArray[index++] = new Object[]{entry.getKey(), entry.getValue()};
059
060        out.writeObject(outObjectArray);
061    }
062
063    @SuppressWarnings({ "unchecked", "rawtypes" })
064    public static BasicMap<?, ?> newInstance(Map<?, ?> map) {
065        return new BasicMap(map);
066    }
067
068    @Override
069    public String toString() {
070        return getClass().getName() + " " + super.toString();
071    }
072}