public boolean contains(Object o) {
for (E x : this)
if (x.equals(o))
return true;
return false;
}
Can someone tell me what excatly means "this" in this code? Can I write it without this and how?
Coded messages have words or symbols which represent other words, so that the message is secret unless you know the system behind the code. The procedure was repeated for all the letters in the coded message . American English: coded /ˈkoʊdɪd/
The double colon (::) operator, also known as method reference operator in Java, is used to call a method by referring to it with the help of its class directly. They behave exactly as the lambda expressions.
The this keyword refers to the current object in a method or constructor. The most common use of the this keyword is to eliminate the confusion between class attributes and parameters with the same name (because a class attribute is shadowed by a method or constructor parameter).
code noun (COMMUNICATION SYSTEM)a system of words, letters, or signs used to represent a message in secret form, or a system of numbers, letters, or signals used to represent something in a shorter or more convenient form: The message was written in code.
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:
String[] array = ...; for(String s : array){...}
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)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With