Reputation: 1364
I'm new to programming and I'm looking for a simple answer to build my foundation of understanding Arrays. I've used google and searched this site.
After a bit of trial and error I get how to make and reference Arrays like thing[3] gets you the fourth thing in the thing array(since 0 is the first). which lets me do something like thing[3].getStupidNumber() to get the StupidNumber of the 4th thing in the thing array.
Then I get to ArrayLists which seem to have much more utility but I cant make logical sense of them like Arrays. When i search I cant find this or word this correctly and thus far everything else I've learned clicked easily.
so say I make an ArrayList thing with 5 things in it. how do i get to the .getStupidNumber() method inside the fourth thing, if possible? I think if I learn this I can learn the rest on my own.
Upvotes: 2
Views: 1440
Reputation: 458
Lets say you have a class called StupidThing
class StupidThing {
int getStupidNumber(){return 1;}
}
List list = new ArrayList();
// This list represents a list of Object. It can hold only object.
StupidThing stupidThing = new StupidThing();
and you want to have an array of StupidThings. We can add stupidThing to the array.
list.add(stupidThing);
Be aware that list represents an array of Objects. Therefore, list.get(0) will return the first stupidThing as an Object. In order to call StupidThing's method, you need to downcast the returned object to StupidThing;
int stupidNumber = ( (StupidThing) (list.get(0)) ).getStupidNumber();
If you don't like "downcast", you can use a list of StupidThing instead.
List<StupidThing> list = new ArrayList<StupidThing>();
// Now list can only hold instances of StupidThing
StupidThing stupidThing = new StupidThing();
list.add(stupidThing);
int stupidNumber = list.get(0).getStupidNumber();
Upvotes: 3
Reputation: 45586
ArrayList
( and List
in general ) has a positional get
method, which acts essentially the same as []
array operator.
ArrayList<StupidThing> list = ...;
list.get(3).getStupidNumber( );
Upvotes: 0