HashSet w porównywaniu obiektów?

0

Chce zrobić prostą rzecz, sprawdzić czy HashSet zawiera obiekt:

Area a = DAO.AreaDAO.getAreaById(Integer.valueOf(index));    
       Set<Question> questions = new HashSet<Question>(0);
       questions = a.getQuestions();       
       boolean x = questions.contains(question);

No i niestety zwracana wartość to zawsze false. Jeśli wydrukuje sobie porównywaną listę obiektów i sam obiekt wszystko się zgadza:

Szukany obiekt: Question{id=19, version=1, description=Pytanie 19}
Wartości w HashSet: [Question{id=19, version=1, description=Pytanie 19}, Question{id=18, version=1, description=Pytanie}]

Nie wiem dlaczego nie wyszukuje mi tego obiektu?

1

A jak nadpisałeś hashcode i equals?

0
  public int hashCode() {
        return (int)this.id;
    }
  
   public boolean equals(Question other) {
        return (int)this.id == (int)other.id;
    }
0

Zmieniłem na jakieś takie bardziej ambitne i jest ok:

@Override
public int hashCode(){
    StringBuffer buffer = new StringBuffer();
    buffer.append(this.id);
    buffer.append(this.version);
    buffer.append(this.description);
    buffer.append(this.active);
    return buffer.toString().hashCode();
}


@Override
public boolean equals(Object object){
    if (object == null) return false;
    if (object == this) return true;
    if (this.getClass() != object.getClass())return false;
    Question questions = (Question)object;
    if(this.hashCode()== questions.hashCode())return true;
   return false;
}  
2
       Set<Question> questions = new HashSet<Question>(0);
       questions = a.getQuestions();      

Szkolny błąd - po co tworzysz HashSet, skoro go w następnej linijce wywalasz? a.getQuestions() zwraca jakąś implementację Seta, nie musi to być HashSet.

Zamiast tego możesz po prostu napisać:

       Set<Question> questions = a.getQuestions();      

Wyjdzie na to samo, ale nie będziesz tworzył śmiecia w pamięci.

1 użytkowników online, w tym zalogowanych: 0, gości: 1