1/*- 2 * See the file LICENSE for redistribution information. 3 * 4 * Copyright (c) 2002,2008 Oracle. All rights reserved. 5 * 6 * $Id: MapProxy.java,v 1.1 2008/02/07 17:12:27 mark Exp $ 7 */ 8 9package com.sleepycat.persist.impl; 10 11import java.util.HashMap; 12import java.util.Map; 13import java.util.TreeMap; 14 15import com.sleepycat.persist.model.Persistent; 16import com.sleepycat.persist.model.PersistentProxy; 17 18/** 19 * Proxy for a Map. 20 * 21 * @author Mark Hayes 22 */ 23@Persistent 24abstract class MapProxy<K,V> implements PersistentProxy<Map<K,V>> { 25 26 private K[] keys; 27 private V[] values; 28 29 protected MapProxy() {} 30 31 public final void initializeProxy(Map<K,V> map) { 32 int size = map.size(); 33 keys = (K[]) new Object[size]; 34 values = (V[]) new Object[size]; 35 int i = 0; 36 for (Map.Entry<K,V> entry : map.entrySet()) { 37 keys[i] = entry.getKey(); 38 values[i] = entry.getValue(); 39 i += 1; 40 } 41 } 42 43 public final Map<K,V> convertProxy() { 44 int size = values.length; 45 Map<K,V> map = newInstance(size); 46 for (int i = 0; i < size; i += 1) { 47 map.put(keys[i], values[i]); 48 } 49 return map; 50 } 51 52 protected abstract Map<K,V> newInstance(int size); 53 54 @Persistent(proxyFor=HashMap.class) 55 static class HashMapProxy<K,V> extends MapProxy<K,V> { 56 57 protected HashMapProxy() {} 58 59 protected Map<K,V> newInstance(int size) { 60 return new HashMap<K,V>(size); 61 } 62 } 63 64 @Persistent(proxyFor=TreeMap.class) 65 static class TreeMapProxy<K,V> extends MapProxy<K,V> { 66 67 protected TreeMapProxy() {} 68 69 protected Map<K,V> newInstance(int size) { 70 return new TreeMap<K,V>(); 71 } 72 } 73} 74