1

我正在尝试按 BigDecimal 对 ArrayList 进行排序并遇到砖墙。我有一个看起来有点像这样的类:

public class deal implements Comparable<deal>{

protected BigDecimal bdPrice;
protected int iQuantity;
protected String sDealType;
protected UUID dealUniqueID;
protected int dealID;
protected BigDecimal bdUnitPrice;

public deal(){
    bdPrice         = new BigDecimal("0");
    bdUnitPrice     = new BigDecimal("0");
    iQuantity       = 1;
    sDealType       = "Single item";
    dealUniqueID    = UUID.randomUUID();
    dealID          = 0;
}

private void setUnitPrice(){
    this.bdUnitPrice = this.bdPrice.divide(new BigDecimal(this.iQuantity));
}

public BigDecimal compareTo(deal oDeal) {
    // TODO Auto-generated method stub
    return bdUnitPrice.compareTo(oDeal.getUnitPrice());
}

public boolean equals(deal oDeal) {
    if (!(oDeal instanceof deal))
        return false;
    deal oD = (deal) oDeal;

    return this.bdUnitPrice.equals(oD.bdUnitPrice);
}
}

我的主要 Android Activity 如下所示:

public class SupermarketDealsActivity extends Activity {
private ArrayAdapter<deal> itemAdapter;
private ListView lvDeals;
private ArrayList<deal> itemArray;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    SetUpView();
}

private void SetUpView(){
lvDeals                     = (ListView)this.findViewById(R.id.listDeals);

    itemArray                   = new ArrayList<deal>();
    itemArray.clear();

    itemAdapter                 = new ArrayAdapter<deal>(this, android.R.layout.simple_list_item_1,itemArray);
    lvDeals.setAdapter(itemAdapter);
}

private void CreateADeal(int iQuantity, BigDecimal bdPrice) {
    deal oDeal                  = new deal();

    oDeal.setQuantity(iQuantity);
    oDeal.setPrice(bdPrice);

    CreateListDeals(oDeal);
}

private void CreateListDeals(deal oDeal){
    itemArray.add(oDeal);
    Collections.sort(itemArray,Collections.reverseOrder());
    itemAdapter.notifyDataSetChanged();
}
}

在我的 java 类中,我的 compareTo 方法出现错误:

类型不匹配:无法从 int 转换为 BigDecimal

我一定是在路上错过了什么,那是什么?

干杯

4

1 回答 1

4
public BigDecimal compareTo(deal oDeal) {
    // TODO Auto-generated method stub
    return bdUnitPrice.compareTo(oDeal.getUnitPrice());
}

既不匹配接口的签名,也不匹配的返回类型bdUnitPrice.compareTo。将其更改为:

public int compareTo(deal oDeal) {
    // TODO Auto-generated method stub
    return bdUnitPrice.compareTo(oDeal.getUnitPrice());
}

我应该提到的其他几件事(来自评论):

  1. 类的名称应以大写字母开头。有一个“代码约定”文档说明了你应该做的其他事情。
  2. 你重写equals——你永远不应该重写equals,除非你也重写hashCode——否则如果你把这个类的对象放入一个 HashSet、HashMap 或其他使用哈希的集合中,你会遇到很多问题。
于 2012-06-29T00:11:32.300 回答