Meaning of “this” in this code?

前端 未结 6 868
眼角桃花
眼角桃花 2020-12-16 01:31
 public boolean contains(Object o) {
    for (E x : this)
        if (x.equals(o))
            return true;
    return false;
}

Can someone tell me

6条回答
  •  再見小時候
    2020-12-16 02:11

    What exactly means this in this code?

    It is always a reference to the current instance. I assume your class implements the Iterable interface and overrides the Iterator iterator() method from it.

    The loop is just a syntax sugar for the enhanced for statement. According to the specification (§14.14.2.):

    for ({VariableModifier} UnannType VariableDeclaratorId : Expression)
        Statement
    

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

    If the type of Expression is a subtype of Iterable, then the translation is as follows.

    If the type of Expression is a subtype of Iterable for some type argument X, then let I be the type java.util.Iterator; otherwise, let I be the raw type Iterator.

    The enhanced for statement is equivalent to a basic for statement of the form:

    for (I #i = Expression.iterator(); #i.hasNext(); ) {
        {VariableModifier} TargetType Identifier = (TargetType) #i.next();
        Statement
    }
    

    Usually, a class implements the Iterable to provide to an API user the ability of being allowed to iterate over the internal collection hiding the actual implementation.

    Can I write it without this and how?

    1. Use the logic you have written for the inner iterator.
    2. Use the implementation of the underlying collection (if it's and it suits).
    3. Choose one of the options mentioned above and rewrite into a standard for.

提交回复
热议问题