用Java定义我自己的不可变数组 [英] Defining my own immutable array in Java

查看:108
本文介绍了用Java定义我自己的不可变数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道声明数组final不会使它不可变.

I know that declaring an array final does not make it immutable.

但是我可以定义一个包装类,其功能类似于不可变数组,例如

I can however define a wrapper class that functions like an immutable array, e.g.

public class ImmutableIntArray {
    private int[] array;

    public ImmutableIntArray(int[] array) {
        this.array = (int []) array.clone();
    }

    public int get(int i) {
        return array[i];
    }

    public int length() {
        return array.length;
    }

    public static void main(String[] args) {
        ImmutableIntArray a = new ImmutableIntArray(new int[]{1, 2, 3});

        for (int i = 0; i < a.length(); ++i)
            System.out.println(a.get(i));
    }
}

这种方法对我来说似乎很优雅,但是,这似乎是一种显而易见的方法,令我感到惊讶的是,我还没有看到其他人使用它.为什么这不应该成为某个地方的标准库的一部分呢?我是否对该定义有任何错误,以至于我的班级实际上是可变的?

This approach seems elegant to me, however, it seems like quite an obvious approach that I'm surprised I haven't seen anyone else apply it. Why shouldn't this be for example part of a standard library somewhere? Am I making any mistakes about this definition, so that my class is in fact mutable?

我相信对于任何不可变的Object都可以使用相同的方法,我什至可以使用泛型(即ImmutableArray<T>类)对其进行定义.

I believe the same approach would work for any Object which is immutable, that I could even define it using generics, i.e. an ImmutableArray<T> class.

推荐答案

您正在重新发明轮子. 使用收藏集#unmodifiableList(..).

Collections.unmodifiableList(Arrays.asList(yourArray)); 

这篇关于用Java定义我自己的不可变数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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