Java Number Equal areEqual(T... elements)

Here you can find the source of areEqual(T... elements)

Description

method that determines if all inputs are .equal().

License

Open Source License

Parameter

Parameter Description
elements to check if equal
T type of the elements

Return

true if all elements are equal or all elements are null. base cases of empty and single element are also considered "equal" in an empty fashion.

Declaration

public static <T> boolean areEqual(T... elements) 

Method Source Code

//package com.java2s;
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

public class Main {
    /**// w  w  w . j a  va  2  s .  c o m
     *
     * method that determines if all inputs are .equal().
     * the method handles null gracefully: if all elements are null, they are considered equal.
     *
     * the function assumes that equality is transitive, and doesn't all pair permutations.
     * it also assumes that no object .equals(null)
     *
     * @param elements to check if equal
     * @param <T> type of the elements
     * @return true if all elements are equal or all elements are null. base cases of empty and single element are
     * also considered "equal" in an empty fashion.
     */
    public static <T> boolean areEqual(T... elements) {

        //base cases, trivially "equal"
        if (elements.length < 2) {
            return true;
        }

        T first = elements[0];
        for (int i = 1; i < elements.length; i++) {
            T current = elements[i];

            //if both are null, then ok, but if only one is... bad.
            if (first == null) {
                if (current != null) {
                    return false;
                }
            }

            //if not null then safe to use equals method. assumes that it handles null correctly.
            else {
                if (!first.equals(current)) {
                    return false;
                }
            }

        }

        return true;
    }
}

Related

  1. areEqual(float left, float right)
  2. areEqual(int align, int mask)
  3. areEqual(int i, int j)
  4. areEqual(int o1, int o2)
  5. areEqual(T s1, T s2)
  6. areEquals(boolean first, boolean second)
  7. areEquals(double p, double q)