表达我的问题有点困难。目前,我在使用 java 中的库方面遇到了很多困难,并且经常不确定如何有效地使用它们。理论上我知道什么是接口(interface)和抽象类,但在实践中这些东西对我来说似乎很难使用。 因此,更具体地说,作为一个例子,目前我正在使用 la4j 库中的 CCS 矩阵。我现在想要迭代它(行和每行中的每个条目)并想要使用该库,但我只找到抽象迭代器(例如 RowMajorMatrixIterator)。一般来说:我不知道如何处理库中的抽象类(或接口(interface))。特别是在此时此刻,作为我的问题的典型实例:如果我有这个抽象迭代器,我如何实际使用它(对于我的 CCS 矩阵)? 感谢您的每一次帮助!
最佳答案
您可以从之前创建的矩阵中获取迭代器:例如,Matrix
类定义了一个方法 rowMajorIterator()
,因此您可以执行以下操作
RowMajorMatrixIterator it = yourMatrix.rowMajorIterator();
这种模式称为“工厂方法”。
正如 Thomas 指出的,它通常作为某种内部类实现,如下所示:
public class MyMatrix extends Matrix {
public RowMajorIterator rowMajorIterator() {
return new RowMajorIterator() { // anonymous class
// needs to implement the abstract methods
public int get() { ... }
...
}
}
}
或
public class MyMatrix extends Matrix {
public RowMajorIterator rowMajorIterator() {
return new MyRowMajorIterator();
}
class MyRowMajorIterator extends RowMajorIterator { // inner, named class
// needs to implement the abstract methods
public int get() { ... }
...
}
}
这些内部类可以访问“外部”类Matrix
的成员。
关于java - 如何使用(la4j 库的)抽象迭代器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46488197/