• Post Reply Bookmark Topic Watch Topic
  • New Topic

Java: Arrays of class objects?

 
Matt Herrington
Greenhorn
Posts: 16
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm fairly new to Java and coming from a C++ and Qbasic background.

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 struct 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? Thank you for any help.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24213
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Welcome to JavaRanch!

First, a bit of business: you may not have read our naming policy on the way in. It requires that you use a full, real (sounding) first and last name for your display name. Joke names and "handles" aren't acceptable at the Ranch. You can change your display name
here.
Thanks!

As to your question: yes, you can. I just answered this yesterday!
 
Ray Horn
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, you can specify an array which holds an Item type:

Item [] myitems; //this creates a reference to an array which holds type Item.

myitems = new Item[50]; //this creates the array which can hold 50 Item ojbects. Note that only the array has been created; no Item objects.

myitems[0] = Item("club", 1, "A club");//This creates the 1 Item instance and puts it into the array.

You may find using the "Java in General (Beginner)" forum would get quicker responses to you initial Java questions as you learn Java.
[ October 31, 2005: Message edited by: Ray Horn ]
 
Unnar Björnsson
Ranch Hand
Posts: 164
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ArrayList is also a useful tool. It is an resizeable array. Extremly useful.
 
Daniel Prene
Ranch Hand
Posts: 241
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You might also want to create a club class that extends Item. It'd definitely be more Javay
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!