KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > nutch > io > ArrayWritable


1 /* Copyright (c) 2003 The Nutch Organization. All rights reserved. */
2 /* Use subject to the conditions in http://www.nutch.org/LICENSE.txt. */
3
4 package net.nutch.io;
5
6 import java.io.*;
7 import java.lang.reflect.Array JavaDoc;
8
9 /** A Writable for arrays containing instances of a class. */
10 public class ArrayWritable implements Writable {
11   private Class JavaDoc valueClass;
12   private Writable[] values;
13
14   public ArrayWritable(Class JavaDoc valueClass) {
15     this.valueClass = valueClass;
16   }
17
18   public ArrayWritable(Class JavaDoc valueClass, Writable[] values) {
19     this(valueClass);
20     this.values = values;
21   }
22
23   public ArrayWritable(String JavaDoc[] strings) {
24     this(UTF8.class, new Writable[strings.length]);
25     for (int i = 0; i < strings.length; i++) {
26       values[i] = new UTF8(strings[i]);
27     }
28   }
29
30   public String JavaDoc[] toStrings() {
31     String JavaDoc[] strings = new String JavaDoc[values.length];
32     for (int i = 0; i < values.length; i++) {
33       strings[i] = values[i].toString();
34     }
35     return strings;
36   }
37
38   public Object JavaDoc toArray() {
39     Object JavaDoc result = Array.newInstance(valueClass, values.length);
40     for (int i = 0; i < values.length; i++) {
41       Array.set(result, i, values[i]);
42     }
43     return result;
44   }
45
46   public void set(Writable[] values) { this.values = values; }
47
48   public Writable[] get() { return values; }
49
50   public void readFields(DataInput in) throws IOException {
51     values = new Writable[in.readInt()]; // construct values
52
for (int i = 0; i < values.length; i++) {
53       Writable value; // construct value
54
try {
55         value = (Writable)valueClass.newInstance();
56       } catch (InstantiationException JavaDoc e) {
57         throw new RuntimeException JavaDoc(e.toString());
58       } catch (IllegalAccessException JavaDoc e) {
59         throw new RuntimeException JavaDoc(e.toString());
60       }
61       value.readFields(in); // read a value
62
values[i] = value; // store it in values
63
}
64   }
65
66   public void write(DataOutput out) throws IOException {
67     out.writeInt(values.length); // write values
68
for (int i = 0; i < values.length; i++) {
69       values[i].write(out);
70     }
71   }
72
73 }
74
75
Popular Tags