假设我想定义一些在结构上相似但参数可能是整数或其他值的类型。
在Java中有没有可能定义由整数甚至任意对象参数化的类族呢?
考虑以下伪代码(无法编译):
/**
* String of a certain length n and a method to reduce to length n-1
*/
public class StringN<int n> {
private String str;
public StringN( String str) {
if(str.length() != n) {
throw new IllegalArgumentException("string is not of required length!");
}
this.str = str;
}
public StringN<n-1> reduce() {
return new StringN<n-1>(s.substring(0, s.length() - 1));
}
@Override
public String toString() {
return str;
}
}
我脑海中想到的其他更自然的例子是数学中的张量积,如果想将空间R^n定义为Java类或在函数编程中的Function<>空间的'arity',那么应该放置参数'n'。那么如何定义具有不同参数n的一组类?
如果Java中无法实现此功能,是否存在于其他更为函数式的语言中,并且该概念的正确名称是什么?(例如,'参数化类'?)
编辑:针对评论所做的最后一部分只是想了解这种概念的通用名称,而不是转向其他语言。