我正在设计一个共享系统。这是我的基本对象
package rider;
import java.util.TreeMap;
public class Uber{
String driver;
TreeMap<Float,String> destination;
public Uber(String d)
{
driver=d;
destination = new TreeMap<Float,String>();
}
private void addTimeDest(float tm, String dest)
{
destination.put(tm, dest);
}
float getTsum() {
float tsum=0;
for (float f : this.destination.keySet())
tsum+=f;
return tsum;
}
}因此,每个对象都有一个驱动程序和该驱动程序的关联时间<->目标映射。最后,我想按时间字段(即树状地图的键)对这类对象的列表进行排序。
下面是我为上面创建的迭代器类
package rider;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
public class UberIterator implements Iterator<Uber> {
int currIndex=0;
ArrayList<Uber> uList;
Comparator<Uber> timeComparator = new Comparator<Uber>(){
public int compare(Uber u1, Uber u2) {
return (int) (u1.getTsum()-u2.getTsum());
}
};
public UberIterator(ArrayList<Uber> nList)
{
uList=nList;
Collections.sort(uList,timeComparator);
}
public boolean hasNext() {
return currIndex<uList.size();
}
public Uber next() {
return uList.get(currIndex++);
}
@Override
public void remove() {
uList.remove(currIndex--);
}
public void remove(String d) {
int rindex=-1;
for(int u=0 ; u<currIndex; u++)
{
if(uList.get(u).driver.equals(d))
{
rindex=u;
break;
}
}
if(rindex<0)
System.out.println("Driver not found.");
else
{
uList.remove(rindex);
currIndex--;
}
}
public void remove(float tm) {
int rindex=Collections.binarySearch(uList, tm, timeComparator);
if(rindex<0)
{
System.out.println("Exact time not found. Closest will be removed.");
}
else
{
uList.remove(rindex);
currIndex--;
}
}
}基本上,用比较器
Comparator<Uber> timeComparator = new Comparator<Uber>(){
public int compare(Uber u1, Uber u2) {
return (int) (u1.getTsum()-u2.getTsum());
}
};我正试着按内部树状图的键分类。但我知道这个错误
The method binarySearch(List<? extends T>, T, Comparator<? super T>) in the type Collections is not applicable for the arguments (ArrayList<Uber>, float, Comparator<Uber>)在…
int rindex=Collections.binarySearch(uList, tm, timeComparator);我应该如何纠正我的实施?
跟踪
有什么方法可以覆盖Collections.binarySearch吗?如果Uber实现了Comparable,并在那里定义了上面所述的比较方法,该怎么办?难道不应该用time维度自动搜索吗?否则,定义用于排序的自定义比较器有什么好处?我想以某种方式对列表进行排序的唯一原因是以后能够高效地搜索它。
package rider;
import java.util.TreeMap;
public class Uber implements Comparable<Uber> {
String driver;
TreeMap<Float,String> destination;
public Uber(String d)
{
driver=d;
destination = new TreeMap<Float,String>();
}
private void addTimeDest(float tm, String dest)
{
destination.put(tm, dest);
}
public int compareTo(Uber u) {
return (int) (this.getTsum()-u.getTsum());
}
float getTsum() {
float tsum=0;
for (float f : this.destination.keySet())
tsum+=f;
return tsum;
}
}发布于 2016-04-19 02:18:44
int rindex=Collections.binarySearch(uList,tm,timeComparator);
不能在float中搜索List<Uber>。
你的alternatives...frankly没那么好。您可以创建一个包含Uber值的假tm,并将其传递给Collections.binarySearch。您可以使用像番石榴这样的库,调用Lists.transform(ubers, getTmFunction)来创建视图,并将其传递给Collections.binarySearch。您可以自己重新实现二进制搜索。
https://stackoverflow.com/questions/36707355
复制相似问题