我写了一个简单的测试程序,我试图存储唯一的一对(String,String)。这里下面我提到了我的部分代码:如何在Java中存储唯一的字符串对?
public class Pair {
private String cr_ts_hi;
private String cr_ts_lo;
//constructor and getter-setter
}
class Test{
private static HashSet<Pair> caseExceptionReport = new LinkedHashSet<Pair>();
public static void main(String[] args) {
caseExceptionReport.add(new Pair("abc","itm1"));caseExceptionReport.add(new Pair("abc","itm2"));
caseExceptionReport.add(new Pair("abc","itm1"));caseExceptionReport.add(new Pair("def","itm1"));
caseExceptionReport.add(new Pair("def","itm2"));caseExceptionReport.add(new Pair("def","itm2"));
caseExceptionReport.add(new Pair("xyz","itm1"));caseExceptionReport.add(new Pair("xyz","itm2"));
for(Pair m:caseExceptionReport){
System.out.println(m.getCr_ts_hi() + " *** " + m.getCr_ts_lo());
}
}
和输出是:
abc *** item1
abc *** item2
abc *** item1
def *** item1
def *** item2
def *** item2
xyz *** item1
xyz *** item2
预期成果是:
abc *** item1
abc *** item2
def *** item1
def *** item2
xyz *** item1
xyz *** item2
我没有得到的方式来存储唯一的对。我虽然HashSet不会允许重复对,但它不起作用。任何其他的想法?
覆盖在Pair类的平等equals和hashCode方法解决 –