比较器仍然是
Comparator<Item>
. 您要更改的是comparator的实现,以根据类型而不是id进行计算。
Comparator<Item> comparator = new Comparator<Item>(){
public int compare(Item a, Item b)
{
return a.getType() - b.getType();
}
}
项,则需要将类型的getter或属性公开。如果使用id也是一样。
不过,不知道你建议我怎么打电话
Item itemToFind = new Item();
itemToFind.setType(typeToFind);
Collections.binarySearch(items, itemToFind, comparator );
经过一番思考:
Item
Comparator
项目
还有针具。
返回int值的接口:
public interface Intgettable{
public int getInt();
}
必须实现此接口:
public class Item implements Intgettable{
private int id;
private int type;
public void setId(int id){
this.id = id;
}
public void setType(int type){
this.type = type;
}
public int getId(){
return id;
}
public int getType(){
return type;
}
public int getInt(){
return type;
}
}
搜索的关键是
Intgettable
1-使用扩展的类
.
public static class MyItemKey implements Intgettable{
private int value;
public MyItemKey(int v){
this.value = v;
}
@Override
public int getInt(){
return value;
}
}
MyItemKey typeToFind = new MyItemKey(6);
Intgettable typeTofind = new Intgettable(){
private int value = 6;
public int getInt(){
return value;
}
};
3-或使用lambda版本:
Intgettable typeTofind = ()->{return 6;};
比较器
将:
Comparator<Intgettable> comparator = new Comparator<Intgettable>(){
public int compare(Intgettable a, Intgettable b){
return a.getInt() - b.getInt();
}
};
最后在二进制搜索中使用它:
Collections.binarySearch(items, typeToFind, comparator );