Question

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.

Was it helpful?

Solution

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?

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top