Converting an ArrayList into a 2D Array

前端 未结 8 2216
北海茫月
北海茫月 2020-12-04 01:55

In Java how do you convert a ArrayList into a two dimensional array Object[][]?

From comments: I will describe you the problem with more details: an XML file inclu

8条回答
  •  粉色の甜心
    2020-12-04 02:36

    I presume you are using the JTable(Object[][], Object[]) constructor.

    Instead of converting an ArrayList 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 contacts;
    
        public ContactTableModel(List 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 contacts = ...;
    TableModel tableModel = new ContactTableModel(contacts);
    JTable table = new JTable(tableModel);
    

提交回复
热议问题