Sunday, 11 August 2013

Casting Object[] to custom Item[]

Casting Object[] to custom Item[]

I have my ArrayList
ArrayList<Item> itemList = new ArrayList<Item>();
It is then populated with Items. Later on, I want to access the items
attributes in a loop to get data but
Item[] itemArr = (Item[]) itemList.toArray();
This gives me error:
java.lang.ClassCastException: java.lang.Object[] cannot be cast to
com.raynemartin.SAAndroidAppCompetition.Item[]
If this is destined to fail, how else can I access attributes of Items?
The Items are in an ArrayList so they can populate and android ListView.
Now I want to sort the ArrayList, but need to access the .getRating()
method of my Item class.
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;
}
}
}
}

No comments:

Post a Comment