【问题标题】:How does "indexOf()" method work and where can it be used?“indexOf()”方法是如何工作的,它可以在哪里使用?
【发布时间】:2016-03-13 01:41:14
【问题描述】:

我是 Java 新手,正在尝试学习迭代器的概念。我从Java Tutorial Oracle 看到了下面的代码,但是,我很难理解这种方法的功能以及如何使用它。有人可以为我提供一个示例,说明如何将此方法用作工作代码的一部分并向我解释它是如何工作的?

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

【问题讨论】:

  • 你有像 {a,b,c,d,e} 这样的列表并且你使用 indexOf 方法像 list.indexOf(a);它将返回 0,因为 a 在列表中为 0。如果你使用 list.indexOf(e);它会给你 4。

标签: java iterator listiterator


【解决方案1】:

这是一种查找元素e(泛型类型E)的索引的方法,该元素可能(或可能不)包含在底层Collection 中。如果存在,它使用it.previousIndex() 返回元素的索引值。否则返回-1

【讨论】:

  • 但不应将“for (ListIterator it = listIterator(); it.hasNext(); )”写成“for (ListIterator it = list.listIterator() ; it.hasNext(); )" 其中 list 是对 ArrayList 或 LinkedList 实例的引用?
  • @TonyStark 如果方法是本身实现List 的类型的一部分,则不会。这里使用this.listIterator
  • 非常感谢您的帮助!我只是想知道您是否可以将此代码 sn-p 作为工作示例的一部分?老实说,我仍然对它并不完全满意,我认为一个可行的例子会对我有很大帮助。对不起,所有的烦恼。再次感谢!
  • 这是ArrayList.indexOf(Object) 的可能实现。这有帮助吗?
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2011-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-18
    • 2014-09-20
    • 1970-01-01
    • 2022-07-31
    • 1970-01-01
    相关资源
    最近更新 更多