简体   繁体   中英

String attribute of object always null in java

I have an arraylist of string arrays I pull from a csv file and I use that array to initialize the person object. All of the variables have values but the string email is always null. I checked and it is at the fifth index of every string array and it is not null in the initial "people" arraylist of string arrays.

public class person {

int year;
int sex;
int college;
int housing;
String email;
double resp_probability;

public person(ArrayList<String[]> people, int a) {
    int year = Integer.parseInt(people.get(a)[0]);
    int sex = Integer.parseInt(people.get(a)[1]);
    int college = Integer.parseInt(people.get(a)[2]);
    int housing = Integer.parseInt(people.get(a)[3]);
    String email = people.get(a)[5]; //where I set a value for email.
}

public String getEmail() {
    return email;
}
}

Because you defining a new local string variable in the constructor. Instead you should use this.email then assign the value.

this.email = people.get(a)[5];

Similarly for the all other class member variables. null is the default value for any reference class member variable and zero for numerical variables like int.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM