I need some help in trying to find out how to cast a method that is within an object which is inside a LinkedList.

Let me try to explain:

I already know that I have to use a wrapper to convert an object back into another state. The think I am confused about is how to use a method from the object. What I am doing is storing Objects called Item into a LinkedList. I have a method from Item that gets a stored variable. Heres the code for my Item class.

public class Item implements Comparable
	private int myId;
	private int myInv;
	public Item(int id, int inv)
		myId = id;
		myInv = inv;
	public int getId() 
		return myId;
	public int getInv() 
		return myInv;
	public int compareTo(Object otherObject) 
		Item right = (Item)otherObject;
		return myId - right.myId;
	public boolean equals(Object otherObject) 
		return compareTo(otherObject) == 0;
	public String toString() 
		String string = (getId() + "  " + getInv());
		return string;

From my experience so far, Arrays with stored objects only need to method call after referencing it.

int id = myArray[index].getId()

What I tried was:

int id = myList.get(index).getId();

I knew that this aproach probably wouldn't work anyway. So right now I need someone to help me to understand how to call a method from an object within a LinkedList.

Thanks in advanced,

Lord Felix

You need to explicitly cast the object you retrieve from the List to the correct type unless you use a 1.5 level compiler in which case you can use generics to declare the List to only accept a specific type (and thus do the cast for you on retrieval).

You'd then declare the List as:

List<Item> myList = new LinkedList<Item>();

Hey there,

int id = myList.get(index).getId(); // yeah this line could work

The only problem is your storing objects, the list doesn't know at run time what kind of object is stored there i think. You would have cast it like jwenting said.

Item t = (Item)myList.get(index);
int id = t.getId();

This would work i think.

good luck,

This article has been dead for over six months. Start a new discussion instead.