Mykhaylo Adamovych Mykhaylo Adamovych - 1 year ago 74
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 Source

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;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download