如何在Java中封装数组 [英] How to encapsulate an array in Java

查看:132
本文介绍了如何在Java中封装数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从Java开始,我正在学习setter,getters和encapsulation。我有一个非常简单的程序,两个类:

I'm starting with Java and I'm learning about setters, getters and encapsulation. I have a very simple program, two classes:


  • Container has一个私有的int数组( numArray )和他的setter& getter。

  • Container has a private int array (numArray) with his setter & getter.

Main 创建一个 Container 对象并在 totalArray 方法中使用它。

Main creates a Container object and uses it in totalArray method.

public class Container {
    private int numArray[]= {0,0,0};
    public int[] getNumArray() {
        return numArray;
    }
    public void setNumArray(int index, int value){
        numArray[index] = value;
    }    
}

public class Main {
    public static void main(String[] args) {
        Container conte = new Container();
        System.out.println(totalArray(conte.getNumArray()));
        conte.getNumArray()[2]++;
        System.out.println(totalArray(conte.getNumArray()));
    }
    private static int totalArray (int v[]){
        int total=0;
        for (int conta =0; conta<v.length;conta++){
            total+=v[conta];
        }
        return total;
    }
}






问题:我可以通过getter更改private int数组,我知道这是因为 getNumArray 返回对 numArray 的引用,不是数组本身。如果我对数组的单个元素感兴趣,我会使用索引值创建一个getter,但我希望整个数组用于 totalArray 方法。


Problem: I can change the private int array through the getter, I know that's because getNumArray returns a reference to numArray, not the array itself. If I were interested in a single element of the array, I'd make a getter with an index value, but I want the whole array for the totalArray method.

如何防止 numArray 被修改出来?

推荐答案

所有你可以做的就是阻止人们改变你的数组就是在getter中提供它的副本。

All you can do to prevent people from changing your array is to provide a copy of it in the getter.

public int[] getArray() {
    return Arrays.copyOf(numArray, numArray.length);
}

这样,其他方法可以更改自己的数组副本,但是他们再次调用getter,他们获得了原始版本,没有变化。只有您提供的 setNumArray()才能实际修改内部数组。

This way, other methods can change their own copy of the array, but when they call the getter again, they get the original version, unchanged. Only the setNumArray() you provide can actually modify your internal array.

否则,如果要完全阻止在容器中,您必须删除数组并使用不可变对象。 某些库提供不可变列表,或使用 Collections.unmodifiableList

Otherwise, if you want to completely block the container, you have to drop arrays and use an immutable object. Some libraries provide immutable lists, or use Collections.unmodifiableList.

这篇关于如何在Java中封装数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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