我需要一种方法来获得3个值的中位数,我认为这是一个很好的机会来编写一个通用的方法,因为我实际上没有这样做。我写了这篇文章,看起来非常直截了当,虽然我得到了一个警告,但根据我的测试,它似乎工作正常。
我知道我可以使用固有排序的集合,或 Collections.sort(),但这种方法是为了理解。
我想查明几件事:
该方法如下:
private static< T extends Comparable> T中位数(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(apareTo(b)> = 0){ max = a; min = b; } else { max = b; min = a; } if(maxpareTo(c)== -1){ max = c; } if(minpareTo(c)> = 0){ min = c; } medianHelper.remove(max); medianHelper.remove(min); 返回medianHelper.get(0);解决方案
类型参数 T ,比如 Comparable 也是通用的。
它应该是:
private static< T extends Comparable <? super T>> T中位数(T a,T b,T c)此外,您可以排序> medianHelper 列表,因为它的元素将> Comparable 。因此,您的方法可以显着缩短为:
private static< T extends Comparable< ;? super T>> T中位数(T a,T b,T c){ List< T> medianHelper = Arrays.asList(a,b,c); Collections.sort(medianHelper); return medianHelper.get(1); $ / code>请注意 Arrays.asList()返回一个不可修改的列表,这意味着您不允许在创建元素后添加/删除元素。如果你想自己进行比较,你可以使用新的ArrayList<> c $ c>来代替 Arrays.asList()然后手动将元素添加到它。
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:
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 (apareTo(b) >= 0) { max = a; min = b; } else { max = b; min = a; } if (maxpareTo(c) == -1) { max = c; } if (minpareTo(c) >= 0) { min = c; } medianHelper.remove(max); medianHelper.remove(min); return medianHelper.get(0); }解决方案
You haven't correctly introduced the type-parameter T, as Comparable is generic, too.
It should rather be:
private static <T extends Comparable<? super T>> T median(T a, T b, T c)Furthermore, you can just sort the medianHelper list, since its elements will be Comparable. So your method can be significantly shortened to:
private static <T extends Comparable<? super T>> T median(T a, T b, T c) { List<T> medianHelper = Arrays.asList(a, b, c); Collections.sort(medianHelper); return medianHelper.get(1); }Note that Arrays.asList() returns an unmodifiable list, which means you're not allowed to add/remove elements after it's created. If you wish to do the comparisons yourself, you can use new ArrayList<> instead of Arrays.asList() and then manually add the elements to it.
更多推荐
通用方法来查找3个值的中位数
发布评论