大家好,我是 Java 新手,为什么它会抛出空指针异常? 我的客户等级
package com.syncfusion;
import java.util.List;
public class Customers {
private List<String> customerNamesList;
public void addCustomerName(String customerName) {
customerNamesList.add(customerName);
System.out.println(customerName);
}
public void printAllCustomers() {
for(String customer : customerNamesList) {
System.out.println(customer);
}
}
}
我的主要功能如下所示:
package com.syncfusion;
public class Persons {
public static void main(String[] args) {
Customers customer = new Customers();
customer.addCustomerName("Inteflex Inc");
}
}
为什么会抛出空指针?我希望我已经实例化了客户类,但它有错误
最佳答案
将列表初始化更改为以下:
private List<String> customerNamesList = new LinkedList<String>();
为什么你的代码有 NullPointerException ?因为您直接使用 List,它是接口(interface)(抽象类型),所以您需要使用其实现进行初始化(ArrayList、LinkedList 根据您的列表操作要求)
关于Java 类抛出 java.lang.NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61153421/