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

查看:110
本文介绍了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 Collections。特别是 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> mysclass = 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; }
}

您创建了一个问题,因为调用者可以更改您的私有数据成员,这导致各种防御性复制。将其与List版本进行比较:

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天全站免登陆