Josh Howson
Josh Howson

Reputation: 11

Removing an element in a 2D array by collapsing all elements

I am making a program that keeps track of employee information. I have a 2D array containing the records ([employee][piece_of_data]), and I want to be able to delete a record by looping through the array and making the current record equal to the following one.

Right now it is deleting the record AHEAD of the one selected rather than the current and it seems that no matter how I manipulate it, it won't delete the proper record.

Here is my code:

//Delete current record, collapse records into it
    for (int iLoop = iEmployee; iLoop < iEmployeeCount; iLoop++){
        for (int iLoop2 = 0; iLoop2 <= 20; iLoop2++){
            sData[iLoop][iLoop2] = sData[iLoop + 1][iLoop2];
        }
    }

Upvotes: 1

Views: 401

Answers (2)

Ian
Ian

Reputation: 354

Because you are unable to convert the matrix to Objects and are unable to use an ArrayList for the entire thing here is a way to do it:

ArrayList<String[]> a=new ArrayList(Arrays.asList(sData));
a.remove(iEmployee);

This will convert the matrix to an ArrayList of String arrays.

Object[] oa = a.toArray();
for(int i = 0; i<oa.length; i++){
    sData[i] = (String[])oa[i];
}

This will then convert the ArrayList back into sData matrix.

Edit: This will not work if you except to have a set matrix size somewhere else. This will resize the matrix after you remove the data.

Upvotes: 0

nhouser9
nhouser9

Reputation: 6780

I suggest that instead of working with this weird double array you solve this problem in the correct way. The current code is messy and not maintainable. Worse, it seems like it probably duplicates records because after you left shift all the columns in your 2D array the last column will contain a duplicate of the second last column.

Java is an Object Oriented language. Use objects.

//declare a class to store the info about one employee
//this will replace one column in your double array
public class Employee {
 //each one of these fields corresponds to one cell in your double array
 public string data1; 
 public string data2;
 public string data3;
}

And then store them in a linked list:

//this is just an example of how you would add employees to a list instead of an array
LinkedList<Employee> employees = new LinkedList<>(); //make a linked list
Employee toAdd = new Employee();                     //make an employee
toAdd.data1 = "example";                             //set up his data
toAdd.data2 = "setting";
toAdd.data3 = "fields";
employees.add(toAdd);                                //add him to the list

Then to remove an employee, instead of doing this complicated and inefficent method with arrays, just get a link to the employee you want and call

employees.remove(iEmployee);

where iEmployee is the number in the list of the employee to remove.

Upvotes: 2

Related Questions