Results 1 to 2 of 2
Thread: Help with array of elements
- 07-24-2007, 02:59 PM #1
Member
- Join Date
- Jul 2007
- Posts
- 40
- Rep Power
- 0
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.
- 07-24-2007, 05:33 PM #2
Member
- Join Date
- Jul 2007
- Location
- England, Bath
- Posts
- 47
- Rep Power
- 0
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"); ...
Java Code:List<Item> itemList = new ArrayList<Item>(); itemList.add(new Item("club", 1, "A Club")); ...
Java Code:Item chosenItem = arrayList.get(index);
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
-
Elements package
By BlitzA in forum New To JavaReplies: 0Last Post: 12-27-2007, 11:58 PM -
reference to elements in array
By Igor in forum New To JavaReplies: 1Last Post: 12-14-2007, 11:56 AM -
problems with asigning elements of an array to a constructor
By rednessc in forum New To JavaReplies: 1Last Post: 12-14-2007, 07:25 AM -
deleting elements
By nalinda in forum New To JavaReplies: 2Last Post: 12-06-2007, 01:42 AM
Bookmarks