[英]Why can't I set an attribute to an object's array?
例如,我想為Gabriel
設置a[1]
名稱,它總是給我錯誤:
Exception in thread "main" java.lang.NullPointerException
at Register.main(Register.java:4)
我的代碼是:
public class Register {
public static void main(String[] args) {
Employee a[] = new Employee[2];
a[0].setName("Douglas");
}
}
當您創建一個非原始數組時,您會創建一個指定大小的null
數組。 在訪問對象的屬性之前,您需要創建它們(使用new
):
Employee a[] = new Employee[2];
a[0] = new Employee(); // Here!
a[0].setName("Douglas");
我們可以假設您的Employee
class 如下:
class Employee {
private String name;
public Employee(String s) {
name = s;
}
public void setName(String s) {
name = s;
}
public String getName() {
return name;
}
}
public class Main {
public static void main(String[] args) {
Employee a[] = null;
if (a == null)
System.out.println("Employee array is null !!!");
a = new Employee[10]; // You are init your aray
a[0] = new Employee("Test Name 1"); // it's init first item of array
a[1] = new Employee("Test Name 2"); // it's init second item of array
a[2] = new Employee("Test Name 3"); // it's init third item of array
for (Employee employee : a) {
if (employee == null) {
System.out.println("Employee is null !!!");
} else
System.out.println("Employee is not null : "
+ employee.getName());
}
}
}
正如您在代碼"Employee a[] = new Employee[2];"
中看到的只為員工數量分配空間。 但它是用null
設置的。 因為它保留了您的null
員工參考資料,所以您應該一一初始化它們。 由於這個原因"a[0].setName("Douglas");"
試圖到達 null 地址並拋出異常。
如果運行它,你可以看到這個 output:
Employee array is null !!!
Employee is not null : Test Name 1
Employee is not null : Test Name 2
Employee is not null : Test Name 3
Employee is null !!!
Employee is null !!!
Employee is null !!!
Employee is null !!!
Employee is null !!!
Employee is null !!!
Employee is null !!!
您可以通過lombok使用構建器模式,並且可以使用非空對象初始化列表。
import lombok.Builder;
import org.assertj.core.util.Arrays;
import java.util.List;
public static class Main {
@Builder
public class Employee {
private String name;
}
public static void main(String[] args) {
List<Main.Employee> employees = List.of(
Employee.builder().name("Douglas").build(),
Employee.builder().name("Maik").build(),
Employee.builder().name("Alex").build()
);
}
}
您應該向Employee
class 添加一個構造函數。 然后可以按如下方式創建數組:
public static void main(String... args) {
Employee[] arr = {
new Employee("Douglas"),
new Employee("Douglas2")};
System.out.println(Arrays.toString(arr));
// [Douglas, Douglas2]
}
public static class Employee {
String name;
public Employee(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.