我正在尝试为我自己的泛型类编写自己的迭代器。我一直在看几个 YouTube 教程并在网上搜索。
import java.util.Iterator;
import java.util.NoSuchElementException;
public class Pair<T> implements Iterable<T> {
private T left;
private T right;
public Pair(T left, T right){
this.left = left;
this.right = right;
}
public T getRight(){return this.right;}
public T getLeft(){return this.left;}
// own Iterator
@Override
public Iterator<T> iterator() {
return new myIterator;
}
class myIterator implements Iterator<T>{
T newLeft = null;
@Override
public boolean hasNext() {
if(newLeft == null && Pair.getLeft() != null){
return true;
}
else if(newLeft !=null){
return Pair.getRight() !=null;
}
else {
return false;
}
}
@Override
public T next() {
if(newLeft == null && Pair.getLeft() != null){
newLeft = Pair.getLeft();
return newLeft;
}
else if(newLeft != null){
T newRight = Pair.getLeft();
newLeft = Pair.getRight();
return newRight;
}
throw new NoSuchElementException();
}
}
}
IntelliJ 指出的问题是,我不能按照我尝试的方式在 Iterator-Class 中使用 getLeft 和 getRight ,因为不能从静态上下文中引用非静态方法。我一直在研究静态等等,但无法解决这个问题。我是完全走错了路,还是我的方法至少有点接近?
更新
运行时:
public static void main(String[] args) {
Pair<Integer> intPair= new Pair(5,1);
Pair<String> stringPair=new Pair("foo", "bar");
Iterator<Integer> itr= intPair.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
我遇到了一个无限循环,打印 5。所以,Iterator 本身可以工作,但是我的方法有一个逻辑错误。正在努力,但我感谢任何输入。:)
更新2
发现逻辑错误:NewLeft 从未更改为 null。努力解决它。
更新3
: 解决了!具有嵌入式迭代器类和主类的完整对类,调用如下:import java.util.Iterator;
import java.util.NoSuchElementException;
public class Pair<T> implements Iterable<T> {
private T left;
private T right;
public Pair(T left, T right){
this.left = left;
this.right = right;
}
public T getRight(){return this.right;}
public T getLeft(){return this.left;}
// size of a pair is always 2
public int size =2;
// own Iterator
@Override
public Iterator<T> iterator() {
return new myIterator();
}
// embedded iterator class
public class myIterator implements Iterator<T>{
T newLeft = null;
T newRight = null;
@Override
public boolean hasNext() {
if(newLeft == null && getLeft() != null){
return true;
}
else if(newLeft !=null && newRight == null){
newRight=getRight();
return getRight() !=null;
}
else {
return false;
}
}
@Override
public T next() {
if(newLeft == null && getLeft() != null){
newLeft = getLeft();
return newLeft;
}
else if(newLeft != null && getRight() != null){
newRight = getRight();
return newRight;
}
throw new NoSuchElementException();
}
}
}
主要的:
import java.util.Iterator;
public class main {
public static void main(String[] args) {
Pair<Integer> intPair= new Pair(5,1);
Pair<String> stringPair=new Pair("foo", "bar");
Iterator<Integer> itr= intPair.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
Iterator<String> itrS= stringPair.iterator();
while(itrS.hasNext()){
System.out.println(itrS.next());
}
}
}
谢谢大家,谁帮助,你把我带到了这个解决方案:)