如何使用抽象迭代器(la4j 库)?
How to use an abstract iterator (of the la4j library)?
我的问题措辞有点困难。我目前在使用 java 中的库方面遇到很多困难,而且常常不确定如何有效地使用它们。理论上我知道接口和抽象 class 是什么,但似乎在实践中这些东西对我来说很难使用。
因此,更具体地说,例如,目前我正在使用 la4j 库中的 CCS 矩阵。我现在想遍历它(行和每一行中的每个条目)并想为它使用库,但我只找到抽象迭代器(例如 RowMajorMatrixIterator)。总的来说:我不知道如何处理库中的抽象 classes(或接口)。特别是在这一刻,作为我的问题的一个典型实例:如果我有这个抽象迭代器,我如何实际使用它(对于我的 CCS 矩阵)?
感谢您的帮助!
您可以从您事先创建的矩阵中获取迭代器:例如,class Matrix
定义了一个方法 rowMajorIterator()
,因此您可以执行
RowMajorMatrixIterator it = yourMatrix.rowMajorIterator();
这个模式叫做"Factory Method"。
正如 Thomas 指出的那样,它通常被实现为某种内部 class,如下所示:
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() { ... }
...
}
}
这些内部 classes 可以访问 "outer" class Matrix
.
的成员
我的问题措辞有点困难。我目前在使用 java 中的库方面遇到很多困难,而且常常不确定如何有效地使用它们。理论上我知道接口和抽象 class 是什么,但似乎在实践中这些东西对我来说很难使用。 因此,更具体地说,例如,目前我正在使用 la4j 库中的 CCS 矩阵。我现在想遍历它(行和每一行中的每个条目)并想为它使用库,但我只找到抽象迭代器(例如 RowMajorMatrixIterator)。总的来说:我不知道如何处理库中的抽象 classes(或接口)。特别是在这一刻,作为我的问题的一个典型实例:如果我有这个抽象迭代器,我如何实际使用它(对于我的 CCS 矩阵)? 感谢您的帮助!
您可以从您事先创建的矩阵中获取迭代器:例如,class Matrix
定义了一个方法 rowMajorIterator()
,因此您可以执行
RowMajorMatrixIterator it = yourMatrix.rowMajorIterator();
这个模式叫做"Factory Method"。
正如 Thomas 指出的那样,它通常被实现为某种内部 class,如下所示:
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() { ... }
...
}
}
这些内部 classes 可以访问 "outer" class Matrix
.