将ArrayList传递给单独的类?

Vin*_*iel 9 java arraylist

我有一个代码从SQL数据库中读取并将每列信息保存到一个ArrayList.我需要将每个ArrayList列表传递到一个单独的类中,我可以将列表存储为单个信息(IE:第一部分中的ArrayList1信息与第一部分中的信息相关ArrayList2...)然后对它们进行排序.我不知道如何将这些信息传递给另一个班级.这是我的主要方法的一部分,它将信息存储到列表中.我需要将这些信息传递给一个名为的单独的类List.java:

String SelectStatement1 = "SELECT InvoiceID FROM Invoice;";
    ps = conn.prepareStatement(SelectStatement1);
    rs = ps.executeQuery();
    int count = 0;
    while (rs.next()){
        count++;
    }
    ps.close();
    ps = conn.prepareStatement(SelectStatement1);
    rs = ps.executeQuery();
    ArrayList<String> InvoiceIDList = new ArrayList<String>();
    String InvoiceID = null;
    int p = 0;
    while (p < count){
        rs.next();
        InvoiceID = rs.getString("InvoiceID");
        InvoiceIDList.add(InvoiceID);
        p++;
    }
    ps.close();
    p = 0;
Run Code Online (Sandbox Code Playgroud)

编辑:这只是我代码的一部分,我已经打开并关闭了连接的代码,我只需要有关如何将ArrayList传递给另一个类进行排序的信息.

Eva*_*tol 8

在您的其他类中创建一个方法,如下所示:

public void receiveList (ArrayList<String> invoiceIDList) {
    // Do something with invoiceIDList data
}
Run Code Online (Sandbox Code Playgroud)

在"List"类中创建构造函数可能不是一个坏主意,它接受ArrayList并使用所需数据创建类实例

另外,更改该课程的名称!! 阅读代码的其他人会感到困惑,因为你已经传递了一个ArrayList!

编辑:

您也可以让您的类实现 List接口,这将使您更容易,因为您可以根据ArrayList中数据的位置将数据插入到类中.

public class yourClass implements List<String> {
     // Your class methods and variables...
}
Run Code Online (Sandbox Code Playgroud)

如果你想扩展它以允许不仅仅是字符串,你可以改为:List<T>,这将为你提供更通用的方法.


Ell*_*sch 5

首先,我建议您SELECT COUNT()在第一个查询中执行而不是迭代行.然后记得close()这两个PreparedStatementResultSet.最后,我建议你编程到List<String>界面.把它们放在一起像,

Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
Run Code Online (Sandbox Code Playgroud)

连接到您的数据库并初始化conn.

int count = 0;
try {
    String query1 = "SELECT COUNT(InvoiceID) FROM Invoice;";
    ps = conn.prepareStatement(query1);
    rs = ps.executeQuery();
    if (rs.next()) {
        count = rs.getInt(1);
    }
} catch (SQLException e) {
    e.printStackTrace();
} finally {
    try {
        rs.close();
    } catch (Exception ignored) {
    }
    try {
        ps.close();
    } catch (Exception ignored) {
    }
}
Run Code Online (Sandbox Code Playgroud)

上面的代码块是必要的close()两个rsps以正确的顺序与所述finally.

List<String> invoiceIdList = new ArrayList<>();
try {
    String query2 = "SELECT InvoiceID FROM Invoice;";
    ps = conn.prepareStatement(query2);
    rs = ps.executeQuery();
    while (rs.next()) {
        invoiceIdList.add(rs.getString("InvoiceID"));
    }
} catch (SQLException e) {
    e.printStackTrace();
} finally { // <-- it's identical to the finally block above.
    try {
        rs.close();
    } catch (Exception ignored) {
    }
    try {
        ps.close();
    } catch (Exception ignored) {
    }
}
// now you can pass invoiceIdList elsewhere...
if (!invoiceIdList.isEmpty()) {
    doSomething(invoiceIdList);
}
Run Code Online (Sandbox Code Playgroud)