假设我有一个Point
类和一个处理Point
实例的函数
类Point {private final int x,y; ...}
...
void handlePoints(Iterable points){表示(Point p:points){...}}
现在,我想从文件中读取points
。文件的每一行包含两个数字,因此我有一个函数(“工厂方法”)从一行创建point
。
点makePoint(字符串行){...}
我现在应该怎么办?我可以编写一个函数来将文件读取到points
列表中,然后调用handlePoints
函数。
List readPoints(BufferedReader reader){...} //在此处使用makePoint
void handlePoints(BufferedReader reader){
List points = readPoints(阅读器);
handlePoints(points);
}
不幸的是,此功能似乎并不特别优雅,因为它在内存中创建了不必要的点列表。
使用迭代器不是更好吗?
void handlePoints(Iterator points){...}
Iterator readPoints(BufferedReader reader){...} //在此处使用makePoint
void handlePoints(BufferedReader reader){
Iterator points = readPoints(reader);
handlePoints(points);
}
是否有意义?此代码在Java中不会太“嘈杂”吗?
最佳答案
如果您不需要在内存中存储所有内容,请考虑以下几点:
while (reader.ready())
{
String line = reader.readLine();
Point point = makePoint(line);
handlePoint(point);
}
如何使用迭代器和handlePoints执行此操作:(用于添加要处理的异常的代码)
class PointIterator implements Iterator<Point>
{
BufferedReader reader;
PointIterator(BufferedReader myReader) { reader = myReader; };
@Override
public boolean hasNext() { return myReader.ready(); };
@Override
public Point next() { return makePoint(myReader.readLine()); };
@Override
public void remove()
{ throw new UnsupportedOperationException("Remove not supported!"); };
}
并且因为
handlePoints
采用了Iterable
:class PointIterable implements Iterable<Point>
{
BufferedReader reader;
public PointIterable(BufferedReader myReader) { reader = myReader; };
@Override
public Iterator<Point> iterator() { return new PointIterator(reader); }
}
使用方法:
handlePoints(new PointIterable(reader));