简体   繁体   中英

why is iterator object not created with new keyword for list collection in Java

I came across this bit of code to remove strings of even length from given Linked list I don't understand why the iterator object itr not instantiated with new keyword. here is the code..

public static void removeEvenLength(List<String> list) {
     Iterator<String> itr= list.iterator();
     while (itr.hasNext()) {
         String element=itr.next();
         if (element.length()%2==0) {
             i.remove();
     }
   }
}       

Does it mean here, that the iterator method is static and it just returns a new iterable object with list as its field . can someone provide with me one or more examples where similar way of instantiating is encountered in Java other than singleton constructors I suppose. Thank you

Does it mean here, that the iterator method is static and it just returns a new iterable object with list as its field.

No, it's an instance method. It just returns a reference to an Iterator<String> . So the body of the iterator() method is likely to contain a new statement (although it's possible that it in turn calls on to something else). Let's take it away from iterators and generics for now - a similar situation is:

class Bar {}

class Foo {
    Bar createBar() {
        return new Bar();
    }
}

public class Test {
    public static void main(String[] args) {
        Foo foo = new Foo();
        Bar bar = foo.createBar();
    }
}

Same pattern: an instance method which returns a new instance of a different type.

Not every object is created explicitly with a new keyword. A method can internally create a new object, do some things to it, and return it.

Depending on the type of List the iterator is usually a private inner class, called Itr in the ArrayList. It is instantiated in iterator( . For the ArrayList example, that method reads as follows:

public Iterator<E> iterator() {
    return new Itr();
}

Other classes implementing List can either use a different private inner class, or may, in certain (non-jre, usually) implementations use an anonymous class.

It's not instantiated with the new operator because list.iterator is not a type, but a method that returns an object that is instantiated within the method. it's merely assigned to the return value of that method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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