Hi,
I am trying to convert a String into an ArrayList. For example, my Struts2 webapp returns this String named row in a format similar to this:
[A, BB, CCC, DDDD, 1, 0, 1] (something along those lines)
I need to convert them into an ArrayList so I can prepopulate some forms in another JSP page. I hardcoded a method to convert such Strings into list form:
StringBuffer rowBuffer = new StringBuffer(row);
int startIndex = 0;
int endIndex = rowBuffer.indexOf(",") - 1;
rowBuffer.deleteCharAt(rowBuffer.indexOf("["));
rowBuffer.deleteCharAt(rowBuffer.indexOf("]"));
while(startIndex != -1 && endIndex != -1 && startIndex < endIndex)
{
String subString = rowBuffer.substring(startIndex, endIndex);
if(subString.contains(","))
{
rowList.add(" ");
startIndex = endIndex + 1;
endIndex = rowBuffer.indexOf(",", startIndex);
}
else
{
rowList.add(subString);
startIndex = endIndex + 2;
endIndex = rowBuffer.indexOf(",", startIndex + 1);
}
if(endIndex == -1)
{
rowList.add(rowBuffer.substring(startIndex));
break;
}
}
This works fine in cases where all the fields are populated. However, lets say I have a String that looks like this: [A, BB, , , 1, 0, 0] (the 3rd and 4th fields are missing), then I get something that doesn't work (the blank elements don't register correctly, and the size of the list is 6, when it should be 7). Is there a more elegant solution than hardcoding? If not, could someone point me in the right direction on how to handle cases with blank fields? Thanks!