我需要创建一个二维表,我知道它的列数但不知道行数。这些行将通过代码生成并添加到表中。 我的问题是,您认为 Java 中的哪种数据结构最适合这些功能?
最佳答案
您应该为每个列创建一个包含字段的类。例如,这里是一个 Person
类。
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;
}
}
然后你可以创建一个ArrayList<Person>
.行数将根据需要增加。
例如
List<Person> table = new ArrayList<>();
table.add(new Person("John", "Smith", 52);
table.add(new Person("Sarah", "Collins", 26);
关于java - 创建具有固定列数的动态数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29868938/