繁体   English   中英

将String数组存储在ArrayList中的正确方法是什么?

[英]What is the proper way to store a String array in an ArrayList?

我有一个函数,它从数据库中选择数据,然后尝试将其存储在ArrayList中。 我想先将每个单独的列存储在String数组的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中。 所有其他条目都将丢失。 请告诉我我在做什么错。

UPDATE:输出:

 1 Axel Namek
 1 Axel Namek

在我的数据库中,该条目是最后一个条目

我会用;

ArrayList<ArrayList<String>>代替ArrayList<String[]>

使用这种方法,您便可以:

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

虽然,我怀疑这也不是你所追求的。 更好的方法是使用名字和姓氏字段创建一个新类,并引用这些

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

创建名称的数组列表很简单。 显然,这个例子可以建立在更多的基础上。

我质疑您的潜在动机,您必须对数组进行其他操作,否则您将在循环中打印它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM