【发布时间】:2016-04-05 14:10:09
【问题描述】:
我想创建具有以下属性的类 Matrix2D:
- 类应该是通用的
- 应该能够接受尽可能多的类型(最好是全部)
- “默认”构造函数应使用默认类型值初始化所有单元格
- 正确处理大小写,当类型没有默认构造函数时(可能默认参数解决了这个问题)
我该怎么做? 这是我的草图:
class Matrix2D<T> : Cloneable, Iterable<T> {
private val array: Array<Array<T>>
// Call default T() constructor if it exists
// Have ability to pass another default value of type
constructor(rows: Int, columns: Int, default: T = T()) {
when {
rows < 1 -> throw MatrixDimensionException("Number of rows should >= 1")
columns < 1 -> throw MatrixDimensionException("Number of columns should be >= 1")
}
array = Array(rows, { Array(columns, { default }) })
}
}
【问题讨论】: