1

I need to create a two dimensional table that I know its number of columns but I don't know the number of rows. The rows will be generated through the code and added to the table. My question is, which data structure in java do you think it would be the best for these features?

2 Answers 2

2

You should create a class with a field for each of your columns. For example, here is a Person class.

public final class Person {

    private final String firstName;
    private final String lastName;
    private final int age;

    public Person(String firstName, String lastName, int age){
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }

    public String firstName() {
        return firstName;
    }

    public String lastName() {
        return lastName;
    }

    public int age() {
        return age;
    }
}

Then you can create an ArrayList<Person>. The number of rows will be increased as needed.

For example

List<Person> table = new ArrayList<>();
table.add(new Person("John", "Smith", 52);
table.add(new Person("Sarah", "Collins", 26);
Sign up to request clarification or add additional context in comments.

Comments

2

There are several options:

  • Create a domain class and put its instances into ArrayList, as @pbabcdefp suggested
  • Put raw arrays into ArrayList:

    List<int[]> list = new ArrayList<>();
    list.add(new int[] {1, 2, 3});
    list.add(new int[] {4, 5, 6});
    
  • Use some special datastructure, like Table from Google Guava:

    Table<Integer, String, Object> table = HashBasedTable.create();
    // row 1
    table.put(1, "Name", "John");
    table.put(1, "Age", 22);
    // row 2
    table.put(2, "Name", "Mike");
    table.put(2, "Age", 33);
    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.