JBoss Community

Entity hashCode and equals overriding

created by fabio valsecchi in EJB3 Development - View the full discussion

Hi there,

 

I'm having some problems overring hashCode() and equals() methods of an entity Book. This is my code:

 

------------------------------------------------------------------------

@Override

          public int hashCode() {

                    int hash = 1;

              hash = hash * 31 + this.isbn.hashCode();

              return hash;

          }

@Override

          public boolean equals(Object o) {

             if (o==this)

                 return true;

             if (o instanceof Book) {

                 return (this.isbn == ((Book) o).getIsbn());

             }

             return false;

          }

------------------------------------------------------------------------

 

The problem is that when I try to add a book to a hashMap like here:

 

------------------------------------------------------------------------

@Override

    public void addArticle(Book book, Integer quantity) {

              Integer currentQuantity = cart.getArticles().get(book);

   

              System.out.println(currentQuantity);

    

        if (currentQuantity == null) {

                  currentQuantity = 0;

        }

        currentQuantity += quantity;

        cart.getArticles().put(book, currentQuantity);

    }

------------------------------------------------------------------------

 

The currentQuantity Integer is always null even if in the hashMap there's already the Book that i'm adding.

 

Maybe it's a problem of my hashCode and equals implementation but i've tried using a hashCode() that return always 1 and with an equals that return always true and currentQuantity is still null.

Can someone give me a hint?

 

Thank you in advance

Reply to this message by going to Community

Start a new discussion in EJB3 Development at Community