tags:

views:

614

answers:

1

Hi there,

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()*);
}
A: 

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:

item myItem = itemList.elementAt(n);

fails because java can't auto-cast to a more specific class. You'd have to use:

Object myItem = itemList.elementAt(n);

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:

for(...)
{
    item myItem = (item) itemList.elementAt(n);
    myItem.method();
}

From then on you just use myItem.

Bill K
Remember i'm using Java Micro Edition. I'm getting the error:generics are not supported in -source1.3type java.util.vector does not take parameters
Garbit
Then use the cast... I think I may have gotten the syntax wrong though--I'll go edit it to be sure.
Bill K
getItem does not exist in micro edition, i tried elementAt(x) but that didnt like it either
Garbit
ElementAt will work. Check my new syntax.. I had it mixed up.
Bill K
Think it works, however i've just refactored in netbeans and its taken all the tags of item and mixed them up with the new class name :S oh dear! thankyou, i think your way works i'll report back after i sort this silly problem out :)
Garbit
Woo it builds :) thank you very very very much for your quick and accurate response!
Garbit