Java动态数组大小?

新手上路,请多包涵

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

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

但是,我不知道我是否需要 10 个。我可能需要 8 个或 12 个或任何其他数字。直到运行时我才知道。我可以即时更改数组中元素的数量吗?如果是这样,如何?

原文由 Paul 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 433
2 个回答

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

 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 本质上包装了一个数组并负责根据需要增加数组的逻辑:

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

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

 class Myclass {
    private int[] items;

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

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

 class Myclass {
    private List<Integer> items;

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

原文由 cletus 发布,翻译遵循 CC BY-SA 4.0 许可协议

在java中数组长度是固定的。

您可以使用 List 来保存值并在需要时调用 toArray 方法 请参见以下示例:

 import java.util.List;
import java.util.ArrayList;
import java.util.Random;

public class A  {

    public static void main( String [] args ) {
        // dynamically hold the instances
        List<xClass> list = new ArrayList<xClass>();

        // fill it with a random number between 0 and 100
        int elements = new Random().nextInt(100);
        for( int i = 0 ; i < elements ; i++ ) {
            list.add( new xClass() );
        }

        // convert it to array
        xClass [] array = list.toArray( new xClass[ list.size() ] );

        System.out.println( "size of array = " + array.length );
    }
}
class xClass {}

原文由 OscarRyz 发布,翻译遵循 CC BY-SA 2.5 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏