“this”的含义在这段代码? [英] Meaning of "this" in this code?
问题描述
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?
推荐答案
这里这个
代表调用当前方法的对象。例如,如果你有 a.contains(x)
,那么里面包含
方法这个
将返回对 a
引用变量中保存的同一对象的引用。
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.
由于你可以在for-each中使用这个
,这意味着包含
方法放在实现 Iterable< E>
接口的类中,因为for-each只能迭代:
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> $ c $的类的实例c>喜欢
List< String>
我们可以在哪里写for(String s:list){...}
- arrays like
String[] array = ...; for(String s : array){...}
- instances of classes which implement
Iterable<E>
likeList<String>
where we can writefor(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;
}
但这意味着您需要以某种方式调用此方法 a.contains(a,x)
因此需要重复 a
两次(更不用说它可以让我们传递其他实例我们班的比 a
喜欢 a.contains(b,x)
)。
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)
).
为了避免这种重复,我们可以使包含
方法 static
允许通过 YourClass.contains(a,x)
调用它。但是这样我们需要从一个基本的OOP概念 - 多态 - 辞职,因为它不适用于 static
方法。
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) {
// ^^^^^^^^^^^^^^
...
}
然后当我们写 a.contains(x)
它被编译为好像我们将调用 a.contains(a,x)
。
Then when we write a.contains(x)
it is compiled as if we would invoke a.contains(a,x)
.
这篇关于“this”的含义在这段代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!