用JAVA实现PAIR结构
在工作中我们经常需要处理KV - (Key - Value)型的数据结构通常我们使用HashMap来进行处理,但是HashMap的结构使得我们并不够很方便的去取Key的值,并且取得特定Value的值也需要一个准确的KEY值或者下标, 且有些时候我们仅且需要一组KV值的时候,HashMap就显得非常的不方便了
在此提出一种新的简单的数据结构Pair来满足这种成对出现的数据结构
package lang;
import java.io.Serializable;
/**
* TODO The class Pair is supposed to be documented...
*
* @author Junying Li
*/
public final class Pair<H, T> implements Serializable {
private H head;
private T tail;
public static <U, V> Pair<U, V> make(U head, V tail){
return new Pair<>(head, tail);
}
//Constructor
public Pair(H head, T tail){
this.head = head;
this.tail = tail;
}
public H getHead() {
return head;
}
public void setHead(H head) {
this.head = head;
}
public T getTail() {
return tail;
}
public void setTail(T tail) {
this.tail = tail;
}
@Override
public String toString(){
return "["+head.toString()+"]["+tail.toString()+"]";
}
@Override
public int hashCode(){
return head.hashCode()+tail.hashCode();
}
@Override
public boolean equals(Object obj){
Pair pairObj = (Pair)obj;
return (head.equals(pairObj.getHead()) && tail.equals(pairObj.getTail()));
}
}
本文介绍了如何使用JAVA实现PAIR结构,以解决工作中处理KV数据结构的不便。传统上,我们常使用HashMap,但其在某些场景下不够灵活。PAIR结构提供了一种更简便的方式,尤其适用于只需要一组KV值的情况。
339

被折叠的 条评论
为什么被折叠?



