• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to build an array of objects of a class...  RSS feed

 
Rick O'Donnell
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I'm trying to build an array of object references in a class called "PersonTest" that reference a class called "Person". Class "Person" has a variable "String name" and an array "String[] friends". Once I've created this array of object references, however, I can't seem to get the friends array of that respective object. It only returns the most recently created object's friends array. I use an object reference in class "PersonTest" to call the getFriends method contained in class "Person" to get a respective persons friends by using "people[x].getFriends()[]" but it only accesses the last object created regardless of the index "x". Please find code below. It includes extensive print statements that I hope illustrates what I'm trying to do. Thank you in advance for your help.




This is the output:

BEGIN OUTPUT

asdf
qwer
bubba
Lucy

Jimmy
Bart
Fand
Fart

Burp
Base
Ball
Frog

Turt
Funny
Sock
Stiff

----
Turt
Funny
Sock
Stiff

----
Turt
Funny
Sock
Stiff

----
Turt
Funny
Sock
Stiff

----
Turt
Funny
Sock
Stiff

END OUTPUT

I would like the output to be:

BEGIN OUTPUT

asdf
qwer
bubba
Lucy

Jimmy
Bart
Fand
Fart

Burp
Base
Ball
Frog

Turt
Funny
Sock
Stiff

----
asdf
qwer
bubba
Lucy

----
Jimmy
Bart
Fand
Fart

----
Burp
Base
Ball
Frog

----
Turt
Funny
Sock
Stiff

END OUTPUT
 
Wayan Saryada
Ranch Hand
Posts: 119
Hibernate Java Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Everytime you created a new instance of Person you will give the same reference to array of friends into the Person object. So if this array of friends is changed it will change every Person's friends. If you want to make each Person have their own friends then you should instantiate the array of friends in your outer for loop instead of in the main() method. This will give you a new array of friends for each Person object.
 
Palak Mathur
Ranch Hand
Posts: 343
IntelliJ IDE Java Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Initialize the String array friends inside the outer for loop. Right now you are writing on the same reference.

Your code should look like this:-
[Moderator action: Removed full code solution. Palak Mathur, please DontBeACodeMill.(⇐click)]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!