我想通過BigDecimal排序一個ArrayList和對磚牆來臨。我有一個類,看起來有點像這樣:Java收藏排序BigDecimal
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的活動是這樣的:
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。 –
好吧,但我怎麼去比較和排序我的unitprices是BigDecimal格式...我把它轉換爲字符串? – Jarede
不,您更改'compareTo'的返回類型以適合界面的正確簽名。 –