Results 1 to 3 of 3
- 11-09-2010, 05:57 PM #1
Member
- Join Date
- Oct 2010
- Posts
- 2
- Rep Power
- 0
Refer to an object from an array/for loop
E.g. I have an objects called elephant1, elephant2 and elephant3 from a separate class. Here are three kinds of things I would like to do.
1. Is there a way to do something like the following?
So I want it to cycle through all my elephants and make them each stampede.Java Code:for(int i=1; i<4; i++){ elepant(i).stampede(); }
2. What about something like the following, where there is an array with values in it.
Java Code:String array["elephant1","elephant2","elephant3"]; array[2].stampede();
3. Or combining those two things...
I've tried out these and can't find a way to make them work.Java Code:String array["elephant1","elephant2","elephant3"]; for(int i=1; i<4; i++){ array[i].stampede(); }
Thanks, Alex
- 11-09-2010, 06:03 PM #2
To access them by index, put them in a List or array.
To access them by String (or some other key), put them in a Map.Last edited by KevinWorkman; 11-09-2010 at 06:08 PM.
- 11-09-2010, 06:12 PM #3
Senior Member
- Join Date
- Feb 2010
- Location
- Ljubljana, Slovenia
- Posts
- 470
- Rep Power
- 4
You can define arrays to hold anything, including your objects. Just like this:
designates an array that holds ints, this:Java Code:int[] array;
designates an array of MyObject type elements. You can use instance methods on them just as if they were a single variable:Java Code:MyObject[] array;
Java Code:MyObject o = new MyObject(); o.doSomething(); MyObject[] array = {o}; array[0].doSomething(); //same effectEver seen a dog chase its tail? Now that's an infinite loop.
Similar Threads
-
Variable of an object in an array compared to an element of another array?
By asmodean in forum New To JavaReplies: 23Last Post: 09-07-2010, 08:12 PM -
Loop through Array in JSP
By Robert_85 in forum JavaServer Pages (JSP) and JSTLReplies: 2Last Post: 04-25-2010, 09:00 PM -
Finding a the max value of the array using a for loop
By soccer_kid_6 in forum New To JavaReplies: 1Last Post: 04-11-2010, 11:25 PM -
Need another program with and if-else, array, and for loop
By Zebra in forum New To JavaReplies: 2Last Post: 05-05-2008, 01:56 PM -
Refer a good Java compiler
By trill in forum New To JavaReplies: 1Last Post: 08-07-2007, 07:31 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks