2016-02-12 3 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

переопределение приравнивает и метод 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.

Смежные вопросы