Meaning of “this” in this code?

前端 未结 6 863
眼角桃花
眼角桃花 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:05

    this is a object of the class that contains your contains() method. It refers to the object of that class for which the method is executed.

    Putting it after the : of an enhanced for loop means that the class that contains this method must implement Iterable, since the enhanced for loop can be used to iterate over either arrays or instances of classes that implement the Iterable interface. This means your class is able to iterate over some collection of E elements. E is probably a generic type parameter`.

    In order to write your method without this, you would have to supply a reference to some alternative object that implements Iterable, but I don't see the point of doing that.

提交回复
热议问题