Java 在ArrayList中存储字符串数组的正确方法是什么?

Java 在ArrayList中存储字符串数组的正确方法是什么?,java,arraylist,resultset,Java,Arraylist,Resultset,我有一个函数,它从数据库中选择数据,然后尝试将其存储在ArrayList中。 我想先将ResultSet中的每一列存储在字符串数组中,然后将数组添加到ArrayList中 public void buildConnection() throws SQLException,ClassNotFoundException { Class.forName("com.mysql.jdbc.Driver"); Connection connection=DriverManager.g

我有一个函数,它从数据库中选择数据,然后尝试将其存储在ArrayList中。 我想先将ResultSet中的每一列存储在字符串数组中,然后将数组添加到ArrayList中

    public void buildConnection() throws SQLException,ClassNotFoundException
{
    Class.forName("com.mysql.jdbc.Driver");
    Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
    Statement statement =connection.createStatement();
    ResultSet rSet=statement.executeQuery("select * from details");
    ResultSetMetaData rSetMd=rSet.getMetaData();
    int ColumnsNo=rSetMd.getColumnCount();
    ArrayList<String[]> arrMatrix=new ArrayList<String[]>();
    int j=0;
    while(rSet.next()){
        String arrRows[] = new String[ColumnsNo];
        for(int i=1;i<=ColumnsNo;i++){
            arrRows[i-1]=rSet.getString(i);
        }
        arrMatrix.add(j,arrRows);
        j++;
    }
    System.out.println(arrMatrix.get(0)[0]+" "+arrMatrix.get(0)[1]+" "+arrMatrix.get(0)[2]);
    System.out.println(arrMatrix.get(1)[0]+" "+arrMatrix.get(1)[1]+" "+arrMatrix.get(1)[2]);

}
在我的数据库中,此条目是我将使用的最后一个条目

ArrayList
代替
ArrayList

使用这种方法,你就可以

ArrayList<ArrayList<String>> arrMatrix = new ArrayList<ArrayList<String>>();
arrMatrix.add(new ArrayList<String>());
arrMatrix.get(0).add("string value");
System.out.println(arrMatrix.get(0).get(0));
//string value
从那时起

Names instance = new Names("John", "Doe");
System.out.println(instance.firstname); // John
System.out.println(instance.surname); // Doe
创建名称的arraylist在这一点上很简单。显然,这个例子可以建立在更多的基础上


我怀疑你的潜在动机你一定是在用数组做其他事情,或者你只是在循环中打印它。

你试过调试循环中发生的事情吗?只需使用
arrMatrix.add(arrRows)
并去掉
j
。虽然我不认为这是错误的根源,但这是不必要的复杂性。arrMatrix.add(arrRows)做同样的事情。实际上这是我以前使用的。然后我得到了错误,所以我将其更改为上面的代码。但仍然是一样的。你能发布你得到的输出吗?数据库中有多少行?这两行打印的东西是一样的吗?哎呀,我把输出搞砸了,它实际上是一个两行的输出。不管我打印多少次,它总是一样的。不过这应该是一个注释。在这种情况下,我如何向内部ArrayList添加元素?
public class Names {
    public String firstname = null;
    public String surname = null;
    public Names(String first, String sur) {
        firstname = first;
        surname = sur;
    }
}
Names instance = new Names("John", "Doe");
System.out.println(instance.firstname); // John
System.out.println(instance.surname); // Doe