如何在Java中存储唯一的字符串对?

时间:2016-02-12 06:49:48

标签: java

我编写了一个简单的测试程序,我试图在其中存储唯一的一对(String,String)。下面我提到了我的代码部分:

 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不允许重复配对,但它不起作用。还有其他想法吗?

3 个答案:

答案 0 :(得分:1)

您需要覆盖hashCode()和equals(),否则您将默认为Object的实现。

请参阅:docs

答案 1 :(得分:1)

您需要覆盖Pair类中的equals()和hashCode()方法。请按照以下相关链接了解详情:

HashSet does not seem to realize that two objects are the same

答案 2 :(得分:1)

您需要定义Pair

的相等性
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;
    }
}