deleting array elements

I am writing a program that contains a JTable which obtains its data from an array that consists of several elements of user input.I'm relatively new to Java and would like to know the best way to delete single rows of this table and at the same time out of the array.
[283 byte] By [jane_76a] at [2007-10-2 21:08:56]
# 1

You can never truly remove an element from an array. An array's size is fixed at creation time and cannot be changed.

You could mark an element as "deleted" by setting it to some value that cannot be a valid useful value in your context, such as null or -1.

You could shift all the following elements over to fill the hole, with System.arraycopy, and keep a separate value that tells you what the size of the in-use portion of the array is.

Or, if it doesn't have to be an array, then you could use a List, such as ArrayList (which is backed by an array and does the above mentioned shifting), or LinkedList, which is more efficient if you're going to insert or remove other than at the end.

http://java.sun.com/docs/books/tutorial/collections/

jverda at 2007-7-13 23:54:50 > top of Java-index,Java Essentials,New To Java...
# 2

Consult APIs, http://java.sun.com/j2se/1.5.0/docs/api/

Use the class javax.swing.table.DefaultTableModel, which is a utility, with a bit too many methods.

TableModel model = new DefaultTableModel(...);

table.setModel(model);

...

int row = 7;

DefaultTabelModel model = (DefaultTableModel)table;

mode.removeRow(row);

...

Object value = model.getValueAt(row, column);

In general I use AbstractTableModel as base class for my own TableModel, and implement my own data (database table or some other things).

joop_eggena at 2007-7-13 23:54:50 > top of Java-index,Java Essentials,New To Java...
# 3

Thanks for the tips so far. I created a menu item that lets me delete selected rows from the table. Now, how do I delete elements from the ArrayList? I am able to add elements to the list, however I don't know how to specify which element is selected for removal?

// set up Delete menu item

deleteItem = new JMenuItem("Delete Row");

deleteItem.setMnemonic('D');

editMenu.add(deleteItem);

deleteItem.addActionListener( // call to addActionListener

new ActionListener() { // anonymous inner class

// delete row when user clicks deleteItem

public void actionPerformed(ActionEvent event)

{

int row = displayTable.getSelectedRow();

tableModel.removeRow(row);

}

} // end anonymous inner class

); // end call to addActionListener

jane_76a at 2007-7-13 23:54:50 > top of Java-index,Java Essentials,New To Java...
# 4
I think I got it - I just added the following statement and it worked.Thanks anyway!variableOfArrayList.remove(row);
jane_76a at 2007-7-13 23:54:51 > top of Java-index,Java Essentials,New To Java...