目标:做一个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