简体   繁体   中英

Create array of string from an Arraylist

I want to get :

String[] phoneNos= {"07064267499","07064267499","07064267499"};

from :

ArrayList<Object> phoneNos = [0803406914, 08167337499, 0803377973] ;

This is my code snippet :

public ArrayList < Object > getPhoneNo() {
    ArrayList < Object > phoneNos = new ArrayList < Object > ();
    try {
        Statement stmt = con.createStatement();
        ResultSet result = stmt.executeQuery("SELECT Phone_No FROM paient_details");
        while (result.next()) {
            phoneNos.add(result.getString(1));
        }
    } catch (SQLException e) {
        System.out.println(e.getMessage());
    }

    return phoneNos;
}

You can use the toArray() method from your List object :

String[] phoneNosArray = new String[phoneNos.size()];
phoneNosArray = phoneNos.toArray(phoneNosArray);

First of all, change your ArrayList to :

ArrayList<String> phoneNos = new ArrayList<String>();

since you store String s in it.

Then you can get the corresponding array with :

String[] arr = phoneNos.toArray(new String[phoneNos.size()]);

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