Junior — Middle
What characteristics need to be implemented in a class for it to serve as a data table?
sobes.tech AI
Answer from AI
For a class to serve as a data table, it must have the following characteristics:
- Store data in a structured form, such as a list of objects or an array.
- Provide access to data by rows and columns (e.g., methods to get a value by row index and column name or index).
- Support operations for adding, deleting, and updating data.
- If necessary, implement interfaces that allow integration with UI components, such as TableModel in Swing.
Example of a simple class representing a data table:
import java.util.ArrayList;
import java.util.List;
public class DataTable {
private List<String[]> rows = new ArrayList<>();
private String[] columns;
public DataTable(String[] columns) {
this.columns = columns;
}
public void addRow(String[] row) {
if(row.length == columns.length) {
rows.add(row);
} else {
throw new IllegalArgumentException("Incorrect number of columns");
}
}
public String getValueAt(int rowIndex, int columnIndex) {
return rows.get(rowIndex)[columnIndex];
}
public int getRowCount() {
return rows.size();
}
public int getColumnCount() {
return columns.length;
}
public String getColumnName(int index) {
return columns[index];
}
}