Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

creating different object in a for loop

Status
Not open for further replies.

davikokar

Technical User
May 13, 2004
523
IT
Hallo, I'm very new to Java and OOP, so maybe my problem is a stupid one. Her it is:

I have a class "Person", with name and id. In the main programm I have an array of names done like this:

Code:
String[] Names  =
{
  "Pisellonio",
  "Gianfranco",
  "Euripide",
  "Sofocle",
  "Agamennone",
  "Tafano",
  "Asdrubale",
  "Ippolito",
  "Zaccaria",
  "Lucrezia"
};

Now I would like to loop my array and create for each name a new istance of the class Person, something like this:

Code:
for (int i=0;i<Names.length;i++)
{
  Person p1;
  p1 = new Person();
  p1.name = Names[i];
}

But this code of corse wouldn't work... because it would overwrite the p1 instance everytime. Do you know how to do it properly?

Thanks for suggestions.
 
What would you like to achieve? Your code is as far as I can see fully correct. Inside the loop you're creating a new local ("temporary") instance of p1. If you to have want to use a single instance only then you have to keep the creation of p1 outside the loop and use a setter method to fill p1.name:

example:

Person p1 = new Person();
for (int i=0;i<Names.length;i++)
{
p1.setName(Names);
}

where p1.setName in class Person is something like:

public void setName(String pName) {
name = pName,
}

 
Code:
		Person [] persons = new Person [names.length];

		for (int i=0; i < names.length; i++)
		{
			persons [i] = new Person (names [i]);
		}
Make 'Names' lowercase.
Make an array of persons.
Or a list, a map or some other useful collection.
Provide a constructor to initialize the person with a name, or use a setName (String n) - Methode.



don't visit my homepage:
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top