Java动态数组大小? [英] Java dynamic array sizes?

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

问题描述

我有一个类 - xClass,我想将它加载到一个 xClass 数组中,所以我声明:

I have a class - xClass, that I want to load into an array of xClass so I the declaration:

xClass mysclass[] = new xClass[10];
myclass[0] = new xClass();
myclass[9] = new xClass();

但是,我不知道我是否需要 10.我可能需要 8 或 12 或任何其他数字.直到运行时我才知道.我可以动态更改数组中的元素数量吗?如果是,怎么办?

However, I don't know if I will need 10. I may need 8 or 12 or any other number for that matter. I won't know until runtime. Can I change the number of elements in an array on the fly? If so, how?

推荐答案

不,一旦创建数组,就不能更改其大小.您要么必须分配比您认为需要的更大的它,要么接受必须重新分配它需要增加大小的开销.当它发生时,您必须分配一个新数据并将数据从旧数据复制到新数据:

No you can't change the size of an array once created. You either have to allocate it bigger than you think you'll need or accept the overhead of having to reallocate it needs to grow in size. When it does you'll have to allocate a new one and copy the data from the old to the new:

int[] oldItems = new int[10];
for (int i = 0; i < 10; i++) {
    oldItems[i] = i + 10;
}
int[] newItems = new int[20];
System.arraycopy(oldItems, 0, newItems, 0, 10);
oldItems = newItems;

如果您发现自己处于这种情况,我强烈建议您改用 Java 集合.特别是 ArrayList 本质上包装了一个数组并根据需要处理增长数组的逻辑:

If you find yourself in this situation, I'd highly recommend using the Java Collections instead. In particular ArrayList essentially wraps an array and takes care of the logic for growing the array as required:

List<XClass> myclass = new ArrayList<XClass>();
myclass.add(new XClass());
myclass.add(new XClass());

通常,出于多种原因,ArrayList 无论如何都是数组的首选解决方案.一方面,数组是可变的.如果你有一个这样做的类:

Generally an ArrayList is a preferable solution to an array anyway for several reasons. For one thing, arrays are mutable. If you have a class that does this:

class Myclass {
    private int[] items;

    public int[] getItems() {
        return items;
    }
}

您造成了一个问题,因为调用者可以更改您的私有数据成员,这会导致各种防御性复制.将此与列表版本进行比较:

you've created a problem as a caller can change your private data member, which leads to all sorts of defensive copying. Compare this to the List version:

class Myclass {
    private List<Integer> items;

    public List<Integer> getItems() {
        return Collections.unmodifiableList(items);
    }
}

这篇关于Java动态数组大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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