2

I would like to implement method that makes comparison of objects of the same type.

Is it feasible to implement isOnceOf() to be compile time type strict and give me compilation error at line 3?
Currently I'm getting only warning.

public static void main(String[] args) {
    System.out.println(isOneOf(3, 1, 2, 3)); // true
    System.out.println(isOneOf("A", "B", "C", "D")); // false
    System.out.println(isOneOf(1, "B", "C", "D")); // false, warn
}

public static <T> boolean isOneOf(T obj, T mate, T... mates) {
    if (obj == null) {
        return false;
    }
    if (obj.equals(mate)) {
        return true;
    }
    for (T m : mates) {
        if (obj.equals(m)) {
            return true;
        }
    }
    return false;
}
user2864740
  • 60,010
  • 15
  • 145
  • 220
Mike
  • 20,010
  • 25
  • 97
  • 140
  • 4
    Type-inference working against you =/. – Tunaki Apr 20 '16 at 15:31
  • 1
    Actually, yes, you can: `System.out.println(MyClass.isOneOf(1, "B", "C", "D"));` will fail. But you can't force the caller to use this form. – JB Nizet Apr 20 '16 at 15:34
  • 1
    http://stackoverflow.com/q/9299194/1743880 also http://stackoverflow.com/q/17390441/1743880. Also related http://stackoverflow.com/q/26538980/1743880 – Tunaki Apr 20 '16 at 15:36
  • For me, the only solution is the one shown here http://stackoverflow.com/q/9299194/1743880. Add a `Class` parameter. – Tunaki Apr 20 '16 at 15:47
  • Why would you want to do that? The reason you can't do it is because there is no type-safety reason to do it. – newacct May 04 '16 at 23:08
  • I'm trying to implement type-safe variant of `Arrays.asList(value1, value2).contains(value3)`. Common usage would be to use in if statements when some value is asserted against multiply constant values. Type-safeness is to eliminate any possibility of typo as list of values could be large and constants could be of different types. – Mike May 05 '16 at 06:33
  • @MykhayloAdamovych: It is already type-safe. Generics is not for you to impose arbitrary constraints. – newacct May 05 '16 at 19:25

1 Answers1

0

Thanks, Tunaki. Next works as expected.

public static <O, T extends O> boolean isMember(O obj, T mate, T... mates) {
    if (obj == null) {
        return false;
    }
    if (obj.equals(mate)) {
        return true;
    }
    for (T m : mates) {
        if (obj.equals(m)) {
            return true;
        }
    }
    return false;
}
Mike
  • 20,010
  • 25
  • 97
  • 140