1

As the tittle says i want to save each new created object of Person's name in a list:

This is my code so far

package javaapplication4;
import java.util.*;

public class Person {
private String namePerson;  
static List personList = new ArrayList();

{ 
    personList.add(getPersonName());
} 

public Person(String namePerson){
       this.namePerson = namePerson;
}

public void setPersonName(String namePerson){
    this.namePerson = namePerson;
}

 public String getPersonName(){
    return namePerson;
}

public void setPersonList(List personList){
      this.personList= personList;
}

  public static List getPersonList(){
      return personList;
  }

each time i am creating a person object its gets added as a 'null' spot in the list (when i use println).

how i change that to the name of the new object Person like

Person Guy = new Person("NameOfGuy"); then list must be [NameOfGuy].
NoobEditor
  • 15,563
  • 19
  • 81
  • 112
Agaeus
  • 43
  • 5

3 Answers3

3
{ 
   personList.add(getPersonName());
} 

The above is called an instance initializer. It is executed before the constructor is executed. At that time, getPersonName will return null as you haven't yet set the value of namePerson.

Move that inside the constructor

public Person(String namePerson){
   this.namePerson = namePerson;
   this.personList.add(namePerson);
}

Sidenote: It is a bad practice to use raw types. You are using a raw List. It must be as

List<String> personList = new ArrayList<>();

What is a raw type and why shouldn't we use it?

Thiyagu
  • 17,362
  • 5
  • 42
  • 79
1

As pointed out by @user7, you are adding the name into the list at the wrong place. What you should be doing is, adding person's name into list while you are creating person's object, i.e. inside your constructor. Replace your constructor with this :

public Person(String namePerson){
  this.namePerson = namePerson;
  personList.add(namePerson);
}
Rajat Sharma
  • 121
  • 7
0

You can do the job Doing below changes to the Person class:

import java.util.*;

public class Person {
private String namePerson;
static List<String> personList = new ArrayList<>();

public Person(String namePerson) {
    this.namePerson = namePerson;
    personList.add(this.namePerson);
}

public void setPersonName(String namePerson) {
    this.namePerson = namePerson;
}

public String getPersonName() {
    return namePerson;
}

public void setPersonList(List personList) {
    this.personList = personList;
}

public static List getPersonList() {
    return personList;
}
}
Anuradha
  • 570
  • 6
  • 20