Always returning the last item in the ArrayList

  • Thread starter Thread starter Adam
  • Start date Start date
A

Adam

Hi all,

I have an arraylist filled with 4 objects and defined as shown below.

ArrayList items = new ArrayList();

public Item GetItemAt(int index)
{
return (Item)items[index];
}

Problem is, no matter what value I provide for "index", it always returns
the LAST item in the ArrayList.
I feed it index 0, 1, 2, or 3 and it always returns Item at index 3.

I'm confused. Any tips would be greatly appreciated.

Thanks!
 
Adam said:
I have an arraylist filled with 4 objects and defined as shown below.

ArrayList items = new ArrayList();

public Item GetItemAt(int index)
{
return (Item)items[index];
}

Problem is, no matter what value I provide for "index", it always returns
the LAST item in the ArrayList.
I feed it index 0, 1, 2, or 3 and it always returns Item at index 3.

I'm confused. Any tips would be greatly appreciated.

That suggests you've actually added 4 references, all to the same
object. Could you post the code you're using to populate the list?
 
Works fine for me...
Try to make your own array derived from ArrayList and override This[int
Index] method. Update us if it helps
 
That's exactly what I did wrong, I posted 4 references to the same object.

Thanks for the help!



Jon Skeet said:
Adam said:
I have an arraylist filled with 4 objects and defined as shown below.

ArrayList items = new ArrayList();

public Item GetItemAt(int index)
{
return (Item)items[index];
}

Problem is, no matter what value I provide for "index", it always returns
the LAST item in the ArrayList.
I feed it index 0, 1, 2, or 3 and it always returns Item at index 3.

I'm confused. Any tips would be greatly appreciated.

That suggests you've actually added 4 references, all to the same
object. Could you post the code you're using to populate the list?
 
Back
Top