我在尝试从一个二维数组中删除空值时遇到了一些问题。我是编程的初学者。我在网上寻找解决方案,但没有找到有用的信息。
这是大学里的一个练习,所以我将数组的名称更改为“array”,对象也是如此。这就是我的代码:
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$);
}
}
我基于我在处理1D数组时找到的解决方案,但问题是列表是1D的,那么如何恢复2D数组的结构呢?“新”数组必须更小,没有空值。
我考虑为array [i]和array [i] [j]分别创建一个列表,但是如何将它们合并成1个2D数组?
非常感谢所有帮助!
========================================
编辑:这是解决方案,谢谢大家:
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.
}
}
for(int j = 0; j < innerArray.length; i++)
。因此你有一个无限循环,不断创建新的数组。 - JB Nizet