Simple implementation of persistent map on an array Note that instances of this class are constant values i.e. add/remove etc return new values Copies array on every change, so only appropriate for _very_small_ maps null keys and values are ok, but you won't be able to dis
| 28 | */ |
| 29 | |
| 30 | public class PersistentArrayMap extends APersistentMap implements IObj, IEditableCollection, IMapIterable, IKVReduce, IDrop{ |
| 31 | |
| 32 | private static final long serialVersionUID = -2074065891090893601L; |
| 33 | |
| 34 | final Object[] array; |
| 35 | static final int HASHTABLE_THRESHOLD = 16; |
| 36 | |
| 37 | public static final PersistentArrayMap EMPTY = new PersistentArrayMap(); |
| 38 | private final IPersistentMap _meta; |
| 39 | |
| 40 | static public IPersistentMap create(Map other){ |
| 41 | ITransientMap ret = EMPTY.asTransient(); |
| 42 | for(Object o : other.entrySet()) |
| 43 | { |
| 44 | Map.Entry e = (Entry) o; |
| 45 | ret = ret.assoc(e.getKey(), e.getValue()); |
| 46 | } |
| 47 | return ret.persistent(); |
| 48 | } |
| 49 | |
| 50 | protected PersistentArrayMap(){ |
| 51 | this.array = new Object[]{}; |
| 52 | this._meta = null; |
| 53 | } |
| 54 | |
| 55 | public PersistentArrayMap withMeta(IPersistentMap meta){ |
| 56 | if(meta() == meta) |
| 57 | return this; |
| 58 | return new PersistentArrayMap(meta, array); |
| 59 | } |
| 60 | |
| 61 | PersistentArrayMap create(Object... init){ |
| 62 | return new PersistentArrayMap(meta(), init); |
| 63 | } |
| 64 | |
| 65 | IPersistentMap createHT(Object[] init){ |
| 66 | return PersistentHashMap.create(meta(), init); |
| 67 | } |
| 68 | |
| 69 | static public PersistentArrayMap createWithCheck(Object[] init){ |
| 70 | for(int i=0;i< init.length;i += 2) |
| 71 | { |
| 72 | for(int j=i+2;j<init.length;j += 2) |
| 73 | { |
| 74 | if(equalKey(init[i],init[j])) |
| 75 | throw new IllegalArgumentException("Duplicate key: " + init[i]); |
| 76 | } |
| 77 | } |
| 78 | return new PersistentArrayMap(init); |
| 79 | } |
| 80 | |
| 81 | /** |
| 82 | * <p>This method attempts to find resue the given array as the basis for an array map as quickly as possible.</p> |
| 83 | * |
| 84 | * <p>If a trailing element exists in the array or it contains duplicate keys then it delegates to the complex path.</p> |
| 85 | **/ |
| 86 | static public PersistentArrayMap createAsIfByAssoc(Object[] init){ |
| 87 | boolean complexPath, hasTrailing; |
nothing calls this directly
no outgoing calls
no test coverage detected