简体   繁体   English

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

[英]Variable length (Dynamic) Arrays in Java

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

Yes: use ArrayList . 是的:使用ArrayList

In Java, "normal" arrays are fixed-size. 在Java中,“普通”数组是固定大小的。 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. 要更改大小,您必须创建一个新数组并复制所需的数据-这效率低下,给您带来痛苦。

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. 您需要检查Java 6 API的完整列表。

One caveat: ArrayList can only hold objects (eg Integers), not primitives (eg ints). 一个警告:ArrayList只能保存对象(例如Integer),而不能保存原语(例如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. 在大多数情况下, 自动装箱/自动拆箱会为您静默处理,但根据您的操作,您可能会得到一些奇怪的行为。

Arrays in Java are of fixed size. Java中的数组大小固定。 What you'd need is an ArrayList, one of a number of extremely valuable Collections available in Java. 您需要的是一个ArrayList,它是Java中许多非常有价值的Collections之一。

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. 然后,要更改列表,可以在适当的Javadocs中找到ints.add(y)ints.remove(z)等许多方便的方法。

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新手往往会尝试不必要地重写自身。

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);

I disagree with the previous answers suggesting ArrayList , because ArrayList is not a Dynamic Array but a List backed by an array. 我不同意前面建议ArrayList答案,因为ArrayList 不是动态数组,而是由数组支持的列表。 The difference is that you cannot do the following: 不同之处在于您不能执行以下操作:

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. 这将为您提供IndexOutOfBoundsException,因为即使支持数组允许添加该元素,但此位置还没有元素。 So you need to use a custom extendable Array implementation like suggested by @randy-lance 因此,您需要使用@ randy-lance建议的自定义可扩展数组实现

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 来源: 如何制作动态数组

  1. It is recommend to use List to deal with small scale size. 建议使用“列表”处理小比例尺。

  2. If you have a huge number of numbers, NEVER use List and autoboxing, 如果您有大量数字,请不要使用列表和自动装箱,

    List< Integer> list List <整数>列表

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. 这些Integer是不必要的对象。 In this case, to use a estimated size would be better, 在这种情况下,使用估计的大小会更好,

int[] array = new int[ESTIMATED_SIZE];

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. 但是,最好的选择是使用来自Jacarta Commons的IntList。 ( here ) 这里

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类)。

How about using a List instead? 如何使用List呢? For example, ArrayList<integer> 例如, ArrayList<integer>

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. 我回答了这个问题,不,您不需要arraylist或任何其他要做的事情,我完成了它,因此,可以增加数组的大小。 Here is the link How to use Java Dynamic Array and here is the link for my question which i answered Java Dynamic arrays 这是如何使用Java动态数组的链接,这是我回答Java动态数组的问题的链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM