【发布时间】:2016-04-19 02:13:35
【问题描述】:
我正在尝试设计一个拼车系统。这是我的基础对象
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;
}
}
【问题讨论】:
-
它在那里说。您的中间参数必须是 T 类型,在本例中是 Uber 类型。传递给它一个 Uber 对象而不是一个浮点数。
-
第二个参数必须是 Uber 对象,而不是浮点数。阅读文档或错误
标签: java collections iterator comparator