有时候方法要返回两个值,后者多个值,用下面定义的bean结构可以很快的构建出来:
package com.clou.douliu.server.bean;
import java.io.Serializable;
/**
* 值对
* 方法需要返回两个值时,可使用Pair减少代码量
* @author rabbit
*
* @param <F>
* @param <S>
*/
public final class Pair<F, S> implements Serializable
{
private static final long serialVersionUID = 1L;
public F first;
public S second;
public Pair(F f, S s)
{
this.first = f;
this.second = s;
}
/**
* 通过值创建值对
* @param <FT>
* @param <ST>
* @param f
* @param s
* @return
*/
public static <FT, ST> Pair<FT, ST> makePair(FT f, ST s)
{
return new Pair<FT, ST>(f, s);
}
private static <T> boolean eq(T o1, T o2)
{
return o1 == null ? o2 == null : o1.equals(o2);
}
@SuppressWarnings("unchecked")
public boolean equals(Object o)
{
Pair<F, S> pr = (Pair<F, S>) o;
if(pr == null)
return false;
return eq(first, pr.first)
&& eq(second, pr.second);
}
private int h(Object o)
{
return o == null ? 0 : o.hashCode();
}
public int hashCode()
{
int seed = h(first);
seed ^= h(second) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
return seed;
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("first=").append(first).append(".\t").append("second=").append(second);
return sb.toString();
}
}
返回三个值:
package com.clou.douliu.server.bean;
import java.io.Serializable;
/**
* 三值
* 方法需要返回三个值时,可使用Triple减少代码量
* @author denghuahui
*
* @param <F>
* @param <S>
* @param <T>
*/
public final class Triple<F, S , T> implements Serializable
{
private static final long serialVersionUID = 1L;
public F first;
public S second;
public T third;
public Triple(F f, S s ,T t)
{
this.first = f;
this.second = s;
this.third = t;
}
/**
* 通过值创建值对
* @param <FT>
* @param <ST>
* @param f
* @param s
* @return
*/
public static <FT, ST ,TT> Triple<FT, ST , TT> makeTriple(FT f, ST s ,TT t)
{
return new Triple<FT, ST ,TT >(f, s ,t);
}
@SuppressWarnings("unchecked")
public boolean equals(Object o)
{
Triple<F, S ,T> pr = (Triple<F, S ,T>) o;
if(pr == null)
return false;
return eq(first, pr.first)
&& eq(second, pr.second) && eq(third , pr.third);
}
private int h(Object o)
{
return o == null ? 0 : o.hashCode();
}
public int hashCode()
{
int seed = h(first);
seed ^= h(second) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
seed ^= h(third) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
return seed;
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("first=").append(first).append(".\t").append("second=").append(second).append(".\t").append("third=").append(third);
return sb.toString();
}
}