Java 中的可变长度(动态)数组 [英] Variable length (Dynamic) Arrays in Java

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

问题描述

我想知道如何初始化一个整数数组,使其大小和值在我的程序执行过程中发生变化,有什么建议吗?

I was wondering how to initialise an integer array such that it's size and values change through out the execution of my program, any suggestions?

推荐答案

是:使用 ArrayList.

在 Java 中,普通"数组是固定大小的.你必须给它们一个尺寸,不能扩大或收缩它们.要更改大小,您必须创建一个新数组并复制您想要的数据 - 这对您来说效率低下并且很痛苦.

In Java, "normal" arrays are fixed-size. You have to give them a size and can't expand them or contract them. To change the size, you have to make a new array and copy the data you want - which is inefficient and a pain for you.

幸运的是,有各种实现通用数据结构的内置类,以及其他有用的工具.您需要查看 Java 6 API 以获取完整列表.

Fortunately, there are all kinds of built-in classes that implement common data structures, and other useful tools too. You'll want to check the Java 6 API for a full list of them.

一个警告:ArrayList 只能保存对象(例如整数),不能保存基元(例如整数).在大多数情况下,autoboxing/autounboxing默默地为你照顾这个,但你可能会得到一些奇怪的行为,这取决于你在做什么.

One caveat: ArrayList can only hold objects (e.g. Integers), not primitives (e.g. ints). In MOST cases, autoboxing/autounboxing will take care of this for you silently, but you could get some weird behavior depending on what you're doing.

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

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