簡體   English   中英

如何將ArrayList轉換為多維數組?

[英]How do i convert an ArrayList into a multidimensional Array?

這行代碼引發了異常:線程“ main”中的異常java.lang.IndexOutOfBoundsException:索引:5,大小:5

String [][] employeeNamesA = new String [2][index];
for (int i = 0; i<index; i++)employeeNamesA[0][i] = employeeNames.get(i);

我正在嘗試將ArrayList轉換為多維數組。

您的employeeNames列表沒有index數量的元素。 它很可能具有5,這意味着在為i = 5執行employeeNames.get(i)時,它將拋出IndexOutOfBoundsException

正如jlordo所建議的那樣,您應該只創建一個Employee類。

這是一個例子:

class Employee {

    String name;
    String info;

    public Employee(String n, String i) {
        name = n;
        info = i;
    }

    public String getName() {
        return name;
    }

    public void setName(String s) {
        name = s;
    }

    public String getInfo() {
        return info;
    }

    public void setInfo(String s) {
        info = s;
    }
}


List<String> nameList = // populate nameList
List<String> infoList = // populate infoList

List<Employee> employeeList = new ArrayList<Employee>();

for (int i = 0; i < nameList.size(); i++) {
    String name = nameList.get(i);
    String info = null;
    if (infoList.size() > i) {
        info = infoList.get(i);
    }
    Employee emp = new Employee(name, info);
    employeeList.add(emp);
}

現在,您有了一個Employee對象列表,而不是一個愚蠢的多維數組。

注意,我們在循環中檢查infoList的大小,以避免IndexOutOfBoundsException

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM