Results 1 to 2 of 2
  1. #1
    zoe
    zoe is offline Member
    Join Date
    Jul 2007
    Posts
    40
    Rep Power
    0

    Default Help with array of elements

    I'm fairly new to Java. I'm currently making a text RPG which I'm trying to port from C++. In the Java code, I have a class called Item that contains all my item variables and methods. Then, I have another class that is the Game class which is the game itself. Here is where all the items, players, etc.. get initialized. Right now I have something like:

    Item club = new Item("club", 1, "A club");

    Now, in C++ I used a estructure to get an array of item. This made it easy, for example, to tell where items are, since I could just do a for loop and cycle through the entire item list by using item[i].location.

    Is there any way to make an array of type Item (or any class in general) in Java?
    Thanks.

  2. #2
    shanePreater is offline Member
    Join Date
    Jul 2007
    Location
    England, Bath
    Posts
    47
    Rep Power
    0

    Default

    Is the array you are creating a fixed size? If so and if you know the size you can simply create an array of Item objects ala:
    Java Code:
    Item itemList = new Item[size];
    itemList[0] = new Item("club", 1, "A Club");
    ...
    However if you don't know the array size or if it is likely to change then your probably better off with an array:
    Java Code:
    List<Item> itemList = new ArrayList<Item>();
    itemList.add(new Item("club", 1, "A Club"));
    ...
    Then when you wish to retrieve an item at a given index use:
    Java Code:
    Item chosenItem = arrayList.get(index);
    The generics and collections stuff in java is very similar to the STL stuff in C++ so if you have used that then your laughing, if not, its not too hard to pick up.

    If you are using a JDK prior to 1.5 then drop the <> sections and cast the item returned from the get method to an Item.

    Hope that helps.

Similar Threads

  1. Elements package
    By BlitzA in forum New To Java
    Replies: 0
    Last Post: 12-27-2007, 11:58 PM
  2. reference to elements in array
    By Igor in forum New To Java
    Replies: 1
    Last Post: 12-14-2007, 11:56 AM
  3. Replies: 1
    Last Post: 12-14-2007, 07:25 AM
  4. deleting elements
    By nalinda in forum New To Java
    Replies: 2
    Last Post: 12-06-2007, 01:42 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
  •