I’m having some trouble removing null values from a 2D array. I’m still a beginner with programming. I looked for solutions on the web, but I didn’t find anything useful.
This is and exercise at the university, so changed the name of the array just to “array”, same for its objects. This is what I have:
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$);
}
}
I based this on a solution I found for 1D arrays, but the problem is the list is 1D, so how do I get the structure back of the 2D array? The “new” array has to be smaller, without the null values.
I thought of making a list for array[i] and one for array[i][j], but then how do I merge them into 1 2D array again?
All help is much appreciated!
========================================
Edit: this is the solution, tnx everyone:
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.
}
}
The corresponding redimensionable structure to an
Object[][]is aList<List<Object>>.Also, note that classes in Java always start with an uppercase, by convention. It should thus be
Object, and notobject.A 2D array is not really a 2D array. It’s an array of arrays. There is thus one outer array, and several inner arrays. If you just want to remove nulls from the inner arrays, you can just use one temporary list to hold the elements of the current inner array during the iteration.
If the outer array contains null inner arrays, and you also want to remove these, then you shoud use a
List<Object[]>: