开发者

Populate a string array from list array in Java

This is my first foray into Java, so forgive me if this is simple, but I am having difficulty iterating through a list and populating a string array with the list items.

Specifically, I am using Jsoup to parse a url and extract certain elements:

Document doc = Jsoup.connect(content).get();
Elements threads = doc.getElementsByClass("page-link");
for (Element src : threads){
    String title = src.text();
    String href = src.attr("href");
        THREADS[0] = title;
}

THREADS is a string array:

static final String[] THREADS = new String[] {};

I don't seem to be able to iterate through the Elements array and populate THREADS with the title values. Leaving the THREADS[0] index in the above example, suc开发者_高级运维cessfully pushes the final title value into the string[], as expected. But using a for(i=0;i<25;i++) type of loop around the THREADS[i] = title; statement causes a force close in the Android application.

Any tips would be awesome.


You've created a zero-element array, and arrays are not resizable. Is there any particular reason that you're not just using a List<String>?

static final List<String> THREADS = new ArrayList<String>();

// ...

for (Element src : threads){
    String title = src.text();
    String href = src.attr("href");
        THREADS.add(title);
}


You have to initialize your array:

static final String[] THREADS = new String[25];

Sure you don't actually mean for(i=0;i>25;i++) but desire for(i=0;i<25;i++), see the differences in < >.

Or even better, as @Matt Ball suggested use a List<String>.


The size of Java arrays is fixed on creation: they do not grow automatically when you add elements in them.

If you know beforehand the number of elements you will put into it, you can create the array with that size. In your case, something like:

String[] THREADS = new String[threads.size()];
int i = 0;
for (Element src : threads) {
  String title = src.text();
  String href = src.attr("href");
  THREADS[i++] = title;
}

Using arrays is not very idiomatic in Java however, as they are not very flexible (they have other issues with typing). It is more common to use one of the many collection types from java.util. The List interface and its ArrayList implementation provide the "growable array of elements" that you want:

List<String> THREADS = new ArrayList<String>();
for (Element src : threads) {
  String title = src.text();
  String href = src.attr("href");
  THREADS.add(title);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜