我希望摆脱clone()方法。
以下类别的sonar(静态代码检查工具)抱怨我“不应该直接公开对象的内部数组”,因为一个人可以在方法调用后更改数组,从而更改对象的状态。它建议在返回之前对该数组进行克隆(clone),以便不更改对象的状态。
以下是我的类...
class DevicePlatformAggregator implements IPlatformListings{
private DevicePlatform[] platforms = null;
public DevicePlatform[] getAllPlatforms() throws DevicePlatformNotFoundException {
if (null != platforms) {
return platforms.clone();
}
List<DevicePlatform> platformlist = new ArrayList<DevicePlatform>();
..... // code that populates platformlist
platforms = platformlist.toArray(new DevicePlatform[platformlist.size()]);
return platforms;
}
}
然而,我不认为克隆是好的,因为重复数据是不必要的。
对于数组而言,没有像Collections.unmodifiableList()这样的东西。
- 我无法将方法getAllPlatforms()的返回类型更改为某个集合类,因为它是一个接口方法。
集合类作为一个接口方法,不能被改变其返回类型。请注意,其中保留了HTML标签。