我认为您要么需要一个,要么需要Comparator<Object>
一个E[]
. 对于后者,我建议查看这两篇文章:
鼓励阅读以上内容。
选项 1:Array.newInstance()
假设 item 永远不会为空
根据我在上述帖子中读到的内容,如果您知道 item 永远不会null
,您可以尝试这样的事情......
@SuppressWarnings("unchecked")
private Location findFirst(E item) {
Location current;
int closestMatchArray1;
int closestMatchArray2;
// Object[] firstItemInArray2 = new Object[numArrayInUse];
// Object firstItem;
E[] firstItemInArray2
= (E[]) Array.newInstance(item.getClass(), numArrayInUse);
E firstItem;
Comparator<E> comparator = new CompareElement();
for (int i = 0; i < numArrayInUse; i++) {
firstItem = (E) topArray[i];
firstItemInArray2[i] = firstItem;
}
closestMatchArray1 = Arrays.binarySearch(firstItemInArray2, item, comparator);
选项 2:Array.newInstance()
需要类参数
如果不能保证 item 永远不会是null
,并且不能对null
值提供任何特殊处理,则可以强制Class<?>
传入参数,如下...
@SuppressWarnings("unchecked")
private Location findFirst(E item, Class<E> clazz) {
Location current;
int closestMatchArray1;
int closestMatchArray2;
// Object[] firstItemInArray2 = new Object[numArrayInUse];
// Object firstItem;
E[] firstItemInArray2
= (E[]) Array.newInstance(clazz, numArrayInUse);
E firstItem;
Comparator<E> comparator = new CompareElement();
for (int i = 0; i < numArrayInUse; i++) {
firstItem = (E) topArray[i];
firstItemInArray2[i] = firstItem;
}
closestMatchArray1 = Arrays.binarySearch(firstItemInArray2, item, comparator);
选项 3:对象比较器包装器
丑陋,但它有效
或者,您可以创建一个Comparator<Object>
来包装您现有的Comparator<E>
,如下所示(我认为这有点像 hack,但它对我来说始终如一)......
private Location findFirst(E item) {
Location current;
int closestMatchArray1;
int closestMatchArray2;
Object[] firstItemInArray2 = new Object[numArrayInUse];
Object firstItem;
// Comparator<E> comparator = new CompareElement();
Comparator<Object> comparator = new Comparator<Object>() {
private final Comparator<E> delegate = new CompareElement();
@Override
@SuppressWarnings("unchecked")
public int compare(Object o1, Object o2) {
return delegate.compare((E) o1, (E) o2);
}
};
for (int i = 0; i < numArrayInUse; i++) {
firstItem = topArray[i];
firstItemInArray2[i] = firstItem;
}
closestMatchArray1 = Arrays.binarySearch(firstItemInArray2, item, comparator);
希望这可以帮助!