我正在尝试在 java 中定义一些基本的数学概念,但总是遇到泛型错误。考虑下面的例子。在此示例中,我尝试将零映射(所有 x 的 f(x) = 0)定义为常量映射(所有 x 的 f(x) = c)和线性映射(f(a*x + b*y) = a*f(x) + b*f(y))。编译器不允许我这样做,因为“零映射是一个向量”这句话是模棱两可的(在 java 方面,但不是在数学方面)。
你能建议一个干净的解决方案来解决这个问题吗?
// A vector in a finite-dimensional vector space over the real numbers.
interface Vector<V extends Vector<?>>
{
int dimension();
V plus(V v);
V times(double c);
}
interface Mapping<U extends Vector<?>, V extends Vector<?>>
// Does not inherit from Vector because the set of all mappings is an
// infinite-dimensional vector space.
{
V map(U u);
}
// Linear mappings, on the other hand, from one finite-dimensional vector space
// to another, do form a finite-dimensional vector space.
interface LinearMapping<U extends Vector<?>, V extends Vector<?>>
extends Mapping<U, V>, Vector<LinearMapping<U, V>>
{
}
// All elements of U are mapped to getImage(). If V is finite-dimensional, then
// the set of constant mappings is also a finite-dimensional vector space.
interface ConstMapping<U extends Vector<?>, V extends Vector<?>>
extends Mapping<U, V>, Vector<ConstMapping<U, V>>
{
V getImage();
}
// A zero mapping is both constant and linear, but cannot be defined as such.
interface ZeroMapping<U extends Vector<?>, V extends Vector<?>>
extends LinearMapping<U, V>, ConstMapping<U, V>
// Error: The interface Vector cannot be implemented more than once with
// different arguments: Vector<ConstMapping<U,V>> and Vector<LinearMapping<U,V>>
{
}