2016-03-13 34 views
2

我是Java新手,正在嘗試學習迭代器的概念。我從Java Tutorial Oracle看到下面的代碼,但是,我很難理解這種方法的功能以及它如何使用。有人能給我提供一個如何使用這個方法作爲工作代碼的一部分的例子,並向我解釋它是如何工作的?「indexOf()」方法如何工作以及它可以在哪裏使用?

public int indexOf(E e) { 
    for (ListIterator<E> it = listIterator(); it.hasNext();) 
     if (e == null ? it.next() == null : e.equals(it.next())) 
      return it.previousIndex(); 
    // Element not found 
    return -1; 
} 
+2

你有列表如{A,B,C,d,E}並且使用的indexOf方法等list.indexOf(a)的並且它將返回0,因爲a在列表中爲0。如果你使用list.indexOf(e);它會回報你4 –

回答

2

這是可以(或可以不)被由基礎Collection包含用於發現元件e(通用型E的)的索引的方法。如果存在,它使用it.previousIndex()來返回元素的索引值。否則,它將返回-1

+0

但不應該 「爲(的ListIterator 它的ListIterator =(); it.hasNext();)」 寫成「對(的ListIterator IT = list.listIterator(); it.hasNext( );)「其中列表是對ArrayList或LinkedList實例的引用? – Thor

+1

@TonyStark如果方法是本身實現List的類型的一部分,則不應該。這裏使用'this.listIterator'。 –

+0

非常感謝您的幫助!我只是想知道你是否可以把這段代碼作爲一個工作例子的一部分?說實話,我仍然不完全熟悉它,我認爲一個可行的例子會大大幫助我。對不起,所有的煩惱。再次感謝! – Thor

1

的的indexOf()方法用於查找一個特定字符的索引,或特定子串的字符串中的索引。請記住,一切都是零索引(如果你不知道)。下面是一個簡單的例子:

public class IndexOfExample { 

    public static void main(String[] args) { 

     String str1 = "Something"; 
     String str2 = "Something Else"; 
     String str3 = "Yet Another Something"; 

     System.out.println("Index of o in " + str1 + ": " + str1.indexOf('o')); 
     System.out.println("Index of m in " + str2 + ": " + str2.indexOf('m')); 
     System.out.println("Index of g in " + str3 + ": " + str3.indexOf('g')); 
     System.out.println("Index of " + str1 + " in " + str3 + ": " + str3.indexOf(str1)); 
    } 
} 

輸出:

Index of o in Something: 1 
Index of m in Something Else: 2 
Index of g in Yet Another Something: 20 
Index of Something in Yet Another Something: 12 
相關問題