2

I have a class that has a List of Article (or what you want). Is it safe to implement/override the hashCode() function in that class like this :

class Place{
    List <Article> list = new List<Article>();

    public int hashCode() {
        if(list.isEmpty())
            return 0; //is it safe to return 0
        else
            return list.get(0).hashCode();
    }
}

public class Main{
    private HashSet<Place> places = new HashSet<>();

    //this function must be donne like this
    public boolean isArticleIn(Article article){
        Place place = new Place();
        place.add(article);
        return places.contains(place);
    }
}

Is there a possibility to have a list that is not empty and return 0.

Hunsu
  • 3,281
  • 7
  • 29
  • 64
  • 3
    `0` is a hash code like any other so yes this is safe. But is it normal that you only want the hash code of the first element of the list otherwise? – fge Mar 21 '14 at 11:00
  • Two list are equals if they have they the same Article so yes. It's not me that have done the conception. – Hunsu Mar 21 '14 at 11:02
  • 2
    Do you mean the list can only ever have one element? If yes why not just use `list.hashCode()`? – fge Mar 21 '14 at 11:06
  • It seems above code is fine since it `follows the contract`.Have you tried in your code? What errors are you getting? – KNU Mar 21 '14 at 11:22

2 Answers2

3

If you want to store objects of your class in a container which uses hashCode, then you should make sure that "if two objects are equal then they should return the same hash code" (otherwise the container may store duplicates / generally get confused). Will objects of your class compare equal if they both have an empty list?

Best advice on how to implement equals and hashcode so that they capture all the information you want while remaining consistent is available here (using EqualsBuilder and HashCodeBuilder from Apache Commons Lang library recommended). It does seem likely that all the elements in your list should contribute to the hashcode - after all, if the second or third element of the list is different, then your objects will return false from 'equals' - right?

Community
  • 1
  • 1
Graham Griffiths
  • 2,196
  • 1
  • 12
  • 15
1

It is safe. It's immutable, which is good.

However your hashed collections won't be performant, since you're not providing an evenly distributed range of hashcodes, and so your hash populations won't be evenly distributed. See here for an explanation of what's going on inside a hashed collection.

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440