【发布时间】:2017-11-18 22:38:00
【问题描述】:
我想摆脱 clone() 方法。
对于下面的类声纳(静态代码检查工具)抱怨说 我不应该直接公开对象的内部数组,因为可以在方法调用之后更改数组,从而更改对象的状态。它建议在返回之前对该数组进行 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() for array
- 我无法将方法 getAllPlatforms() 的返回类型更改为 some
集合,因为它是一个接口方法
【问题讨论】: