Java 中的可变长度(动态)数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2426671/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 07:27:57  来源:igfitidea点击:

Variable length (Dynamic) Arrays in Java

javaarraysdynamicarraylist

提问by Mohammad Sepahvand

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?

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

采纳答案by Pops

Yes: use ArrayList.

是:使用ArrayList

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 中,“普通”数组是固定大小的。你必须给它们一个尺寸,不能扩大或收缩它们。要更改大小,您必须创建一个新数组并复制您想要的数据 - 这对您来说效率低下并且很痛苦。

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 APIfor a full list of them.

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

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

一个警告:ArrayList 只能保存对象(例如整数),不能保存原语(例如整数)。在大多数情况下,自动装箱/自动拆箱会默默地为您处理这个问题,但是根据您的操作,您可能会出现一些奇怪的行为。

回答by Thiago Chaves

You can't change the size of an array. You can, however, create a new array with the right size and copy the data from the old array to the new.

您无法更改数组的大小。但是,您可以创建一个大小合适的新数组,并将数据从旧数组复制到新数组。

But your best option is to use IntList from jacarta commons. (here)

但你最好的选择是使用来自 jacarta commons 的 IntList。(这里

It works just like a List but takes less space and is more efficient than that, because it stores int's instead of storing wrapper objects over int's (that's what the Integer class is).

它的工作方式与 List 类似,但占用的空间更少,效率更高,因为它存储的是 int 而不是将包装对象存储在 int 上(这就是 Integer 类的含义)。

回答by Konrad Garus

How about using a Listinstead? For example, ArrayList<integer>

用 aList代替怎么样?例如,ArrayList<integer>

回答by Mnementh

Arrays are fixed size once instantiated. You can use a List instead.

数组一旦实例化就固定大小。您可以改用列表。

Autoboxing make a List usable similar to an array, you can put simply int-values into it:

自动装箱使 List 类似于数组可用,您可以简单地将 int 值放入其中:

List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);

回答by MattGrommes

Arrays in Java are of fixed size. What you'd need is an ArrayList, one of a number of extremely valuable Collections available in Java.

Java 中的数组是固定大小的。您需要的是一个 ArrayList,它是 Java 中可用的许多极有价值的集合之一。

Instead of

代替

Integer[] ints = new Integer[x]

you use

你用

List<Integer> ints = new ArrayList<Integer>();

Then to change the list you use ints.add(y)and ints.remove(z)amongst many other handy methods you can find in the appropriate Javadocs.

然后改变你使用列表ints.add(y)ints.remove(z)以及许多其他方便的方法,你可以在适当的Javadoc中找到。

I strongly recommend studying the Collections classes available in Java as they are very powerful and give you a lot of builtin functionality that Java-newbies tend to try to rewrite themselves unnecessarily.

我强烈建议您学习 Java 中可用的 Collections 类,因为它们非常强大,并为您提供了许多 Java 新手倾向于尝试不必要地重写自己的内置功能。

回答by Nobody

I answered this question and no you do not need an arraylist or any other thing this was an assignment and I completed it so yes arrays can increase in size. Here is the link How to use Java Dynamic Arrayand here is the link for my question which i answered Java Dynamic arrays

我回答了这个问题,不,你不需要数组列表或任何其他东西,这是一项任务,我完成了它,所以是的,数组可以增加大小。这是链接 如何使用 Java 动态数组,这是我回答Java 动态数组的问题的链接

回答by cspann

I disagree with the previous answers suggesting ArrayList, because ArrayListis nota Dynamic Array but a List backed by an array. The difference is that you cannot do the following:

我不同意前面建议的答案ArrayList,因为ArrayList不是动态数组,而是由数组支持的列表。不同之处在于您不能执行以下操作:

ArrayList list = new ArrayList(4);
list.put(3,"Test");

It will give you an IndexOutOfBoundsException because there is no element at this position yet even though the backing array would permit such an addition. So you need to use a custom extendable Array implementation like suggested by @randy-lance

它会给你一个 IndexOutOfBoundsException 因为在这个位置还没有元素,即使后备数组允许这样的添加。因此,您需要使用@randy-lance 建议的自定义可扩展数组实现

回答by Hao Deng

  1. It is recommend to use List to deal with small scale size.

  2. If you have a huge number of numbers, NEVERuse List and autoboxing,

    List< Integer> list

  1. 建议使用 List 来处理小规模的尺寸。

  2. 如果您有大量数字,切勿使用列表和自动装箱,

    列表<整数> 列表

For every single int, a new Integer is auto created. You will find it getting slow when the size of the list increase. These Integers are unnecessary objects. In this case, to use a estimated size would be better,

对于每一个 int,都会自动创建一个新的 Integer。当列表的大小增加时,您会发现它变慢。这些整数是不必要的对象。在这种情况下,使用估计的大小会更好,

int[] array = new int[ESTIMATED_SIZE];

回答by Anuj Dhiman

Simple code for dynamic array. In below code then array will become full of size we copy all element to new double size array(variable size array).sample code is below 

public class DynamicArray {
 static   int []increaseSizeOfArray(int []arr){
          int []brr=new int[(arr.length*2)];
          for (int i = 0; i < arr.length; i++) {
         brr[i]=arr[i];     
          }
          return brr;
     }
public static void main(String[] args) {
     int []arr=new int[5];
      for (int i = 0; i < 11; i++) {
          if (i<arr.length) {
              arr[i]=i+100;
          }
          else {
              arr=increaseSizeOfArray(arr);
              arr[i]=i+100;
          }        
     }

for (int i = 0; i < arr.length; i++) {
     System.out.println("arr="+arr[i]);
}    
}

}

Source : How to make dynamic array

来源:如何制作动态数组