简体   繁体   中英

Why does for(T t : this) work and what does it mean?

public abstract class MyAbstractSet<T> implements Iterable<T> { 
    ...
    // some code
    ...
    method addElement(T t){
        for (T t : this) {
           //why does this work????
        }
    }
}

I just finished a homework about sets and implementing Iterable and Iterator classes in Java. The whole purpose of the homework is to understand generics and collections, which I think I kind of grasp now.

However, while implementing this class above MyAbstractSet<T> , I typed for(T t: this) by mistake, which somehow confused me, since the compiler had no problems compiling it.

I tried figuring out what this meant but nothing clear yet. Like does adding the generic type <T> make a class some sort of list, which a for-each-loop iterates over?

Could someone explain to me why this works and what it does, maybe also post a link where this is explained in the Java documentation?

Simply said, it's a combination of these:

  • An enhanced for loop, I bet you know it:

     List<String> listOfStrings = ... for (String string: listOfStrings)
  • T stands for a generic type. List<T> is a good example.

  • this refers to the instance of a class where is the method called. Since this implements Iterable<T> , it might be used in the enhanced loop.

Therefore, for (T t : this) is an enhanced loop of the very same instance of the class of all the elements accessed through forEach(Consumer<? super T> action) .

The Java Language Specification, section 14.14.2. The enhanced for statement says:

The type of the Expression must be a subtype of the raw type Iterable or an array type ( §10.1 ), or a compile-time error occurs.

Since your this object implements Iterable , the loop is valid, and will be iterating the elements of your set, by calling the iterator() method.

Your loop gets compiled to the following, except that iter is a hidden variable:

for (Iterator<T> iter = this.iterator(); iter.hasNext(); ) {
    T t = iter.next();
    ...
}

See the JLS link above for full description of how it gets compiled.

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