【发布时间】:2013-08-12 23:37:00
【问题描述】:
我有我的数组列表
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;
}
}
【问题讨论】:
-
显示您的
Item类代码。mkyong.com/java/…。检查这个 -
与您的问题无关,但无论如何都值得更改:将 ArrayList
- 更改为 List
- 。
- 更改为 List
-
试试 Item[] itemArr = itemList.toArray(new Item[itemList.size()]);
-
@Captain-RayneMartin 试试我的答案,让我知道它是否有效
标签: android listview casting arraylist