Java Collection排序BigDecimal

时间:2012-06-29 00:01:46

标签: java android collections arraylist bigdecimal

我正在尝试通过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

我一定错过了一些东西,它是什么?

干杯

1 个答案:

答案 0 :(得分: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. 类的名称应以大写字母开头。有一个“code conventions”文档说明了你应该做的事情和其他事情。
  2. 您覆盖equals - 除非您还覆盖equals,否则不应覆盖hashCode - 否则如果将此类的对象放入HashSet中,则会遇到大量问题, HashMap或其他使用哈希的集合。