简体   繁体   English

for (ListIterator<E> it = listIterator(); it.hasNext(); ) VS for (ListIterator<E> it = list.listIterator(); it.hasNext(); )

[英]for (ListIterator<E> it = listIterator(); it.hasNext(); ) VS for (ListIterator<E> it = list.listIterator(); it.hasNext(); )

Could someone tell me, if the for (ListIterator<E> it = listIterator(); it.hasNext(); ) part of the code should be instead written as for (ListIterator<E> it = list.listIterator(); it.hasNext(); ) where list is an reference to an instance of ArrayList or LinkedList class?有人能告诉我,如果 for (ListIterator<E> it = listIterator(); it.hasNext(); )部分代码应该写成for (ListIterator<E> it = list.listIterator(); it.hasNext(); )其中list是对 ArrayList 或 LinkedList 类实例的引用? Is both form acceptable and correct?两种形式都可接受且正确吗? Where should I use one over the other?我应该在哪里使用一个?

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;
}
for (ListIterator<E> it = listIterator(); it.hasNext(); )

This code calls listIterator() of myself ( this ) and use its return value.此代码调用我自己( this )的listIterator() ) 并使用其返回值。 The class where this code is written has higher chance to List is implement ed.编写此代码的类有更高的机会List被实现。

for (ListIterator<E> it = list.listIterator(); it.hasNext(); )

This code calls listIterator() of the instance reference to which is stored in list and use its return value.此代码调用存储在list中的实例引用的listIterator()并使用其返回值。 This code may appear everywhere to write routines.这段代码可能会出现在写例程的任何地方。

Both are acceptable, but whether thay are correct should depend on what you want to do.两者都是可以接受的,但是否正确应该取决于您想要做什么。

It would be something like this:它会是这样的:

import java.util.ListIterator;
import java.util.ArrayList;

public class TestIndexOf<E> extends ArrayList<E> {
    private static final long serialVersionUID = 1L;

    @Override
    public int indexOf(Object e){
        for(ListIterator<E> it = listIterator(); it.hasNext();)
            if (e == null ? it.next() == null: e.equals(it.next()))
            return it.previousIndex();
        return -1;
    }

    public static void main(String[] args){

        TestIndexOf<String> ti = new TestIndexOf<>();
            ti.add("a");
            ti.add("b");
            ti.add("c");
            ti.add("d");

        System.out.format("The index of %s is %d\n", "b", ti.indexOf("b"));
    
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM