source: sample/hadoop-0.17/tw/org/nchc/tuple/HashMapWritable.java @ 20

Last change on this file since 20 was 20, checked in by waue, 16 years ago

將改完的 hadoop 0.17版package 放來備份
目前繼續開發 hadoop 0.16 + hbase 1.3

File size: 2.4 KB
Line 
1
2package tw.org.nchc.tuple;
3
4import java.io.DataInput;
5import java.io.DataOutput;
6import java.io.IOException;
7import java.util.Map;
8import java.util.Set;
9import java.util.HashMap;
10
11
12import org.apache.hadoop.io.Writable;
13
14public class HashMapWritable<K extends Writable, V extends Writable> extends HashMap<K, V> implements
15        Writable {
16
17  /**
18     *
19     */
20    private static final long serialVersionUID = 1L;
21
22    /**
23   * Creates a HashMapWritable object.
24   */
25  public HashMapWritable() {
26    super();
27  }
28 
29  /**
30   * Creates a HashMapWritable object from a regular HashMap.
31   */
32  public HashMapWritable(HashMap<K, V> map) {
33    super(map);
34  }
35
36  /**
37   * Deserializes the array.
38   *
39   * @param in
40   *            source for raw byte representation
41   */
42  public void readFields(DataInput in) throws IOException {
43   
44    this.clear();
45
46    int numEntries = in.readInt();
47    if(numEntries==0) return;
48   
49    String keyClassName = in.readUTF();
50    String valueClassName = in.readUTF();
51   
52    K objK;
53    V objV;
54    try {
55      Class keyClass = Class.forName(keyClassName);
56      Class valueClass = Class.forName(valueClassName);
57      for (int i = 0; i < numEntries; i++) {
58        objK = (K) keyClass.newInstance();
59        objK.readFields(in);
60        objV = (V) valueClass.newInstance();
61        objV.readFields(in);
62        put(objK, objV);
63      }
64
65    } catch (ClassNotFoundException e) {
66      e.printStackTrace();
67    } catch (IllegalAccessException e) {
68      e.printStackTrace();
69    } catch (InstantiationException e) {
70      e.printStackTrace();
71    }
72   
73  }
74
75  /**
76   * Serializes this array.
77   *
78   * @param out
79   *            where to write the raw byte representation
80   */
81  public void write(DataOutput out) throws IOException {
82    // Write out the number of entries in the map
83      out.writeInt(size());
84      if(size()==0) return;
85     
86      // Write out the class names for keys and values
87      // assuming that data is homogeneuos (i.e., all entries have same types)
88      Set<Map.Entry<K, V>> entries = entrySet();
89      Map.Entry<K, V> first = entries.iterator().next();
90      K objK = first.getKey();
91      V objV = first.getValue();
92      out.writeUTF(objK.getClass().getCanonicalName());
93      out.writeUTF(objV.getClass().getCanonicalName());
94
95      // Then write out each key/value pair
96      for (Map.Entry<K, V> e: entrySet()) {
97        e.getKey().write(out);
98        e.getValue().write(out);
99      }
100  }
101
102}
Note: See TracBrowser for help on using the repository browser.