I’m making a shopping list mobile application (Java ME) and i have two classes; item, list.
item object allows get/set name and quantity (string itemName, int quantity)
Now i need to store an array of items in my list class and be able to access the methods of the object from its list array index as follows; code below is pseudo code
item[] itemList = new item[]
for(int x = 0; x < itemList.length; x++)
{
String tempStoreOfName = itemList[x].getItemName()
System.out.println(tempStoreOfName)
}
I’ve googled a lot and found out that you can use vectors however i cannot seem to be able to call the object’s methods. Where am i going wrong?
I’ve done something like this in C# and i used ArrayLists however these are not supported in Java ME
Current Code
Vector itemList = new Vector();
for(int x = 0; x <= itemList.size(); x++)
{
dataOutputStream.writeUTF(itemList.elementAt(x)*here i cannot put .getItemName()*);
}
Since you can’t use generics you have to cast so that Java knows what you got out of the Vector. Notice that Vector.elementAt() returns Object? all you can do with it is treat it like an Object:
fails because java can’t auto-cast to a more specific class. You’d have to use:
which is useless to you because you want an item, not an Object.
You have to cast it to an object of the type you want:
From then on you just use myItem.