[英]How do i convert an ArrayList into a multidimensional Array?
this line of code is throwing me the exception: Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 5, Size: 5 这行代码引发了异常:线程“ 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);
I am trying to convert a ArrayList into a multidimensional Array. 我正在尝试将ArrayList转换为多维数组。
Your employeeNames
list doesn't have index
amount of elements. 您的
employeeNames
列表没有index
数量的元素。 It most likely has 5, which means it will throw IndexOutOfBoundsException
when executing employeeNames.get(i)
for i = 5. 它很可能具有5,这意味着在为i = 5执行
employeeNames.get(i)
时,它将抛出IndexOutOfBoundsException
。
As jlordo has suggested, you should just create an Employee class. 正如jlordo所建议的那样,您应该只创建一个Employee类。
Here's an example: 这是一个例子:
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);
}
Now you have a list of Employee objects rather than a silly multi-dimensional array. 现在,您有了一个Employee对象列表,而不是一个愚蠢的多维数组。
( Notice we check the size of infoList
in the loop to avoid an IndexOutOfBoundsException
) ( 注意,我们在循环中检查
infoList
的大小,以避免IndexOutOfBoundsException
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.