Mykhaylo Adamovych Mykhaylo Adamovych - 7 months ago 14
Java Question

Ensure generic vararg parameters have the same type

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;
}

Answer

Thanks, Tunaki. Next works as expected.

public static <T, O extends T> boolean isOneOf(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;
}