-4

My requirement is I want to write custom Comparator library such that it can compare two objects return true if they are equal or false for example

public interface Icomparator<X, Y> {
    public boolean compare(X x, Y y);
}

public class ComparatorImpl<X, Y> implements Icomparator<X, Y> {

    @override
    public boolean compare(X x, Y y) {
        // logic for example as below.
        if (x == y)
            return true;

        return false;
    }
}

How this could be used to compare two objects and how this will be called to compare any two objects.

ernest_k
  • 44,416
  • 5
  • 53
  • 99
Vikki Lohana
  • 39
  • 2
  • 10
  • 7
    Comparison isn't meant to check (just) equality. `Comparator` does not return `boolean`. So *this* cannot be used as `Comparator`. If all you're looking for is to check whether any two objects are *equal*, then the standard way to do that is to override `Object.equals` in their respective classes. Then you can simply call `x.equals(y)`. – ernest_k Jan 27 '20 at 18:56
  • 2
    It doesn't make sense for objects of different types to be considered "equal"; but it's reasonable to have some notion of two objects being "equivalent". Indeed, [Guava has such a class](https://guava.dev/releases/23.0/api/docs/com/google/common/base/Equivalence.html). – Andy Turner Jan 27 '20 at 19:50
  • 1
    It is a very strange way of software development, to first create an interface and then ask us how to use it. – Holger Feb 04 '20 at 13:12

1 Answers1

-2

I consider that you can use equals or ==

private boolean check(Object comparatorOne, Object comparatorTwo) {
        if (comparatorTwo instanceof String) {
            return comparatorOne.equals(comparatorTwo);
        } else {
            return comparatorOne == comparatorTwo;
        }
    }
Alejandro Gonzalez
  • 1,221
  • 4
  • 15
  • 30