gpt4 book ai didi

java - 使用比较器对对象的 ArrayList 进行排序,代码无法访问

转载 作者:行者123 更新时间:2023-12-01 07:47:45 25 4
gpt4 key购买 nike

  @Override
public boolean add( Object o )
{
return super.add( o );
// Sorts arraylist
Collections.sort(this, new Comparator<Object>() {
// code here
}
});
}
}

正如你所看到的,我试图@Override在父类(super class)中找到的方法add,并在子类中实现Collections.sort()。我添加了一个比较器来帮助实现这一点,但是它表示代码无法访问。

如有任何建议,我们将不胜感激。

最佳答案

您有一个 return 语句作为第一个语句,因此它后面的任何内容都是无法访问的代码:

public boolean add( Product pr )
{
return super.add(pr);
Collections.sort(this, new Comparator<Product>() { // unreachable
@Override
public int compare(Product p1, Product p2) {
double f = p1.getPrice();
double s = p2.getPrice();
if (f == s) return 0;
return f<s ? 1 : -1;
}
});
}

由于 List.add 始终返回 true,因此您可以安全地忽略 super.add(pr) 返回的值并添加返回值对 List 进行排序后的语句:

public boolean add( Product pr )
{
super.add(pr);
Collections.sort(this, new Comparator<Product>() {
@Override
public int compare(Product p1, Product p2) {
double f = p1.getPrice();
double s = p2.getPrice();
if (f == s) return 0;
return f<s ? 1 : -1;
}
});
return true;
}

关于java - 使用比较器对对象的 ArrayList 进行排序,代码无法访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47890368/

25 4 0