首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 自定義對象數組創建與初始化完全指南

     編輯:Java 相關知識

核心概念:引用類型數組

Student[] stu = new Student[3]; 僅在堆中分配 **3 個引用槽位** (初始值均為 null),**不會自動創建 Student 對象**。必須顯式 new Student() 為每個槽位賦值,否則調用方法觸發 NullPointerException。

標準創建姿勢


// 1. 聲明並分配引用空間
Student[] students = new Student[3];

// 2. 逐個實例化對象並賦值
for (int i = 0; i < students.length; i++) {
    students[i] = new Student();          // 關鍵步驟!
    students[i].setId(i + 1);
    students[i].setName("學生" + (i + 1));
    students[i].setScore(60 + i * 10);
}

// 3. 靜態初始化 (已知數據)
Student[] classA = {
    new Student(1, "張三", 90),
    new Student(2, "李四", 85),
    new Student(3, "王五", 95)
};

完整示例:文件讀寫學生成績


public class StudentManager {
    private static final File DATA_FILE = new File("data/students.txt");

    public void saveStudents(Student[] students) throws IOException {
        try (BufferedWriter bw = new BufferedWriter(new FileWriter(DATA_FILE))) {
            for (Student s : students) {
                bw.write(s.getId() + " " + s.getName() + " " + s.getScore());
                bw.newLine();
            }
        }
    }

    public Student[] loadStudents(int count) throws IOException {
        Student[] students = new Student[count];
        try (BufferedReader br = new BufferedReader(new FileReader(DATA_FILE))) {
            String line;
            int i = 0;
            while ((line = br.readLine()) != null && i < count) {
                String[] parts = line.trim().split("\\s+");
                students[i] = new Student();                 // 必須 new 對象!
                students[i].setId(Integer.parseInt(parts[0]));
                students[i].setName(parts[1]);
                students[i].setScore(Integer.parseInt(parts[2]));
                i++;
            }
        }
        return students;
    }

    public double averageScore(Student[] students) {
        return Arrays.stream(students).mapToInt(Student::getScore).average().orElse(0);
    }
}

進階:動態擴容 → ArrayList

數組長度固定,頻繁增刪請用 List list = new ArrayList<>();:

  • list.add(new Student(...)) 自動擴容。
  • list.removeIf(s -> s.getScore() < 60) 刪除不及格。
  • Student[] arr = list.toArray(new Student[0]) 需轉數組時轉換。

常見錯誤與避坑

錯誤代碼現象修正
Student[] s = new Student[3]; s[0].setName("A");NPE先 s[0] = new Student();
Student[] s = new Student[3]; Arrays.fill(s, new Student());所有元素指向同一對象循環 new Student()
Student[] s = {}; s[0] = new Student();ArrayIndexOutOfBoundsException指定長度或用 ArrayList

總結

「new 數組 只分配引用,必須循環 new 對象」是 Java 引用類型數組的鐵律。掌握「聲明 → 分配 → 實例化 → 賦值」四步驟,配合 ArrayList 靈活應對動態場景,徹底告別 NPE 與共享引用陷阱。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved