How to change String Array to ArrayList in java -
here original code has defined string-array (25). working perfectly. don't need define 25. instead, used arraylist. please check code.
using string of array:
public string[] getemailaddr(string straccountnbr) throws exception { string strquery2 = null; resultset rs = null; preparedstatement ps = null; string[] emailaddress = new string[25]; int i=0; strquery2 = "select c.emailaddress emailaddress" + " customeremailid c " + "where c.accountnbr = ? " ; logmsg("strquery2: "+strquery2); ps = getdbconn().preparestatement(strquery2); ps.setstring(1, straccountnbr); rs = ps.executequery(); while(rs.next()) { emailaddress[i]=(rs.getstring("emailaddress")); logmsg("emailaddress[i]"+" "+i+": "+emailaddress[i]); i=i+1; } homecoming emailaddress; }
here, need alter string-array arraylist. tried this,
public string[] getemailaddr(string straccountnbr) throws exception { string strquery2 = null; resultset rs = null; preparedstatement ps = null; //newly tried // arraylist<string> strarremailids = new arraylist<string>(); string[] emailaddress= new string[strarremailids.size()]; strarremailids.toarray(emailaddress); //newly tried // int i=0; strquery2 = "select c.emailaddress emailaddress" + " customeremailid c " + "where c.accountnbr = ? " ; logmsg("strquery2: "+strquery2); ps = getdbconn().preparestatement(strquery2); ps.setstring(1, straccountnbr); rs = ps.executequery(); while(rs.next()) { emailaddress[i]=(rs.getstring("emailaddress")); logmsg("emailaddress[i]"+" "+i+": "+emailaddress[i]); i=i+1; } homecoming emailaddress; }
email ids database instead of example.com.
but getting java.lang.arrayindexoutofboundsexception: 0
error in line. emailaddress[i]=(rs.getstring("emailaddress"));
please help!
this not how utilize arraylist
.
first, need write:
list<string> strarremailids = new arraylist<>();
so, programme interface
, utilize java 7 diamond operator.
next, remove index i
. don't need this.
finally, do:
emailaddress.add(rs.getstring("emailaddress"));
to convert string[]
can do:
string[] arr = emailaddress.toarray(new string[emailaddress.size()]);
here suggestion final code:
public string[] getemailaddr(string straccountnbr) throws exception { final list<string> emailaddress = new arraylist<>(); final string strquery2 = "select c.emailaddress emailaddress" + " customeremailid c " + "where c.accountnbr = ? "; seek (final preparedstatement ps = getdbconn().preparestatement(strquery2)) { ps.setstring(1, straccountnbr); seek (final resultset rs = ps.executequery()) { while (rs.next()) { emailaddress.add(rs.getstring("emailaddress")); } } } homecoming emailaddress.toarray(new string[emailaddress.size()]); }
i have removed pointless assignments null
. have added try-with-resources blocks close external resources, code 1 massive memory leak.
java arrays string arraylist
No comments:
Post a Comment