user2277729 user2277729 - 1 year ago 73
Java Question

How do I create multiple Java object instances from an array?

I'm trying to get this method to create two instances of the class 'Sport'. The method is passing in a array which has the information about the class which is then sent to the constructor to be created.

However, I'm unsure how to refer to instance 1 or 2 given my code.

public static void seperateValues(String sportDetail) {
String[] sportDetails = sportDetail.split(",");
System.out.println("Adding new sport to the Sport collection");
for(int i=0; i<sportDetails.length; i++) //just used for testing whether it was splitting correctly {
//name,usagefee,insurance,affiliationfees, then court numbers
int vlength;
vlength = sportDetail.length();
new Sport(sportDetails); //this static methods loops twice, giving tennis and baseball
System.out.println(name); //this lists tennis and baseball respectively

Answer Source

If you just want to refer to two instances of sport, you can simply do this:

Sport sport1 = new Sport(sportDetails);
Sport sport2 = new Sport(sportDetails);

And then simply call sport1 or sport2 when you want to access them, however if you want to use that method n number of times for n number of sports, you can do this: First change the separateValues() method to return a sport, by changing these lines:

public static void seperateValues(String sportDetail) {


public static Sport seperateValues(String sportDetail) {

At the end of the method, make it return a sport, like this:

Sport sport = new Sport(sportDetails);
return sport;

And then you can call the method inside a loop and create a list, so you can create as many sports are you need:

//First declare a list of sports:
List<Sport> sports = null;

for (int i = 0; i<asManySportsAsYouWantToAdd; i++){

And then, to access each individual sport, you can simple use:

sports.get(n); //Where n is place of the sport on the list
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download