Reputation: 7394
I have the following object:
public class PersonDTO {
private Map<String, String> idsAndNames;
//default constructor
public PersonDTO() {
}
public PersonDTO(Map<String, String> idsAndNames) {
this.idsAndNames = idsAndNames;
}
public void setIdsAndNames(Map<String, String> idsAndNames) {
this.idsAndNames = idsAndNames;
}
public Map<String, String> getIdsAndNames() {
return idsAndNames;
}
public void addEntryToMap(String id, String name) {
this.idsAndNames.put(id, name);
}
}
Whenever I try to populate the map
within the object (see method below), I get a Null Pointer Exception
saying that the Map
is null
. How can I fix this?
Method to populate object (within main class):
public PersonDTO populatePersonDTO(List<String> ids, List<String> names){
Map<String, String> idsAndNames = new HashMap<>();
PersonDTO personDTO = new PersonDTO();
personDTO.setIdsAndNames(idsAndNames);
for(int i=0;i<ids.size();i++){
personDTO.addEntryToMap(ids.get(i),names.get(i)); //line throwing NPE
}
return personDTO;
}
Calling populatePersonDTO:
List<String> ids= Arrays.asList("1", "2", "3");
List<String> names= Arrays.asList("name1", "name2", "name3");
populatePersonDTO(ids, names);
Upvotes: 0
Views: 62
Reputation: 7273
If the NPE line points to populatePersonDTO
, then names
is the one being null (ids
can't be since we're calling ids.size()
w/o problem). If it was idsAndNames
the NPE would point to addEntryToMap
instead.
So make sure that names
is not null.
Upvotes: 1