我已经将从 Java 数据库中检索到的值保存到数组列表中。 我已经使用一个类将数据保存到数组列表中,如下所示。
ArrayList<NewSms> details = new ArrayList<NewSms>();
try{
Statement query = conn.createStatement();
ResultSet result = query.executeQuery("Select `senderAddress,message,linkid from sdp_smsincoming where status=0 AND smsServiceActivationNumber =1234 ");`
while(result.next()){
String address = result.getString("senderAddress");
String message = result.getString("message");
String linkid = result.getString("linkid");
NewSms smsdetails = new NewSms();
smsdetails.set_address(address);
smsdetails.set_message(message);
smsdetails.set_linkid(linkid);
details.add(smsdetails);;
}
}
但是我现在想从程序中的另一个类中逐行单独检索值。我该怎么做呢?单独是指获取数组列表中每行的地址、消息和 linkid。
最佳答案
However i now want to retrieve the values individually per row,from another class in the program.How can i do this?
您只需访问列表中的每个 NewSms
。要按索引访问一个,您可以使用:
NewSms sms = details.get(2); // Or whatever
// Now access the properties of sms
或者依次访问它们中的每一个,使用增强的 for 循环:
for (NewSms sms : details) {
// Now access the properties of sms
}
请注意,为了遵守 Java 命名约定,您的 NewSms
类应该具有诸如 getAddress
、setAddress
之类的方法 - 而不是 set_address
。
另请注意,您需要关闭结果集/语句/连接 - 如果您使用的是 Java 7,则可以使用 try-with-resources 语句;否则你应该使用 finally
block 。
编辑:如果您的问题实际上只是返回列表,那很简单:
public List<NewSms> loadSmsDetails() {
// Code as before...
return details;
}
然后从你的其他类调用它:
// Where repository is a reference to an instance of the class containing the above method
List<NewSms> allDetails = repository.loadSmsDetails();
关于java - 从数组列表中检索多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18482898/