如何在Java中创建只读数组?

3

我希望摆脱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;
    }
    }

然而,我不认为克隆是好的,因为重复数据是不必要的。

  1. 对于数组而言,没有像Collections.unmodifiableList()这样的东西。

    1. 我无法将方法getAllPlatforms()的返回类型更改为某个集合类,因为它是一个接口方法。

集合类作为一个接口方法,不能被改变其返回类型。请注意,其中保留了HTML标签。

1个回答

2

我不是Java大师,但我相信你在这里是没有运气的。除了创建一个长度为 0 的数组之外,没有办法使原始数组不可变。

将其设置为 final 是无济于事的,因为只有指向它的引用是不可变的。

正如你已经说过的,获取不可修改的列表的方法是使用 Collections,如下面的示例所示:

List<Integer> contentcannotbemodified= Collections.unmodifiableList(Arrays.asList(13,1,8,6));

希望这有所帮助。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接