is Collection Equals - Android java.util

Android examples for java.util:Collection

Description

is Collection Equals

Demo Code


//package com.java2s;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

public class Main {
    public static <E> boolean isCollectionEquals(Collection<E> collection1,
            Collection<E> collection2) {
        boolean equals = true;
        if (collection1 != null && null == collection2) {
            equals = false;/*from  ww  w .ja v  a 2 s  . c  o m*/
        } else if (collection2 != null && null == collection1) {
            equals = false;
        } else if (collection1 != null && collection2 != null) {
            int size1 = collection1.size();
            int size2 = collection2.size();
            if (size1 != size2) {
                equals = false;
            } else {
                Iterator<E> iterator1 = collection1.iterator();
                Iterator<E> iterator2 = collection2.iterator();
                while (iterator1.hasNext() && iterator2.hasNext()) {
                    if (!iterator1.next().equals(iterator2.next())) {
                        equals = false;
                        break;
                    }
                }
            }
        }
        return equals;
    }

    /**
     * Returns a {@code List} of the objects in the specified array.
     * 
     * @param array the array.
     * @return a {@code List} of the elements of the specified array.
     */
    public static <T> List<T> asList(T[] array) {
        List<T> list = new ArrayList<T>();
        for (T object : array) {
            list.add(object);
        }
        return list;
    }

    /**
     * Checks if the beginnings of two byte arrays are equal.
     * 
     * @param array1 the first byte array
     * @param array2 the second byte array
     * @param length the number of bytes to check
     * @return true if they're equal, false otherwise
     */
    public static boolean equals(byte[] array1, byte[] array2, int length) {
        if (array1 == array2) {
            return true;
        }
        if (array1 == null || array2 == null || array1.length < length
                || array2.length < length) {
            return false;
        }
        for (int i = 0; i < length; i++) {
            if (array1[i] != array2[i]) {
                return false;
            }
        }
        return true;
    }
}

Related Tutorials