Im relatively new to Java and have started implementing an ArrayList
using:
private ArrayList items;
initialising it using:
items = new ArrayList();
adding to it using:
items.add(item); - where item is of class Item
the problem is when i am calling the Item from the arraylist:
Item getitem = items.get(0);
I get the error message: incompatible types - Item expected but Object
found.....
Any help would be great :D
Tobias Schröer - 28 Nov 2006 16:23 GMT
Lawrence schrieb:
> Im relatively new to Java and have started implementing an ArrayList
> using:
[quoted text clipped - 12 lines]
>
> Item getitem = items.get(0);
If you don't use generics (you don't, see your code above), you must
explicitly cast the object you get from a list:
Item getItem = (Item)items.get(0);
Or, if you are working with Java 1.5 or above, you should use generics,
as long as you only store Item objects (or subtypes of Item) in your list:
private ArrayList<Item> items = new ArrayList<Item>();
items.add(item); // you can only add Item or sub types
Item getItem = items.get(0); // now withou casting
> I get the error message: incompatible types - Item expected but Object
> found.....
>
> Any help would be great :D
HTH,
Tobi
Doug Pardee - 28 Nov 2006 16:24 GMT
> Item getitem = items.get(0);
You need to cast the returned object to the expected type:
Item getitem = (Item) items.get(0);
Alternatively, if you're using Java 5.0 you could do it with generics:
private ArrayList<Item> items;
items = new ArrayList<Item>();
items.add(item);
Item getitem = items.get(0);
trippy - 28 Nov 2006 21:54 GMT
In article <1164729017.173636.245310@80g2000cwy.googlegroups.com>,
Lawrence took the hamburger meat, threw it on the grill, and I said "Oh
Wow"...
> Im relatively new to Java and have started implementing an ArrayList
> using:
[quoted text clipped - 17 lines]
>
> Any help would be great :D
Cast it to the type you need.
Item itm = (Item) items.get(0);

Signature
trippy
mhm31x9 Smeeter#29 WSD#30
sTaRShInE_mOOnBeAm aT HoTmAil dOt CoM
NP: "Aces High" -- Iron Maiden
"Now, technology's getting better all the time and that's fine,
but most of the time all you need is a stick of gum, a pocketknife,
and a smile."
-- Robert Redford "Spy Game"