【发布时间】:2012-06-30 13:21:05
【问题描述】:
我正在尝试按 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
我一定是在路上错过了什么,那是什么?
干杯
【问题讨论】:
-
compareTo 不应返回 BigDecimal。
-
好的,但是我如何按照 BigDecimal 格式的单价进行比较和排序...我是否将其转换为字符串?
-
不,您更改
compareTo的返回类型以适合接口的正确签名。 -
您可能需要考虑
SortedSet实现(换句话说,TreeSet),并可能阅读用于标识符的正确大小写,例如在code conventions. -
凌晨 1 点脑子放个屁,你当然回来了……为 Paul Tomblin 欢呼。 @owlstead 我会检查一下 SortedSet。
标签: java android collections arraylist bigdecimal