简体   繁体   English

为什么 for(T t : this) 起作用,它是什么意思?

[英]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.我刚刚完成了关于集合和在 Java 中实现IterableIterator类的作业。 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.然而,在MyAbstractSet<T>之上实现这个类时,我错误地输入了for(T t: this) ,这让我有些困惑,因为编译器在编译它时没有问题。

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?就像添加泛型类型<T>使类成为某种列表一样,for-each-loop 循环遍历它?

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?有人可以向我解释为什么这会起作用以及它的作用是什么,也许还可以发布一个链接,在 Java 文档中对此进行了解释?

Simply said, it's a combination of these:简单地说,它是这些的组合:

  • An enhanced for loop, I bet you know it:一个增强的 for 循环,我打赌你知道它:

     List<String> listOfStrings = ... for (String string: listOfStrings)
  • T stands for a generic type. T代表泛型类型。 List<T> is a good example. List<T>就是一个很好的例子。

  • this refers to the instance of a class where is the method called. this指的是调用方法所在的类的实例。 Since this implements Iterable<T> , it might be used in the enhanced loop.由于this实现了Iterable<T> ,因此它可能用于增强循环。

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) .因此, for (T t : this)是通过forEach(Consumer<? super T> action)访问的所有元素的类的相同实例的增强循环。

The Java Language Specification, section 14.14.2. Java 语言规范,第14.14.2 The enhanced for statement says: 增强的 for 语句说:

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. Expression的类型必须是原始类型Iterable的子类型或数组类型(第10.1 节),否则会发生编译时错误。

Since your this object implements Iterable , the loop is valid, and will be iterating the elements of your set, by calling the iterator() method.由于您的this对象实现了Iterable ,因此循环是有效的,并且将通过调用iterator()方法来迭代您的集合的元素。

Your loop gets compiled to the following, except that iter is a hidden variable:您的循环被编译为以下内容,除了iter是一个隐藏变量:

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.有关如何编译的完整说明,请参阅上面的 JLS 链接。

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

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