【发布时间】:2012-01-18 09:37:07
【问题描述】:
我在从二维数组中删除空值时遇到了一些问题。我仍然是编程的初学者。我在网上寻找解决方案,但没有发现任何有用的东西。
这是和大学的练习,所以将数组的名称更改为“数组”,对于它的对象也是如此。这就是我所拥有的:
import java.util.ArrayList;
public class Compact
{
public static void Compact(object[][] array)
{
ArrayList<object> list = new ArrayList<object>();
for(int i=0; i<array.length; i++){
for(int j=0; j < array[i].length; j++){
if(array[i][j] != null){
list.add(array[i][j]);
}
}
}
array = list.toArray($not sure what to typ here$);
}
}
我基于我为一维数组找到的解决方案,但问题是列表是一维的,那么我如何获取二维数组的结构呢? “新”数组必须更小,没有空值。
我想为array[i] 和array[i][j] 分别创建一个列表,但是如何再次将它们合并为 1 个二维数组?
非常感谢所有帮助!
=========================================
编辑:这是解决方案,tnx 大家:
public void compact(Student[][] registrations)
{
for(int i=0; i < registrations.length; i++){
ArrayList<Student> list = new ArrayList<Student>(); // creates a list to store the elements != null
for(int j = 0; j < registrations[i].length; j++){
if(registrations[i][j] != null){
list.add(registrations[i][j]); // elements != null will be added to the list.
}
}
registrations[i] = list.toArray(new Student[list.size()]); // all elements from list to an array.
}
}
【问题讨论】: