Compares two collections without giving credit to the order. - Android java.util

Android examples for java.util:Collection

Description

Compares two collections without giving credit to the order.

Demo Code


import com.android.cartloading.models.CartProduct;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class Main{
    /**/*from ww  w  .jav a  2 s  .  com*/
     * Compares two collections without giving credit to the order.
     *
     * @param a one of the two lists to compare
     * @param b the other one of the two lists to compare
     * @return if the two given lists are equal.
     */
    public static <T> boolean areCollectionsEqual(Collection<T> a,
            Collection<T> b) {

        if ((a == null && b == null))
            return true;
        if ((a == null && b != null) || (a != null && b == null))
            return false;

        int aSize = a.size();
        int bSize = b.size();

        if (aSize != bSize)
            return false;

        return internalAreCollectionsEqual(a, b, aSize);
    }
    private static <T> boolean internalAreCollectionsEqual(Collection<T> a,
            Collection<T> b, int size) {

        List<T> aCopy, bCopy;
        aCopy = new ArrayList<T>(a);
        bCopy = new ArrayList<T>(b);

        for (int i = 0; i < size; i++) {
            T item = aCopy.get(i);
            if (!bCopy.remove(item))
                return false;
        }

        if (!bCopy.isEmpty())
            return false;

        return true;
    }
}

Related Tutorials