Hadoop之个性化键类型

前面我们的Piont3D类型能够作为一个值来满足mapper的使用。但是如果我们也想用Point3D对象作为键呢?在Hadoop的MR中,如果向一个reduce任务分发不同的(key, value)对,reducer将有序地对键进行处理。所以键的类型必须实现一个更加严格的接口,WritableComparable。除了它是一个Writable,可以被在网络传输之外,它们也遵循Java的Comparable接口。下面的代码扩展了Piont3D来满足这个接口的要求:

public class Point3D implements WritableComparable{

public float x;

public float y;

public float z;


public Point3D(float x, float y, float z){

this.x = x;

this.y = y;

this.z = z;

}

public Point3D(){

this(0.0f, 0.0f, 0.0f);

}

public void readFields(DataInput in) throws IOException{

x = in.readFloat();

y = in.readFloat();

z = in.readFload();

public String toString(){

return Float.toString(x) + "," + Float.toString(y) + "," + Float.toString(z);


/* 返回从到原点的欧氏距离 */

public float distanceFromOrigin(){

return (float)Math.sqrt(x*x + y*y + z*z);

}


public int compareTo(Point3D other){

float myDistance = distanceFromOrigin();

float otherDistance = other.distanceFromOrign();

return Float.compare(myDistance, otherDistance);

}


public boolean equals(Object o){

if(!(other instanceof Point3D)){

return false;

}

Point3D other = (Point3D)o;

return this.x == other.x && this.y == other.y && this.z == other.z;

}


public int hashCode(){

return Float.floatToIntBits(x) ^Float.floatToIntBits(y)^Float.floatToIntBits(z);

}

}

实现hashCode()对于key类型来说是重要的;在Partitioner部分中将说明原因。hashCode()和equals()在这个版本中也一并提供了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值