ternes3 ternes3 - 5 months ago 12
Java Question

In Java, how can I test if an Array contains the same value?

I'm looking for a method to detect if all objects within an array(list) are the same.
e. g:

arraylist1 = {"1", "1", "1", "1"} // elements are the same
arraylist2 = {"1", "1", "0", "1"} // elements are not the same


Thanks for help

Answer
public static boolean AreAllSame(String[] array)
{
    boolean isFirstElementNull = array[0] == null;
    for(int i = 1; i < array.length; i++)
    {
        if(isFirstElementNull)
            if(array[i] != null) return false;
        else 
            if(!array[0].equals(array[i])) return false;
    }

    return true;
}

Please feel free to correct any syntax mistakes. I fear my Java-fu may be lacking today.

Comments