(14) Hadoop MapReduce 自定义数据类型

*
 * 所有Mp数据类型 都要实现Writable (这个类中有2个方法  写  读 )  以便这些类定义的数据可以被序列化和存储
 * Writeble接口中方法:
 * 		write() 是把每个数据对象序列化到输出流
 * 		readFields 是把输入流字节凡序列化
 * 
 * 基本数据类型:
 * //		BooleanWritable 标准布尔型数据
	 //		ByteWritable  单字节数据
	 //		doubWritable  双字节数据
	 //		FloatWritable  浮点数据
	 //		IntWritable		整数型
	 //		LongWritable  长整型数
	 //		Text 使用UTF8格式存储的文本
	 //		NullWritable 当<key,value> 中的key或value为空时使用
 * 
 * 
 * 排序:
 * 	 依据key 进行比较  所以MR中 key的数据类型 不仅仅需要实现Writeble 还要实现Comparable接口
 *         	也就是直接继承WritableComparable 就可以    
*  		** value的数据类型只需要继承Writeble
 * 
 * 	
 * 自定义数据对象的时候  (java的时候)
 * 重写:toString  hashCode() equals() 方法
 * 
 * 
 * 
 * 
 * */

例子:PairWritable.java  


package com.my.hadoop.hadoophdfs.io;

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

import org.apache.hadoop.io.WritableComparable;

public class PairWritable implements WritableComparable<PairWritable> {
	/**
	 * user info *id *name
	 * 
	 */
	private int id;
	private String name;
	
	public PairWritable(){
		
	}
	public PairWritable(int id,String name){
				this.set(id, name);
	}
	
	public void set(int id,String name){
		this.setId(id);
		this.setName(name);
	}
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + id;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		PairWritable other = (PairWritable) obj;
		if (id != other.id)
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}
	
	public String toString() {
		return id +"\t"+ name ;
	}
	public void write(DataOutput out) throws IOException {
		out.writeInt(id);
		out.writeUTF(name);
	}
	public void readFields(DataInput in) throws IOException {
		
			   //这里的读取顺序  跟write中设置顺序一定要  一致! 一致!  一致!
				this.id=in.readInt();
				this.name = in.readUTF();
	}
	public int compareTo(PairWritable o) {
		//先比较id
		int comp =Integer.valueOf(this.getId()).compareTo(o.getId());
		
		if(0 != comp){
			return comp;
		}
		//如果不相等  再比较name
		return this.getName().compareTo(o.getName());
	}
	
}

猜你喜欢

转载自blog.csdn.net/qq_36291682/article/details/79590670