Wednesday, 28 August 2013

How can I perform an order-independent equality check on lists?

How can I perform an order-independent equality check on lists?

I want to implement an equals method on a class where the equality of
instance is derived from the 'weak' equality of the contained lists, i. e.
the same order of the list elements is not necessary, whereas
java.util.List.equals(Object) (you can see its javadoc below) demands the
same order.
So, what's the best way to perform an order-independent equality check on
lists?



I thought of wrapping the lists into new lists, sorting them and then
performing the equals there on.
Or another approach (that would make this question obsolete): Use a
TreeSet instead, this way the order of the elements would always be the
same in sets with the equal elements.
/**
* Compares the specified object with this list for equality. Returns
* <tt>true</tt> if and only if the specified object is also a list, both
* lists have the same size, and all corresponding pairs of elements in
* the two lists are <i>equal</i>. (Two elements <tt>e1</tt> and
* <tt>e2</tt> are <i>equal</i> if <tt>(e1==null ? e2==null :
* e1.equals(e2))</tt>.) In other words, two lists are defined to be
* equal if they contain the same elements in the same order. This
* definition ensures that the equals method works properly across
* different implementations of the <tt>List</tt> interface.
*
* @param o the object to be compared for equality with this list
* @return <tt>true</tt> if the specified object is equal to this list
*/
boolean equals(Object o);



I know the answer and closed the tab. Afterwards I read a post on meta
about what to do in these kind of situations. But since my question was
cached by SO, I'm going to post it anyway. Maybe someone has the same
'problem' in future. I'm going to post the answer, if no one does.

No comments:

Post a Comment