I'm having an issue splitting a string array into a List/ArrayList. I realise this is basic stuff but I've looked at so many examples that I've now completely confused myself at what's happening (or not happening).
Some code snippets:
private String[] stringTempList;
private ArrayList<List<String>> arrayImageList = new ArrayList<List<String>>();
My list is read from a webpage and is formatted in plain text like:
So, some lines to strip out the stuff I want/don't want (note - I've separated these out to help me follow the process through):
stringExtractedList = stringText.substring(stringText.indexOf("['") + 2,
stringText.lastIndexOf("']"));
stringTempList = stringExtractedList.split("','");
From what I can see the above works as expected (creating an array (stringTempList), splitting out each item where it sees ','
.
Where it's going wrong:
arrayImageList.add((List<String>) Arrays.asList(stringTempList));
I expect this line to take my array (stringTempList) and move the items into an ArrayList. I was hoping to use code similar to arrayImageList.get(i);
to access individual elements.
However, the code above seems to add all items to the first index in arrayImageList (list size is always 1). Running some debug tests eg Log.d("Test", arrayImageList.get(0));
returns the following:
[One,Two,Three,Four, etc...]
I'd be grateful if someone could point me in the right direction. I think I've confused two different ideas here.
I think you want to use addAll()
instead of add()
You'll also want to declare
private List<String> arrayImageList = new ArrayList<String>();
Change arrayImageList to a list of strings:
private ArrayList<String> arrayImageList = new ArrayList<String>();
and add them using the addAll method:
arrayImageList.addAll((List<String>) Arrays.asList(stringTempList));
您要使用addAll
而不是add
。
I'm not sure i got this "wrong the right way", and I'm not that familiar with java, but here are my thoughts:
Your "arrayImageList" object is an ArrayList of List's. When youre adding your stringTempList-object, that object is correctly stored at the first available index of your 'List-of-lists'. If you want to access the individual elements (strings) from your "arrayImageList", you either have to adress the second dimension (the list of the list) like this:
arrayImageList.get(0).get(i) <- not entirely sure about java-syntax here, but you get the picture.
If on the other hand you dont need the extra dimension, just use ArrayList instead og ArrayList>.
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.