ternes3 ternes3 - 1 year ago 69
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 Source
public static boolean AreAllSame(String[] array)
    boolean isFirstElementNull = array[0] == null;
    for(int i = 1; i < array.length; i++)
            if(array[i] != null) return false;
            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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download