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

Using a comparator to sort an ArrayList of objects, code is unreachable

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

如您所见,我正在尝试@Override 在超类中找到的方法 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 总是 returns true,您可以安全地忽略由 super.add(pr) 编辑的值 return 并添加一个 return 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;
}

问题是您正在做的return super.add( pr )return 关键字 returns 值并结束函数的执行,确保您的代码永远不会执行

public class BetterBasket extends Basket implements Serializable
{
  private static final long serialVersionUID = 1L;

  @Override
  public boolean add( Product pr )
  { 
    return super.add( pr ); // returns the value returned by super.add( pr ) and ends the function
    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 super.add( pr );

在您要执行的其余代码之前。 Return 立即终止该方法,因此您拥有的所有代码都不会 运行 这就是您收到无法访问错误的原因。您只需从 super.add() 中删除 return 即可消除此错误