簡體   English   中英

需要使用迭代器的幫助

[英]Need help using an Iterator

我是迭代器的新手。 我有一個帶有字符串對象的名為“ Test”的ArrayList。 我將如何使用迭代器類? 我已經嘗試了所有我能想到的,只是沒有意義。 謝謝您的幫助。

假設我有一個名為“ iter”的迭代器。 我需要單步執行ArrayList來查找某個字符串。 找到該字符串后,我需要將其添加到名為“ test2”的另一個ArrayList中。

while(iter.hasNext()) {
    if(iter.next() == sampleString) {
        test2.add(sampleString);
    }
}

唯一的問題是,當我調用next()時,它將指針移至下一個String,而忽略了ArrayList中的第一個String。 我將如何實施?

您不需要一個。 ArrayList已經可以迭代了! :-D

ArrayList<String> test = new ArrayList<String>();
test.add("Hello");
test.add("world");
for(String str : test) System.out.println(str);

迭代器通常這樣使用:

while (iter.hasNext()) {
    String nextString = iter.next();
    // Do something with the string...
}

有些人(包括我自己)將更喜歡增強的for循環:

for (String nextString : listOfStrings) {
    // Do something with the string
}

for循環避免了獲取顯式Iterator引用的需要,並包含nextString變量聲明,使其簡潔明了且范圍適當。

問題是您對Iterator.next()的工作方式不太了解

直接從Java API復制

E next()-返回迭代中的下一個元素。

這意味着.next()將返回一個對象,然后移至列表中的下一項。

調用next()時需要存儲返回的對象

while(iter.hasNext()) 
{
    String temp = iter.next();
    //this is a more old school method but more true to form. 
    //== doesn't necessarily do equality checks on all objects the way
    //you would think 
    if(temp.equals(sampleString)) 
    {
        test2.add(temp);
    }
}

迭代器只是了解如何遍歷給定數據結構的東西。

您不了解什么?

對於List ,迭代器將跟蹤其在列表中的當前位置,並了解如何獲取列表中的下一個元素。 對於列表來說,它相對簡單,但是您也可以為其他一些不像列表那么簡單的任意數據結構定義一個迭代器。 您還可以定義一個做不同的事情,例如向后遍歷列表。 如果您有關於迭代器的特定問題,請更新您的問題,我們將為您解決:-)

迭代器是遍歷項目集合的一種方法。 遵循該聲明,java.util.Collection 擴展了 Iterable( public interface Collection<E> extends Iterable<E> )。 即所有集合類是可迭代某種方式 iterator()是獲取該Iterator的句柄的方法。 一旦有了手柄,就可以遍歷所有項目。

我之所以強調,是因為並非所有Iterator都允許雙向遍歷。 ListIterator允許這樣做。

我將如下重寫您的代碼

for(String s : myCollection)
{
   if(s.equals(sampleString))
   {
      test.add(s);
   }
}

暫無
暫無

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

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