How to get String[] String's to a seperate String?
I have a list of URL's added to a String[] with this.
try {
Elements thumbs = jsDoc.select("div.latest-media-images img.latestMediaThumb");
List<String> thumbLinks = new ArrayList<String>();
for(Element thumb : thumbs) {
thumbLinks.add(thumb.attr("src"));
}
for(String thumb : thumbLinks) {
System.out.println(thumbLinks.get(1));
}
}
How can i add eac开发者_如何学Ch String that is loaded into a separate String?
EDIT:
SO as the images are loaded into the thumbLinks list. I want to get each link to a seperate
String url1;
String url2;
String url3;
If you expect a fixed number of items, and you have a fixed number of String
variables, you have little choice but something like:
String url0 = thumbLinks.get(0);
String url1 = thumbLinks.get(1);
...
String url5 = thumbLinks.get(5);
Well, you could do something grim with reflection, I guess. But probably best to avoid this at all.
take a String array of the size of your ArrayList object - thumbLinks in your case. take an int
variable and initialize it with zero. I have made some changes in your code just have a look:
try{
Elements thumbs = jsDoc.select("div.latest-media-images img.latestMediaThumb");
List<String> thumbLinks = new ArrayList<String>();
for(Element thumb : thumbs) {
thumbLinks.add(thumb.attr("src"));
}
String[] urls = new String[thumbLinks.size()];
int x =0;
for(String thumb : thumbLinks) {
urls[x++] = thumb;
}
}catch(Excpetion e){
}
use urls
for your purpose
ArrayList
has method public <T> T[] toArray(T[] a)
that you can call as described below on thumbLinks
:
String[] url = new String[thumbLinks.size()];
url = thumbLinks.toArray(url);
Then, you will have an array of strings that you can access like this:
System.out.println(url[0]);
System.out.println(url[1]);
System.out.println(url[2]);
// etc, etc. all the say up to thumbLinks.size() - 1
While this is not exactly what you've asked for, it's pretty much the same thing. If you really want variables named url1, url2, url3, etc.
, you're likely going to have to code it line by line for every element in the list.
Just as an aside, you don't need an array to access the elements of your thumbLinks
list directly. You can already do this:
System.out.println(thumbLinks.get(0));
System.out.println(thumbLinks.get(1));
System.out.println(thumbLinks.get(2));
// etc. all the way up to thumbLinks.size() - 1
精彩评论