簡體   English   中英

從Java中的列表數組填充字符串數組

[英]Populate a string array from list array in Java

這是我第一次嘗試Java,因此請您原諒我,如果這很簡單,但是我很難遍歷列表並用列表項填充字符串數組。

具體來說,我正在使用Jsoup解析URL並提取某些元素:

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是一個字符串數組:

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

我似乎無法遍歷Elements數組並用標題值填充THREADS。 如上所示,在上面的示例中保留THREADS[0]索引已成功將最終標題值推入string []中。 但是在THREADS[i] = title;周圍使用for(i=0;i<25;i++)類型的循環THREADS[i] = title; 語句在Android應用程序中導致強制關閉。

任何提示都會很棒。

您已經創建了一個零元素數組,並且數組不可調整大小。 是否有某些特殊原因導致您不僅僅使用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);
}

您必須初始化數組:

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

確定您實際上不是for(i=0;i>25;i++)而是for(i=0;i<25;i++)渴望,請參閱< >的區別。

甚至更好,如@Matt Ball建議使用List<String>

Java數組的大小在創建時是固定的:在其中添加元素時,它們不會自動增長。

如果事先知道要放入其中的元素數,則可以創建具有該大小的數組。 在你的情況下,像:

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;
}

但是,在Java中使用數組不是很習慣,因為數組不是很靈活(它們在鍵入時還有其他問題)。 使用java.util中的多種收集類型之一更為常見。 List接口及其ArrayList實現提供了所需的“元素的可增長數組”:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM