English 中文(简体)
Most compact way to compare three objects for equality using Java?
原标题:
  • 时间:2009-11-16 15:46:41
  •  标签:
  • java
  • equals

What s the most compact code to compare three objects for (semantic) equality using Java? I have a business rule that the objects must be unique i.e. A is different to B, A is different to C and B is different to C.

Assume that the objects are all of the same class and have correctly overridden equals and hashCode methods. A slight wrinkle is that object C could be null—if this is the case then A and B have to be different to each other.

I have some code but it s a bit workmanlike for my tastes.

最佳回答

As the OP said A and B are never null, C may be null, use this:

if(A.equals(B) || B.equals(C) || A.equals(C))
   // not unique

and, as others have already suggested, you can put it in a method for reuse. Or a generic method if you need more reuse ;-)

Note that in Java, a feature of equals is that if its argument is null it should not throw, but return false.

问题回答

Since I never start a Java project without using Apache commons-lang, try ObjectUtils.equals (it s null safe):

if (ObjectUtils.equals(a, b) || ObjectUtils.equals(b, c) || ObjectUtils.equals(a, c)) {
  // error condition
}

Put that logic in a generic method, and you ll do even better.

While the business logic allows C to be null, in scenarios like this, it s often better to code defensively and assume that either A or B could be null as well.

You can abstract that method in a utilities method like:

public boolean allUnique(Object... objs) {
  Set<Object> set = new HashSet<Object>();
  for (Object o : objs)
    set.add(o);
  return set.size() == objs.length
}

The method may not perform well for small numbers (due to the overhead of creating the Set and the varargs array). However, it grows linearly O(n), and for large values it s better than the quadratic growth of a nested if statements.

boolean areDistinct(Object a, Object b, Object c) {
    return (!a.equals(b) &&
            (c == null || (!c.equals(a) && !c.equals(b))));
}

As long as your objects implement equals, you can use the Stream API to get a distinct set of values, and if that distinct count is 1, they are all the same.

boolean allEqual = Stream.of(obj1, obj2, obj3).distinct().count() == 1

As the apache s common.lang3.ObjectUtils.equals() is @Deprecated. Use Objects.equals(aObj,bObj). Comparison should be made with && if you want that all 3 objects are the same. Use || if you want that just one combination of a&b, a&c or b&c is the same.

/**
 * Compare 3 objects of the same {@link TYPE}, if they are all equal using {@link Objects#equals(Object, Object)}.
 * 
 * @param aObj the 1st object
 * @param bObj the 2nd object
 * @param cObj the 3th object
 * @param <TYPE> the type of the objects
 * @return true if the are all the same
 */
public static <TYPE> boolean equals(TYPE aObj, TYPE bObj, TYPE cObj) {
    return Objects.equals(aObj, bObj) && Objects.equals(bObj, cObj) && Objects.equals(cObj, aObj);
}
package com.test;

public class Equality {

    public static void main(String[] args) {

        Boolean flag;

        int[] arr={1,1,1,12};
        flag=check_equal(arr);
        System.out.println(flag);
    }

    public static Boolean check_equal(int[] arr){
        Boolean flag=true;

        outerloop:
        for(int i=1; i< arr.length; i++)
            {
                for(int j=1; j< arr.length; j++){
                    if(arr[i]==arr[j]){
                        flag=true;
                    }   
                    else{
                        flag=false;
                        break outerloop;
                    }

                }

            }
        return flag;
    }
}




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签