简体   繁体   中英

Retrieving multiple values from an arraylist

I have saved values retrieved from a database in java to an arraylist. I have used a class to save the data to the array list as shown below.

    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);;
        }
    }

However i now want to retrieve the values individually per row,from another class in the program.How can i do this?By individually i mean getting the address,message and linkid per row in the arraylist.

However i now want to retrieve the values individually per row,from another class in the program.How can i do this?

You just access each NewSms in the list. To access one by index, you could use:

NewSms sms = details.get(2); // Or whatever
// Now access the properties of sms

Or to access each of them in turn, use an enhanced for loop:

for (NewSms sms : details) {
    // Now access the properties of sms
}

Note that to comply with Java naming conventions, your NewSms class should have methods such as getAddress , setAddress - not set_address .

Also note that you need to close your result set / statement / connection - if you're using Java 7, you can use a try-with-resources statement; otherwise you should use finally blocks.

EDIT: If your problem is actually just returning the list, that's easy:

public List<NewSms> loadSmsDetails() {
    // Code as before...

    return details;
}

Then just call it from your other class:

// Where repository is a reference to an instance of the class containing the above method
List<NewSms> allDetails = repository.loadSmsDetails();
for(NewSms smsdetails:details){ 
String address = smsdetails.get_address();
String message = smsdetails.get_message();
String linkId = smsdetails.get_linkid();
}

However i now want to retrieve the values individually per row,from another class in the program

You need to pass the arraylist to the another class and iterate over it there to get the individual elements. The idea is to use a common araylist - to store the values from the resultset and in another class to iterate through them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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