Results 1 to 3 of 3
  1. #1
    Chro is offline Member
    Join Date
    Oct 2010
    Posts
    2
    Rep Power
    0

    Default 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?
    Java Code:
    for(int i=1; i<4; i++){
      elepant(i).stampede();
    }
    So I want it to cycle through all my elephants and make them each 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...
    Java Code:
    String array["elephant1","elephant2","elephant3"];
    for(int i=1; i<4; i++){
      array[i].stampede();
    }
    I've tried out these and can't find a way to make them work.

    Thanks, Alex

  2. #2
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    3,874
    Rep Power
    8

    Default

    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.

  3. #3
    m00nchile is offline Senior Member
    Join Date
    Feb 2010
    Location
    Ljubljana, Slovenia
    Posts
    470
    Rep Power
    5

    Default

    You can define arrays to hold anything, including your objects. Just like this:
    Java Code:
    int[] array;
    designates an array that holds ints, this:
    Java Code:
    MyObject[] 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 o = new MyObject();
    o.doSomething();
    MyObject[] array = {o};
    array[0].doSomething(); //same effect
    Ever seen a dog chase its tail? Now that's an infinite loop.

Similar Threads

  1. Replies: 23
    Last Post: 09-07-2010, 08:12 PM
  2. Loop through Array in JSP
    By Robert_85 in forum JavaServer Pages (JSP) and JSTL
    Replies: 2
    Last Post: 04-25-2010, 09:00 PM
  3. Finding a the max value of the array using a for loop
    By soccer_kid_6 in forum New To Java
    Replies: 1
    Last Post: 04-11-2010, 11:25 PM
  4. Replies: 2
    Last Post: 05-05-2008, 01:56 PM
  5. Refer a good Java compiler
    By trill in forum New To Java
    Replies: 1
    Last Post: 08-07-2007, 07:31 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •