2 will rast Will_Rast 于 2015.06.02 15:21 提问

Thinking in java 中遇到的关于内部类的小问题

// Sequence.java

interface Selector{
boolean end();
Object current();
void next();
}

public class Sequence{
private Object[] items;
private int next = 0;
public Sequence(int size){ items = new Object[size]; }
public void add(Object x){
if(next < items.length )
items[next++] = x;
}
private class SequenceSelector implements Selector{
private int i = 0;
public boolean end(){ return i == items.length ;}
public Object current(){ return items[i]; }
public void next(){ if(i < items.length) i++; }
}
public Selector selector(){
return new SequenceSelector();
}
public static void main(String[] args){
Sequence sequence = new Sequence(10);
for(int i = 0; i < 10; i++)
sequence.add(Integer.toString(i));
Selector selector = sequence.selector();
while(!selector.end()){
System.out.println(selector.current()+" ");
selector.next();
}
}
}

// 书上的原话:
举个例子,如果Sequence.java不适用内部类,就必须声明“Sequence是一个Selector”,对于某个特定的Sequence只能有一个Selector。然而使用内部类很容易能够拥有另一个方法reverseSelector(),用它来生成一个反向遍历的Selector。只有内部类才有这种灵活性。

// 问题:
实现Sequence.java中的reverseSelector()方法

1个回答

llx1943llx
llx1943llx   2015.06.04 09:55

Sequence类中新加一个内部类:

private class ReverseSequenceSelector implements Selector{
    private int i = items.length;
    public boolean end(){ return i == 0 ;}
    public Object current(){ return items[i]; }
    public void next(){ if(i > 0) i--; }
}

然后再加一个方法reverseSelector():

public Selector reverseSelector(){
    return new ReverseSequenceSelector();
}
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!