public class Tuple { public staticTuple2 of(V1 v1, V2 v2) { return new Tuple2<>(v1, v2); } public static Tuple3 of(V1 v1, V2 v2, V3 v3) { return new Tuple3<>(v1, v2, v3); } }
public class Tuple2{ private final V1 v1; private final V2 v2; public Tuple2(V1 v1, V2 v2) { this.v1 = v1; this.v2 = v2; } public static Tuple2 of(V1 v1, V2 v2) { return new Tuple2<>(v1, v2); } public V1 _1() { return v1; } public V2 _2() { return v2; } @Override public String toString() { return "(" + v1 + "+" + v2 + ")"; } /** * 重写hashcode * * @return 用31 可以减少hashcode值在范围内值冲突 以及31可以被JVM优化 * * * 左移 << : 左边的最高位丢弃,右边补全0(把 << 左边的数据*2的移动次幂)。 * * 右移 >> : 把>>左边的数据/2的移动次幂。 * * 无符号右移 >>> : 无论最高位是0还是1,左边补齐0。 *
* 所以 : 31 * i = (i << 5) - i(左边 31*2=62,右边 2*2^5-2=62) - 两边相等,JVM就可以高效的进行计算啦。。。 */ @Override public int hashCode() { int result = v1.hashCode(); result = 31 * result + v2.hashCode(); return result; } /** * 重写equals 方法 */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } //对象为空,或者引用地址不等 返回 false if (obj == null || getClass() != obj.getClass()) { return false; } // 值不等返回false Tuple2, ?> tuple2 = (Tuple2, ?>) obj; if (!v1.equals(tuple2.v1)) return false; return v2.equals(tuple2.v2); } }
public class Tuple3{ private final V1 v1; private final V2 v2; private final V3 v3; public Tuple3(V1 v1, V2 v2, V3 v3) { this.v1 = v1; this.v2 = v2; this.v3 = v3; } public static Tuple3 of(V1 v1, V2 v2, V3 v3) { return new Tuple3<>(v1, v2, v3); } public V1 _1() { return v1; } public V2 _2() { return v2; } public V3 _3() { return v3; } @Override public String toString() { return "(" + v1 + "," + v2 + "," + v3 + ')'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Tuple3, ?, ?> tuple3 = (Tuple3, ?, ?>) o; if (!v1.equals(tuple3.v1)) return false; if (!v2.equals(tuple3.v2)) return false; return v3.equals(tuple3.v3); } @Override public int hashCode() { int result = v1.hashCode(); result = 31 * result + v2.hashCode(); result = 31 * result + v3.hashCode(); return result; } }
测试:
package com.stduy; import com.stduy.Tuple.Tuple2; import java.util.ArrayList; import java.util.List; import static java.lang.System.out; /** * @author zhangkun * @create 2018-12-17 10:16 AM * @desc **/ public class TupleTest { public static void main(String[] args) { Tuple2tuple = testTuple(); out.println(tuple._1()); List list = tuple._2(); list.stream().forEach(out::println); } public static Tuple2 testTuple(){ List longList = new ArrayList<>(3); longList.add(1); longList.add(2); longList.add(3); return Tuple2.of("test",longList); } }
打印值为下;
Connected to the target VM, address: '127.0.0.1:51475', transport: 'socket'
test
1
2
3
Disconnected from the target VM, address: '127.0.0.1:51475', transport: 'socket'
看完 是不是觉得这种元组数据结构在某些地方用起来很方便呢。