You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中ArrayList指定索引添加元素报错及数据丢失问题求助

Fixing Your ArrayList Issues in Java

Let's break down and fix the three key problems you're hitting with ArrayList step by step:

1. Why old data keeps getting lost

The root cause here is that you’re creating a brand new empty ArrayList every time you select option 2a. This code block:

List<Department> departmentList;
departmentList = new ArrayList<>();

runs inside the if ("2a".equals(option)) check, so every time you add a department, you start fresh—all previous entries get discarded immediately.

Fix: Initialize the list once, outside the loop

Move the list initialization to the top of your main method so it persists across all loop iterations:

public static void main(String[] args) {
    printOptions() ;
    Scanner in = new Scanner(System.in) ;
    int d = 0 , c = 0 , p = 0 , s=0 ;
    College AinShams = new College() ;
    // Initialize the department list ONCE here (persists through loop runs)
    List<Department> departmentList = new ArrayList<>(); // ✅
    
    while (true){
        String option = in.nextLine() ;
        if(!"6".equals(option)) {
            if ("2a".equals(option)) {
                // Your existing code to collect department details
                System.out.println("Department Name:");
                String depName = in.nextLine() ;
                System.out.println("Department Description:");
                String depDescripe = in.nextLine() ;
                System.out.println("Department Max Students:");
                int max_num = in.nextInt() ;
                in.nextLine() ;
                
                Department newDept = new Department(depName, depDescripe, max_num);
                // Use the persistent list instead of creating a new one
                departmentList.add(d, newDept);
                d++ ;
                AinShams.setDepart(departmentList);
            }
        } else {
            // Don't forget to exit the loop when user selects "6"
            break;
        }
    }
}

2. Why add(index, thing) throws an error on the second addition

Before fixing the list initialization, the second time you tried adding, you were working with a brand new empty list. The index d had incremented to 1, but the list’s size was 0—you can’t add an element at index 1 to an empty list (valid indices only go up to size-1). With the persistent list, d will match the list’s current size, so add(d, ...) works as intended (it’s equivalent to appending to the end).

3. Why elements always went to index [0] when omitting the index

This was another side effect of creating a new empty list every time. add(thing) adds to the end of the list, but if the list is empty, that’s index 0. Since you never kept the old list, it always looked like elements were only added to position 0. With the persistent list, each new department will append to the end of the existing list.

Bonus: Simplify your code (optional)

You don’t even need the d variable! The add(thing) method automatically appends to the end of the list, so you can replace:

departmentList.add(d, newDept);
d++ ;

with just:

departmentList.add(newDept);

This eliminates any index-related errors entirely and makes the code cleaner.

Final Tip

Make sure your College class’s setDepart method correctly handles updating the list (or consider adding an addDepartment method instead of replacing the entire list every time—this is more efficient and safer).

内容的提问来源于stack exchange,提问作者Abnaby

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 06:47:20