首页 > 解决方案 > 数组列表中的空指针异常 - 对象如何工作?

问题描述

我有空指针异常。你能帮帮我吗?我遇到了数组列表中的对象问题。我不知道问题出在哪里。

这是我的错误:

Picked up _JAVA_OPTIONS: -Djava.net.preferIPv4Stack=true
Exception in thread "main" java.lang.NullPointerException
    at javaapplication3.JavaApplication3.main(JavaApplication3.java:26)
C:\Users\User\AppData\Local\NetBeans\Cache\12.3\executor-snippets\run.xml:111: The following error occurred while executing this line:
C:\Users\User\AppData\Local\NetBeans\Cache\12.3\executor-snippets\run.xml:68: Java returned: 1
BUILD FAILED (total time: 0 seconds)

标签: javaswingarraylistnullpointerexception

解决方案


只需将其从 S 转换为 name

 public void setName(String name){
    
        this.name=name;
    
    }

并更改为此代码

ArrayList<user> object=new ArrayList<user>();
 user[] obj=new user[3]; 
obj[0]=new user(); 
obj[2]=new user(); 
obj[0].setName("S"); 
obj[0].setNumber(5);
 obj[1]=new user(); 
obj[1].setName("7");
 obj[1].setNumber(6); 
object.add(obj[0]); 
object.add(obj[1]);
 System.out.println(object.get(0).getName()); System.out.println(object.get(1).getName()); 

推荐阅读