在編寫MapReduce程式時,Map和Reduce之間傳遞的資料需要是ArrayList類型的,在偵錯執行時遇到了這樣的錯誤:
java.lang.RuntimeException: java.lang.NoSuchMethodException: org.apache.hadoop.io.ArrayWritable.<init>()
經查詢官網API文件後發現這樣的一段話:
A Writable for arrays containing instances of a class. The elements of this writable must all be instances of the same class. If this writable will be the input for a Reducer, you will need to create a subclass that sets the value proper type. For example: public class IntArrayWritable extends ArrayWritable { public IntArrayWritable() { super(IntWritable.class); } }
原來是要自己實作一個ArrayWritable類別的衍生類,使用時只要實作兩個建構子即可
public static class TextArrayWritable extends ArrayWritable { public TextArrayWritable() { super(Text.class); } public TextArrayWritable(String[] strings) { super(Text.class); Text[] texts = new Text[] strings) { super(Text.class); Text[] texts = new Text[strings.length]Text; (int i = 0; i < strings.length; i++) { texts[i] = new Text(strings[i]); } set(texts); }}