This question already has answers here:
What is a NullPointerException, and how do I fix it?

(12个答案)


2个月前关闭。





嗨,大家好我是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");




    }
}


为什么会抛出空指针?我希望我已经实例化了Customer Class但它有错误

最佳答案

将列表初始化更改为以下内容:

 private List<String> customerNamesList = new LinkedList<String>();


为什么您的代码具有NullPointerException?由于您直接使用的是接口(抽象类型)的列表,因此需要使用其实现进行初始化(根据列表操作要求进行ArrayList,LinkedList)

09-04 13:29
查看更多