我有我的 ArrayList
ArrayList<Item> itemList = new ArrayList<Item>();
然后用项目填充它。稍后,我想循环访问项目属性以获取数据,但是
Item[] itemArr = (Item[]) itemList.toArray();
这给了我错误:
java.lang.ClassCastException: java.lang.Object[] cannot be cast to com.raynemartin.SAAndroidAppCompetition.Item[]
如果这注定要失败,我还能如何访问项目的属性?这些项目位于 ArrayList 中,因此它们可以填充和 android ListView。现在我想对 ArrayList 进行排序,但需要访问我的 Item 类的 .getRating() 方法。
Item[] itemArr= (Item[])itemList.toArray();
for(int i =0;i<itemArr.length;i++){
for(int j=i;i<itemArr.length;j++){
if(itemArr[j].getRating()>itemArr[i].getRating()){
Item temp = itemArr[j];
itemArr[j] = itemArr[i];
itemArr[i] = temp;
}
}
}
}
编辑 - 这是项目类代码
public class Item {
private String title;
private String category;
private String downloads;
private double rating;
private Bitmap icon;
public Item(String title, String category, String downloads,double rating,Bitmap icon) {
this.title = title;
this.category = category;
this.downloads = downloads;
this.icon = icon;
this.rating = rating;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getDownloads() {
return downloads;
}
public void setDownloads(String downloads) {
this.downloads = downloads;
}
public Bitmap getIcon() {
return icon;
}
public void setIcon(Bitmap icon) {
this.icon = icon;
}
public double getRating() {
return rating;
}
public void setRating(double rating) {
this.rating = rating;
}
}