I needed a method to get the median of 3 values, I thought it a good opportunity to write a generic method since I don't really have that practiced. I wrote this and it seems pretty straight-forward, though I get a warning, but it seems to work fine, according to my tests.
I'm aware I could use an inherently sorted set, or Collections.sort()
, but this approach is for the sake of understanding.
I want to pinpoint a few things:
- I noticed this doesn't work if I tried to declare
medianHelper
withArrays.asList(a, b, c)
why is this? Trying to search this gives me unrelated results and it's otherwise elusive since I'm not sure what is happening. I get anUnsupportedOperationException
, but this is not present the way I have it below. - Why am I getting a warning? What is wrong/missing?
The method follows:
private static <T extends Comparable> T median(T a, T b, T c) {
List<T> medianHelper = new ArrayList<>();
T max;
T min;
medianHelper.add(a);
medianHelper.add(b);
medianHelper.add(c);
if (a.compareTo(b) >= 0) {
max = a;
min = b;
} else {
max = b;
min = a;
}
if (max.compareTo(c) == -1) {
max = c;
}
if (min.compareTo(c) >= 0) {
min = c;
}
medianHelper.remove(max);
medianHelper.remove(min);
return medianHelper.get(0);
}