You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@commons.apache.org by Lukas Bradley <lu...@somnia.com> on 2004/12/23 21:28:56 UTC
[collections] ListUtil Method Proposal: isEqualUnordered
I needed a method like isEqualList(final Collection list1, final
Collection list2), but did not consider order as important.
I don't know if this is a welcome addition to the ListUtil class, but I
am posting it here to be used as desired.
/**
* <p>
* Tests two lists for value-equality as per the equality contract
in List.equals(java.lang.Object), with one
* exception: the lists <b>do not </b> have to have the objects in
the same order.
* </p>
*
* <p>
* The relevant text (slightly paraphrased and reworded as this is a
static method) is:
* </p>
*
* <blockquote>Compares the two list objects for equality. Returns
true if and only if both lists have the same size,
* and all corresponding pairs of elements in the two lists are
equal. (Two elements e1 and e2 are equal if (e1==null ?
* e2==null : e1.equals(e2)).) In other words, two lists are defined
to be equal if they contain the same elements
* <i>in any order </i>. This definition ensures that the equals
method works properly across different
* implementations of the List interface. </blockquote>
*
* <p>
* This method iterates over all items in list one, making sure they
are contained in list two.
* </p>
*
* <p>
* <b>Note: </b> The behaviour of this method is undefined if the
lists are modified during the equals comparison.
* </p>
*
* @param pList1
* The first list, may be null.
* @param pList2
* The second list, may be null.
* @return Whether the lists are equal by value comparison,
regardless of order.
* @see java.util.List#contains(java.lang.Object)
*/
public static final boolean isEqualUnordered(final Collection
pList1, final Collection pList2)
{
// If both lists are null, they are considered equal
if (pList1 == pList2)
return true;
// If one of the lists is null, or the lists have different
sizes, they are NOT equal
if (pList1 == null || pList2 == null || pList1.size() !=
pList2.size())
return false;
Iterator it1 = pList1.iterator();
Object obj1;
while (it1.hasNext())
{
obj1 = it1.next();
// If the object is null, or the second list does not contain
the object, return false
if (obj1 == null || !pList2.contains(obj1))
return false;
}
return true;
} // public static final boolean isEqualUnordered(final Collection
pList1, final Collection pList2)
---------------------------------------------------------------------
To unsubscribe, e-mail: commons-dev-unsubscribe@jakarta.apache.org
For additional commands, e-mail: commons-dev-help@jakarta.apache.org