2016-02-12 76 views
2

我写了一个简单的测试程序,我试图存储唯一的一对(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不会允许重复对,但它不起作用。任何其他的想法?

+5

覆盖在Pair类的平等equals和hashCode方法解决 –

回答

1

您需要定义一对

public class Pair { 
    private String cr_ts_hi; 
    private String cr_ts_lo; 

    //constructor and getter-setter 

    @Override 
    public boolean equals(Object o) { 
     if (this == o) return true; 
     if (o == null || getClass() != o.getClass()) return false; 

     Pair pair = (Pair) o; 

     if (cr_ts_hi != null ? !cr_ts_hi.equals(pair.cr_ts_hi) : pair.cr_ts_hi != null) return false; 
     return cr_ts_lo != null ? cr_ts_lo.equals(pair.cr_ts_lo) : pair.cr_ts_lo == null; 
    } 

    @Override 
    public int hashCode() { 
     int result = cr_ts_hi != null ? cr_ts_hi.hashCode() : 0; 
     result = 31 * result + (cr_ts_lo != null ? cr_ts_lo.hashCode() : 0); 
     return result; 
    } 
} 
+0

谢谢:) – Madhusudan

1

您需要重写hashCode()和equals()否则您默认为Object的实现。

参见:docs

相关问题