Here this
represents object on which current method was invoked. For instance if you have a.contains(x)
then inside contains
method this
will return reference to same object as held in a
reference variable.
Since you ware able to use this
in for-each it means that contains
method is placed in class which implements Iterable<E>
interface because for-each can iterate only over:
- arrays like
String[] array = ...; for(String s : array){...}
- instances of classes which implement
Iterable<E>
like List<String>
where we can write for(String s : list){...}
To avoid this
you can explicitly add to your method parameter of class which contains this method, like
public boolean contains(YourClass yc, Object o) {
//and use that parameter in loop instead of `this`
for (E x : yc)
if (x.equals(o))
return true;
return false;
}
but this means you would need to call such method in a way a.contains(a,x)
so it needs to repeat a
twice (not to mention it can allow us to pass other instance of our class than a
like a.contains(b,x)
).
To avoid this repetition we can make contains
method static
which will allow to invoke it via YourClass.contains(a,x)
. But this way we need to resign from one of basic OOP concepts - polymorphism - since it doesn't work with static
methods.
Compiler solves it using first solution, so it compiles our methods like they would be written (and we actually CAN write methods that way) as
public boolean contains(YourClass this, Object o) {
// ^^^^^^^^^^^^^^
...
}
Then when we write a.contains(x)
it is compiled as if we would invoke a.contains(a,x)
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…