简体   繁体   中英

issue with overriding hashcode and equals

I would like to create a class that will take a list of strings as input. I want to override hashcode and equals of this class so that this class will always return true when the list of strings sent are equal irrespective of their order.

Here is the code:

public final class TableValues
{
    private final String[] tableValue;

    TableValues(final String[] values)
    {
        this.tableValue = values;
    }

    /**
     * @see java.lang.Object#hashCode()
     */
    @Override
    public int hashCode()
    {
        final int prime = 31;
        int result = 1;
        result = prime * result + Arrays.hashCode(tableValue);
        return result;
    }

    /**
     * @see java.lang.Object#equals(java.lang.Object)
     */
    @Override
    public boolean equals(final Object obj)
    {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        final TableValues other = (TableValues) obj;
        if (!Arrays.equals(tableValue, other.tableValue))
            return false;
        return true;
    }
}

But when I do :

final String[] str1 = {"A", "B", "C"};
final String[] str2 = {"B", "C", "A"};
final TableValues tab1 = new TableValues(str1);
final TableValues tab2 = new TableValues(str2);
if (tab1.equals(tab2))
{
    System.out.println("Equal");
}
else
{
    System.out.println("Not Equal");
}

It always prints Not Equal. What is wrong here?

The two TableValues instances are not equal because arrays are not equal. This is due to the fact that the order of elements in the array matters. If you want order insensitive matching you'd have to add it in your code so that it considers two arrays with same contents but different orderings as same or use a Set of strings in case ordering is not important.

Try changing:

if (!Arrays.equals(tableValue, other.tableValue))
        return false;

to :

if (!Arrays.equals(Arrays.sort(tableValue), Arrays.sort(other.tableValue)))
        return false;

From the documentation for Arrays.equals:

the two arrays are equal if they contain the same elements in the same order.

Since you need them to be equal irrespective of order, you have to sort them first for Arrays.equal to consider them to be equal.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM