我有一个任务:
public interface Task {
}
然后我有这些实现:
public interface Task__Init extends Task {
void init(Element e);
}
public interface Task__Hit_Test extends Task {
boolean hit_test(Element e, float x, float y);
}
public interface Task__Draw extends Task {
void draw(Element e);
}
我还有一个类可以保存这些实现的实例:
static public class Task_Holder<T extends Task> {
public int task_id;
public Task_Type type;
public T task;
// ...
}
然后我有一个类来保存这些,其中最后一个 ArrayList 保存所有它们(all_task_holders)
static public class Implementation_Context {
public HashMap<String, ArrayList<Task_Holder<Task__Init>>> init_solvers = new HashMap<>();
public HashMap<String, ArrayList<Task_Holder<Task__Draw>>> draw_solvers = new HashMap<>();
public HashMap<String, ArrayList<Task_Holder<Task__Hit_Test>>> hit_test_solvers = new HashMap<>();
public ArrayList<Task_Holder<? extends Task>> all_task_holders = new ArrayList<>();
// ...
}
现在出现了一个问题:
static public Task_Holder<?> find_task_holder(int task_id) {
Comparator<Task_Holder<?>> comparator = (a, b)-> {
if (a.task_id < b.task_id) return -1;
if (a.task_id > b.task_id) return 1;
return 0;
};
Collections.sort(ctx.implementation.all_task_holders, comparator);
Task_Holder<?> key = new Task_Holder<>();
key.task_id = task_id;
int index = Collections.binarySearch(ctx.implementation.all_task_holders, key);
for (Task_Holder<?> th : ctx.implementation.all_task_holders) {
if (th.task_id == task_id) {
return th;
}
}
assert false; // should we find things that are not there?
return null;
}
对于我得到的二进制搜索(我在这里将其设为代码块,否则 stackoverflow 会因某种原因删除单词?):
The method binarySearch(List<? extends Comparable<? super T>>, T) in the type Collections is not applicable for the arguments (ArrayList<sfjl_ui.Task_Holder<?>>, sfjl_ui.Task_Holder<capture#6-of ?>)
我不知道如何解决这个问题。每次尝试都会破坏其他东西(例如我破坏了高 3 行的排序)。 这感觉就像用其他信用卡还清信用卡债务一样,你永远不会赢。
我该如何解决这个问题?
最佳答案
传递比较器as an additional argument :
int index = Collections.binarySearch(ctx.all_task_holders, key, comparator);
关于java - 使用泛型进行二进制搜索并捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59040706/