Arrays 如何在java中创建只读数组?
我想去掉clone()方法 对于低级声纳(静态代码检查工具)来说 我不应该直接公开对象的内部数组,因为人们可以在方法调用之后更改数组,从而更改对象的状态。它建议在返回之前对该数组进行克隆(),这样对象的状态就不会改变 下面是我的班级Arrays 如何在java中创建只读数组?,arrays,clone,Arrays,Clone,我想去掉clone()方法 对于低级声纳(静态代码检查工具)来说 我不应该直接公开对象的内部数组,因为人们可以在方法调用之后更改数组,从而更改对象的状态。它建议在返回之前对该数组进行克隆(),这样对象的状态就不会改变 下面是我的班级 class DevicePlatformAggregator implements IPlatformListings{ private DevicePlatform[] platforms = null; public DevicePlatf
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;
}
}
class DevicePlatformAggregator实现IPlatformListings{
私有设备平台[]平台=null;
公共DevicePlatform[]GetAllPlatform()引发DevicePlatformNotFoundException{
如果(空!=平台){
返回platforms.clone();
}
List platformlist=新建ArrayList();
..…//填充platformlist的代码
platforms=platformlist.toArray(新设备平台[platformlist.size());
返回平台;
}
}
但是我认为克隆并不好,因为复制数据是不必要的
集合,因为它是一种接口方法我不是Java大师,但我很有信心您在这里运气不好。除了创建一个
0
元素的数组外,没有办法使基元数组不可变
将其设置为final不会有帮助,因为只有指向它的引用是不可变的
正如您已经说过的,获取不可修改列表的方法是使用集合
,如下例所示:
List<Integer> contentcannotbemodified= Collections.unmodifiableList(Arrays.asList(13,1,8,6));
List contentcannotbemodified=Collections.unmodifiableList(Arrays.asList(13,1,8,6));
希望能有帮助