创建一个Tuple

本文介绍了如何使用Tuple来存放数据库查询得到的pair对象,如host和platform。通过创建自定义的tuple,避免了字符串拼接的不便和提取错误,同时,由于tuple的hashcode和equals方法进行了特殊实现,适合进行String值的比较。示例代码和相关参考链接提供了更多细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目标:做一个tuple 存放pair 对象

例子:

比如我要存放的数据来自数据库,SELECT distinct host,platform FROM "Log_loginfo",host 和 platform 是一个pair 对象,用字符串串接麻烦又有提取回来失误的风险,用map本质上是key-value的关系而不是pair关系,因此,使用tuple来解决。


tuple.java

package j2seTest2;

import java.io.Serializable;

public class Tuple<L, R> implements Serializable {
	
	private static final long serialVersionUID = 1L;

	/** The left object. */
    public L left;

	/** The right object. */
    public R right;
    
    /** Construct a tuple with the specified two objects. */
    public Tuple(L left, R right) {
        this.left = left;
        this.right = right;
    }
    
    /** Construct a blank tuple. */
    public Tuple() {
    }
    
    /**
     * Returns the combined hashcode of the two elements.
     */
    public int hashCode() {
        return left.hashCode() ^ right.hashCode();
    }
    
    /**
     * Generates a string representation of this tuple.
     */
    public String toString() {
        return "[left=" + left + ", right=" + right + "]";
    }
    
    /**
     * A tuple is equal to another tuple if the left and right elements
     * are equal to the left and right elements (respectively) of the
     * other tuple.
     */
	@SuppressWarnings("rawtypes")
	public boolean equals(Object other) {
		if (this == other) {
			return true;
		}
		if (other == null) {
			return false;
		}
		if (getClass() != other.getClass()) {
			return false;
		}
		if (other instanceof Tuple) {
			Tuple to = (Tuple) other;
			return (left.equals(to.left) && right.equals(to.right));
		}
		return false;
	}
}

TupleTest.java

package j2seTest2;

import java.util.HashSet;

public class TupleTest {

	public static void main(String[] args) {
		
		Tuple<String, String> tempxY1 = new Tuple<String, String>();
		Tuple<String, String> tempxY2 = new Tuple<String, String>();
		HashSet<Tuple<String, String>> xYSet = new HashSet<Tuple<String, String>>();
		
		String xStr = "x1";
		tempxY1.left = "x1";
		tempxY1.right = "y1";
		tempxY2.left = xStr;
		tempxY2.right = "y1";
		xYSet.add(tempxY1);
		
		if (xYSet.contains(tempxY2)) {
			System.out.println("contains-Yes");		// value compare
		} else {
			System.out.println("contains-No");		// object compare
		}
	}

}

解释:

set contains 方法会调用包含对象的hashcode 和 equals 方法,这里tuple的hashcode 和 equals 方法已经特别改写,适合String值比较。


Reference:

http://blog.youkuaiyun.com/renfufei/article/details/14163329


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值