java - 数组列表中的空指针异常 - 对象如何工作?
问题描述
我有空指针异常。你能帮帮我吗?我遇到了数组列表中的对象问题。我不知道问题出在哪里。
主班
公共类 JavaApplication3 {
public static void main(String[] args) { ArrayList<user> object=new ArrayList<user>(); user[] obj=new user[3]; obj[0].setName("S"); obj[0].setNumber(5); 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()); }
}
这是我的用户类:
公共类用户{
private int no; private String name; public int getNo() { return this.no; } public void setNumber(int no) { this.no = no; } public String getName(){ return this.name; } public void setName(String S){ this.name=name; }
}
这是我的错误:
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)
解决方案
只需将其从 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());
推荐阅读
- sql-server - 如何创建一个始终返回传递给其 WHERE 子句的值的表(或其他对象),如镜像
- python - 在单个模型的多个模型中使用外键时出现 django 错误
- php - PHP Array 如何使所有数组具有相同的长度
- angular - 如何以角度打印HttpRequest标头
- amazon-cloudformation - 无服务器框架 - 获取 API 网关 URL 以用于测试
- qt - 组合框qml的动态翻译
- pandas - 如何计算特定列的滚动平均值并需要打印滚动平均值以及日期
- android - 如何在 Android P (API 28) 中在外部 SD 卡上打开数据库
- angular - 使用服务的可重用组件之间的通信
- angular - Angular Material Snackbar 未正确显示