Hadoop实现定制的Writeable集合

         Hadoop提供的Writeable实现可以满足大部分的需求,但是在有些情况下,我们需要根据自己的需求来构造一个全新的实现,根据自定义的Writeable类型,我们可以完全控制二进制表示和排序操作,通过实WriteableComparable接口来完成。


import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.WritableComparable;

/*
 * 实现定制的Writeable集合
 */
public class SerializationDemo implements WritableComparable {

	private Text first;
	private Text second;

	public SerializationDemo() {
		set(new Text(), new Text());
	}

	public SerializationDemo(Text first, Text second) {
		set(first, second);
	}

	public SerializationDemo(String first, String second) {
		set(new Text(first), new Text(second));
	}

	public Text getFirst() {
		return first;
	}

	public void setFirst(Text first) {
		this.first = first;
	}

	public Text getSecond() {
		return second;
	}

	public void setSecond(Text second) {
		this.second = second;
	}

	private void set(Text text1, Text text2) {
		// TODO Auto-generated method stub
		this.first = text1;
		this.second = text2;
	}

	public void readFields(DataInput in) throws IOException {
		// TODO Auto-generated method stub
		first.readFields(in);
		second.readFields(in);
	}

	public void write(DataOutput out) throws IOException {
		// TODO Auto-generated method stub
		first.write(out);
		second.write(out);
	}

	public int compareTo(SerializationDemo o) {
		// TODO Auto-generated method stub
		// return 0;
		int cmp = first.compareTo(o.first);
		if (cmp != 0) {
			return cmp;
		}
		return second.compareTo(o.second);
	}

	@Override
	public int hashCode() {
		// TODO Auto-generated method stub
		// return super.hashCode();
		return first.hashCode() * 163 + second.hashCode();
	}

	@Override
	public boolean equals(Object obj) {
		// TODO Auto-generated method stub
		// return super.equals(obj);
		if (obj instanceof SerializationDemo) {
			SerializationDemo s = (SerializationDemo) obj;
			return first.equals(s.first) && second.equals(s.second);
		}
		return false;
	}

	@Override
	public String toString() {
		// TODO Auto-generated method stub
		// return super.toString();
		return first + "," + second;
	}

}

参考:

 Hadoop权威指南

你可能感兴趣的:(Hadoop)