我编写了一个简单的测试程序,其中尝试存储唯一的(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不允许重复的Pairs,但是它不起作用。还有其他想法吗?

最佳答案

您需要定义对的相等性

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;
    }
}

09-27 22:49