在对象中填充HashMap时的NPE?

时间:2016-10-26 10:49:48

标签: java object nullpointerexception null hashmap

我有以下对象:

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);
    }

}

每当我尝试填充对象中的map时(请参阅下面的方法),我都会Null Pointer ExceptionMapnull。我该如何解决这个问题?

填充对象的方法(在主类中):

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;
    }

调用populatePersonDTO:

List<String> ids= Arrays.asList("1", "2", "3");
List<String> names= Arrays.asList("name1", "name2", "name3");

populatePersonDTO(ids, names);

1 个答案:

答案 0 :(得分:1)

如果NPE行指向populatePersonDTO,那么names是空的ids,因为我们正在调用ids.size()没有问题)。如果是idsAndNames,则NPE会指向addEntryToMap

因此请确保names不为空。