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?
Try changing:
to :
From the documentation for Arrays.equals:
Since you need them to be equal irrespective of order, you have to sort them first for
Arrays.equalto consider them to be equal.