今天我学习了Iterator模式,但是我不太理解代码。你能帮我一下吗?
这里有一门课:
public class Repository implements Container{
public String[] names = {"John", "Iren", "Anthony", "Lorn"};
@Override
public Iterator getIterator() {
return new MyIterator();
}
private class MyIterator implements Iterator {
int index;
@Override
public boolean hasNext() {
if (index < names.length) {
return true;
}
return false;
}
@Override
public Object next() {
if (this.hasNext()) {
return names[index++];
}
return null;
}
}
}主要的方法是:
public static void main(String[] args) {
Repository name = new Repository();
for (Iterator iter = name.getIterator(); iter.hasNext(); ) {
String local = (String) iter.next();
System.out.println("Name = " + local);
}
}问题是关于方法next():
@Override
public Object next() {
if (this.hasNext()) {
return names[index++];
}
return null;
}在这种情况下,我不明白关键字的含义。这是什么参考?
发布于 2015-07-04 15:57:57
this关键字是对您所在的非静态方法的对象的引用。这里this位于MyIterator对象的next()方法中,因此this是对MyIterator对象的引用。注意,在所提供的代码中,您可以省略this.并编写简单的if(hasNext()) {...}。
发布于 2015-07-04 16:10:45
发布于 2015-07-04 17:30:28
Java中的这个关键字是一个特殊的关键字,可以用来表示Java中任何类的当前对象或实例。“this”关键字还可以调用Java中相同类的构造函数,并用于调用重载的构造函数。
"this“有时还与Super关键字相关联,它用于表示Java中超类的实例,并可用于调用Java中的重载构造函数。
--> this keyword represent current instance of class.
--> this keyword can be used to call overloaded constructor in java. if used than it must be first statement in constructor this() will call no argument constructor and this(parameter) will call one argument constructor with appropriate parameter. here is an example of using this() for constructor chaining:
Example
"this" keyword to call constructor in Java
class Student{
private int id;
private String name;
public Student(){
this(“Student of the year”);
}
public Student(int id){
this.id = id;
this.interest = 0.0;
}
}
If member variable and local variable name conflict, this can be used to refer member variable.
Example #2
public Student(int id, double name){
this.id = id;
this.name = name;
}
this is a final variable in Java and you can not assign value to this.
this = new Student(); //this will result in compilation error--cannot assign value to final variable : this
Or you can call methods of class by using this keyword
Example #3
public String getName(){
return this.toString();
}
Or this can be used to return object. this is a valid return value.
Example #4
public Student getStudent(){
return this;
}在您的示例中,我认为"this“可以表示您当前的对象存储库中包含的字符串数组名称,这些字符串名称在每个elements.And中都有John、Iren、Anthony、Lorn,作为单词/ String在每个this.hasnext()中都会返回true,当迭代有更多的值时,这意味着如果当前对象数组中仍然有单词,它将继续在屏幕上显示人员的名称。否则,它将取出"if“块并返回为null。
https://stackoverflow.com/questions/31222538
复制相似问题