Reputation: 9
I'm trying to create a Person-object inside of a method called on, and then i want to add that person to a list of participants.
public void addPerson(String name, int age){
//Adding person in a list of participants, capping it at 99 participants
int i = 0;
if (i<100) {
Person participant = new Person(name, age);
participants.add(participant.getName());
this.newest= deltager;
i++;
}
}
If i want to call on a specific participant after having filled up the list, how would i name the object so that they won't all be called "participant"? Wouldn't the object be overridden every time i add a new person, because the name of it would be the same?
Upvotes: 0
Views: 908
Reputation: 338720
The Answer by stht55 is correct and important. Objects do not have a name while reference variables do.
Also note that your code is instantiating a Person
object and then immediately discarding it after extracting the name. So there is no point to calling new Person
in that code.
One solution is to loop the collection, interrogating each contained object for its member field name
to see if it is a match.
List< Person > persons =
List.of(
new Person( "Alice" , 42 ) ,
new Person( "Bob" , 28 )
)
;
for( Person p : persons ) {
if( p.getName().equals( "Bob" ) { … we have a match … }
}
Map
Perhaps the data structure you want is a Map
, a pairing of a key object that leans to value object.
Map < String , Person > map = new HashMap<>() ;
To use it, pass the name as key, and pass a new Person
object as value.
map.put( name , new Person( name , age ) ) ;
Retrieval.
Person p = map.get( "Bob" ) ;
Beware of multiple objects coincidentally sharing the same key. In your case, several people might share the name “Bob”, but the map can store only one value per key. One way around this is to use a multimap, where the value paired with the key is a collection of value objects rather than a single. This has been covered many times already on Stack Overflow, so search to learn more.
Upvotes: 1
Reputation: 410
Person participant = new Person(name, age);
inside the function creates a local object.
This object is initialized with the arguments
from your function namely String name, int age
.
However, your condition if (i<100) {...}
will always be true.
You initialize the local variable int i = 0;
and then
execute the code in the if-case which will always be the case.
If you where to write a for-loop like this:
for (int i = 0; i < 100; i++){
... }
You would create the same participant (same name and age given in the arguments in the function) 100 times.
Upvotes: 3