需要实现类似于 java.util.Collections 的类的方法——一个具有静态方法的库类,旨在为元素的一般集合提供有用的功能。如果它们是整数元素,我知道该怎么做。现在我需要将代码转换为通用类型。任何帮助都感激不尽!
从:
import java.util.Arrays;
public final class Selector {
private Selector() {
}
public static int nearest(int[] a, int val) {
if (a == null || a.length == 0) {
throw new IllegalArgumentException("a is null or has zero-length");
}
int idx = 0;
int distance = Math.abs(a[0]-val);
for (int c = 1; c < a.length; c++) {
int cdistance = Math.abs(a[c] - val);
if (cdistance <= distance) {
idx = c;
distance = cdistance;
}
}
int theNumber = a[idx];
return theNumber;
}
}
到
import java.util.Collections;
import java.util.Collection;
import java.util.ArrayList;
import java.util.Iterator;
public final class Selector {
private Selector() { }
public static <T> T nearest(Collection<T> c, T val, Telemeter<T> tm) {
.
.
.
}
}
遥测仪
import java.util.Comparator;
public interface Telemeter<E> extends Comparator<E> {
double distance(E e1, E e2);
}