Converting an ArrayList into a 2D Array
I presume you are using the JTable(Object[][], Object[])
constructor.
Instead of converting an ArrayList<Contact>
into an Object[][]
, try using the JTable(TableModel)
constructor. You can write a custom class that implements the TableModel
interface. Sun has already provided the AbstractTableModel
class for you to extend to make your life a little easier.
public class ContactTableModel extends AbstractTableModel {
private List<Contact> contacts;
public ContactTableModel(List<Contact> contacts) {
this.contacts = contacts;
}
public int getColumnCount() {
// return however many columns you want
}
public int getRowCount() {
return contacts.size();
}
public String getColumnName(int columnIndex) {
switch (columnIndex) {
case 0: return "Name";
case 1: return "Age";
case 2: return "Telephone";
// ...
}
}
public Object getValueAt(int rowIndex, int columnIndex) {
Contact contact = contacts.get(rowIndex);
switch (columnIndex) {
case 0: return contact.getName();
case 1: return contact.getAge();
case 2: return contact.getTelephone();
// ...
}
}
}
Later on...
List<Contact> contacts = ...;
TableModel tableModel = new ContactTableModel(contacts);
JTable table = new JTable(tableModel);
The simple way is to add a method to the Contact
like this:
public Object[] toObjectArray() {
return new Object[] { getName(), getAddress, /* ... */ };
}
and use it like this:
ArrayList<Contact> contacts = /* ... */
Object[][] table = new Object[contacts.size()][];
for (int i = 0; i < contacts.size(); i++) {
table[i] = contacts.get(i).toObjectArray();
}
Try this:
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(..);
list.add(..);
list.add(..);
list.add(..);
list.add(..);
list.add(..);
int[][] a = new int[list.size()][list.size()];
for(int i =0; i < list.size(); i++){
for(int j =0; j <list.size(); j++){
a[i][j]= list.get(j +( list.size() * i));
}
}