返回“数据"可能会暴露内部数组? [英] Returning 'data' may exposed internal array?

查看:77
本文介绍了返回“数据"可能会暴露内部数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个

public class Data {

    private final SomeField[] fields;
    .....

    public SomeField[] getFields() {
        return map == null ? null : map.clone();
    }

安全性-方法返回内部数组

Security - Method returns internal array

直接公开内部数组使用户可以修改一些代码 那可能很关键.返回数组的副本更安全.

Exposing internal arrays directly allows the user to modify some code that could be critical. It is safer to return a copy of the array.

我知道我们不应该使用clone()复制对象,而应该使用copy constructor复制对象.

I get that we should not use clone() to copy objects, rather copy the objects using copy constructor.

但这仍然会复制作为引用的内部对象. 为避免出现上述clone()的建议方法是什么?

But that still copies the internal objects which are references. What are recommended ways to avoid clone() above?

谢谢

推荐答案

实用程序方法Arrays.copyOf(T [] original,int newLength)将使用内部数组中的相同对象创建一个新数组.

The utility method Arrays.copyOf(T[] original, int newLength) will create a new array with the same objects from the internal array.

返回内部数组的问题通常是关于防止对数组内容进行意外更改,该更改将与其他任何客户端共享.共享包含的对象通常不会引起同样的关注,但是如果您要实现某种地图,则您的要求可能会更加严格.

The issue with return the internal array is usually about preventing unintended changes to the contents of the array, which would be shared any other clients. Sharing the contained objects is not usually of the same order of concern but if you are implementing some sort of map your requirements may be more stringent.

这篇关于返回“数据"可能会暴露内部数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆