在Java中可变长度(动态)阵列 [英] Variable length (Dynamic) Arrays in Java

查看:122
本文介绍了在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 API 6 为他们的完整列表。

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中只能保存对象(例如整数),而不是原语(例如整数)。在大多数情况下,<一href=\"http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html\">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天全站免登陆