我正在编写一个与Jython一起使用的Java集合类.我希望最终用户能够以这种方式操作集合:
myCollection = MyJavaCollection()
myCollection[0] += 10.;
a = myCollection[0]; //a = 10
myCollection[0] += 20.;
b = myCollection[0]; //b = 20
Run Code Online (Sandbox Code Playgroud)
我在Python文档中找到的是以下方法:
__getitem__和__setitem__方法应该为括号运算符重载做的工作.
__iadd__方法是很好的候选人+=.
我怎么能把两者混合起来想要我想要的?
我有以下界面:
public interface ClusterPopulation
{
public double computeDistance(ClusterPopulation other);
}
Run Code Online (Sandbox Code Playgroud)
是否可以在接口本身中指定,ClusterPopulation的实现A只能将A实现作为computeDistance的参数?
我看到的唯一的approching解决方案如下,但我不喜欢它:
使用泛型重新定义界面:
public interface ClusterPopulation
{
public <T extends ClusterPopulation> double computeDistance(T other);
}
Run Code Online (Sandbox Code Playgroud)
在实现中,如果参数不是来自良好类型,则抛出IllegalArgumentException,如果类型正常,则执行一些强制转换... Meeeeh!
即使采用这种方法,最终用户也只是通过阅读文档/查看代码实现/试验和错误来了解约束...
更好的解决方案?