如何在Java中创建可调整的数组?

时间:2023-01-27 15:38:13

What is the best way to do a resizable array in Java? I tried using Vector, but that shifts all elements over by when when you do an insert, and I need an array that can grow but the elements stay in place. I'm sure there's a simple answer for this, but I still not quite sure.

在Java中处理可调整大小的数组的最佳方式是什么?我尝试过使用向量,但是当你做插入的时候,所有的元素都会移动,我需要一个可以增长的数组,但是元素会保持不变。我肯定有一个简单的答案,但我还是不太确定。

10 个解决方案

#1


22  

As an alternative, you could use an ArrayList. It is a resizable-array implementation of the List interface.

作为替代方案,您可以使用ArrayList。它是列表接口的一个resizable-array实现。

Usage (using String):

使用(使用字符串):

List<String> myList = new ArrayList<String>();
myList.add("a");
myList.add("c");
myList.add("b");

The order will be just like you put them in: a, c, b.

订单就像你输入的一样:a, c, b。

You can also get an individual item like this:

你也可以得到这样的单个项目:

String myString = myList.get(0);

Which will give you the 0th element: "a".

第0个元素是a。

#2


4  

Like Sanjo pointed out: "An array is a static datastructure, so they can't grow". The list interface can by backed by an array(for example ArrayList like Kevin pointed out in his post). When the list structure is full and a new item has to be added to the list. Then the structure first creates a new array which can contain the old elements plus the new element which has to be added to the list.

像Sanjo指出的那样:“数组是静态数据结构,所以它们不能增长”。列表接口可以由数组支持(例如Kevin在他的文章中指出的ArrayList)。当列表结构已满且必须向列表中添加新项时。然后该结构首先创建一个新的数组,该数组可以包含旧元素和必须添加到列表中的新元素。

The list interface has a different implementations which all have there pros/cons and you should pick the one best solving your problem-set. Below I will try to give a short summary when to use which implementation:

列表接口有不同的实现,它们都有优缺点,您应该选择最好的解决问题的方法。下面我将尽量简短地总结一下什么时候使用哪个实现:

Not thread-safe implementations:

  • ArrayList: Resizable-array implementation of the List interface. You should use this implementation when you are doing a lot of size, isEmpty, get, set, iterator, and listIterator operations run in constant time. The add operation runs in amortized constant time, that is, adding n elements requires O(n) time. I think you should use this implementation when doing more lookups(get()) then adding items to list(add()).
  • ArrayList:列表接口的resizabl -array实现。当您在执行大量的大小、isEmpty、get、set、iterator和listIterator操作时,您应该使用这个实现。添加操作以平摊不变时间运行,即添加n个元素需要O(n)时间。我认为您应该在执行更多查找(get())然后向list(add())添加项时使用这个实现。
  • LinkedList: This implementation is not backup by an array but "links" the nodes together. In my opinion you should use this implementation when you are doing more add() then get().
  • LinkedList:这个实现不是由数组进行备份的,而是将节点“链接”在一起。在我看来,当您执行更多的add()然后get()时,您应该使用这个实现。

Thread-safe implementations:

Be aware that these list implementations aren't thread-safe which means it is possible to get race conditions when accesing them from multiple threads. If you want to use List implementations from multiple threads I would advise you to study the java.util.concurrent package and use implementation from that class.

请注意,这些列表实现不是线程安全的,这意味着在从多个线程适应它们时,可以获得竞争条件。如果您想使用来自多个线程的列表实现,我建议您学习java.util。并发包并使用该类的实现。

#3


3  

A LinkedList?

LinkedList吗?

#4


3  

You probably should use ArrayList instead of Vector for reasons explained in other answers.

您可能应该使用ArrayList而不是Vector,原因在其他答案中有解释。

However ...

然而……

I tried using Vector, but that shifts all elements over by when when you do an insert, and I need an array that can grow but the elements stay in place.

我尝试过使用向量,但是当你做插入的时候,所有的元素都会移动,我需要一个可以增长的数组,但是元素会保持不变。

When you do an insertElementAt(pos, elem), you have specifically asked for the element shifting. If you don't want the elements to be shifted, you should use set(pos, elem) instead. Or if you want to add the element at the end of the vector, you can also use add(elem).

当您执行insertElementAt(pos, elem)时,您特别要求元素移位。如果不希望元素移位,应该使用set(pos, elem)。或者如果想在向量的末尾添加元素,也可以使用add(elem)。

Incidentally, the previous paragraph applies to all implementations of List, not just Vector, though the implementation details and performance vary across the different kinds of List.

顺便说一下,前面的段落适用于列表的所有实现,而不仅仅是向量,尽管实现细节和性能在不同类型的列表中有所不同。

#5


2  

Check out ArrayList

看看ArrayList

#6


1  

I tried using Vector, but that shifts all elements over by when when you do an insert, and I need an array that can grow but the elements stay in place.

我尝试过使用向量,但是当你做插入的时候,所有的元素都会移动,我需要一个可以增长的数组,但是元素会保持不变。

You probably want to use ArrayList instead of Vector.

你可能想用ArrayList代替向量。

They both provide about the same interface, and you can replace elements with both of them by calling set(idx, element). That does not do any shifting around. It also does not allow you to grow the array, though: You can only insert at already occupied positions (not beyond the current size of the array), to add new elements at the end you have to use add(element).

它们都提供了相同的接口,您可以通过调用set(idx, element)来替换这两个元素。这不会有任何改变。不过,它也不允许扩展数组:您只能在已经占用的位置(不超过数组的当前大小)插入新元素,以便在最后使用add(element)添加新元素。

The difference between ArrayList and Vector is that Vector has synchronization code which you most likely do not need, which makes ArrayList a little faster.

ArrayList和Vector之间的区别是,Vector拥有您最可能不需要的同步代码,这使得ArrayList更快。

#7


1  

If you want to operate array data after all element had already inserted or deleted, there is a way that try to create a LinkedList or ArrayList, its simply resize, after the data input is finished, you can transfer the ArrayList to an Array, then do all the things you normally to Array.

如果你想操作数组数据毕竟已经插入或删除元素,有一种方法,试图创建一个LinkedList或ArrayList,其简单的调整,数据输入完成后,你可以转移ArrayList数组,然后做所有的事情你通常的数组。

#8


1  

ArrayList and LinkedList

ArrayList和链表

Space Complexity:

空间复杂度:

a) ArrayList: Allocates a chunk of memory when you initialize and doubles everytime it reaches it max size whenever you add an element dynamically.

a) ArrayList:初始化时分配一块内存,每次动态添加一个元素时,当它达到最大大小时加倍。

b) LinkedList: It allocates memory only everytime you add an item to the list.

b) LinkedList:它只在每次向列表中添加一个条目时分配内存。

Runtime Complexity:

运行时的复杂性:

a) ArrayList: Search is faster, insertion and deletion is slower compared to linked list

a) ArrayList:搜索速度快,插入和删除速度慢于链表

b) LinkedList: Insertion and deletion is faster, search is slower compared to array list

b) LinkedList:插入和删除速度更快,搜索速度慢于数组列表。

#9


0  

Use either ArrayList or LinkedList.

使用ArrayList或LinkedList。

#10


-3  

Using wonderful classes in Collections framework is the better than using arrays. But in case your question is from a "quizzing" perspective, here is what you should do. Create your own resize method such as:

在集合框架中使用优秀的类比使用数组要好。但如果你的问题是从“提问”的角度出发,你应该这么做。创建您自己的resize方法,例如:

  int[] oldArray = {1,2,3};

  int oldSize = java.lang.reflect.Array.getLength(oldArray);
  Class elementType = oldArray.getClass().getComponentType();
  Object newArray = java.lang.reflect.Array.newInstance(
         elementType,newSize);
  int preserveLength = Math.min(oldSize,newSize);
  if (preserveLength > 0)
      System.arraycopy (oldArray,0,newArray,0,preserveLength);

  oldArray = newArray;

#1


22  

As an alternative, you could use an ArrayList. It is a resizable-array implementation of the List interface.

作为替代方案,您可以使用ArrayList。它是列表接口的一个resizable-array实现。

Usage (using String):

使用(使用字符串):

List<String> myList = new ArrayList<String>();
myList.add("a");
myList.add("c");
myList.add("b");

The order will be just like you put them in: a, c, b.

订单就像你输入的一样:a, c, b。

You can also get an individual item like this:

你也可以得到这样的单个项目:

String myString = myList.get(0);

Which will give you the 0th element: "a".

第0个元素是a。

#2


4  

Like Sanjo pointed out: "An array is a static datastructure, so they can't grow". The list interface can by backed by an array(for example ArrayList like Kevin pointed out in his post). When the list structure is full and a new item has to be added to the list. Then the structure first creates a new array which can contain the old elements plus the new element which has to be added to the list.

像Sanjo指出的那样:“数组是静态数据结构,所以它们不能增长”。列表接口可以由数组支持(例如Kevin在他的文章中指出的ArrayList)。当列表结构已满且必须向列表中添加新项时。然后该结构首先创建一个新的数组,该数组可以包含旧元素和必须添加到列表中的新元素。

The list interface has a different implementations which all have there pros/cons and you should pick the one best solving your problem-set. Below I will try to give a short summary when to use which implementation:

列表接口有不同的实现,它们都有优缺点,您应该选择最好的解决问题的方法。下面我将尽量简短地总结一下什么时候使用哪个实现:

Not thread-safe implementations:

  • ArrayList: Resizable-array implementation of the List interface. You should use this implementation when you are doing a lot of size, isEmpty, get, set, iterator, and listIterator operations run in constant time. The add operation runs in amortized constant time, that is, adding n elements requires O(n) time. I think you should use this implementation when doing more lookups(get()) then adding items to list(add()).
  • ArrayList:列表接口的resizabl -array实现。当您在执行大量的大小、isEmpty、get、set、iterator和listIterator操作时,您应该使用这个实现。添加操作以平摊不变时间运行,即添加n个元素需要O(n)时间。我认为您应该在执行更多查找(get())然后向list(add())添加项时使用这个实现。
  • LinkedList: This implementation is not backup by an array but "links" the nodes together. In my opinion you should use this implementation when you are doing more add() then get().
  • LinkedList:这个实现不是由数组进行备份的,而是将节点“链接”在一起。在我看来,当您执行更多的add()然后get()时,您应该使用这个实现。

Thread-safe implementations:

Be aware that these list implementations aren't thread-safe which means it is possible to get race conditions when accesing them from multiple threads. If you want to use List implementations from multiple threads I would advise you to study the java.util.concurrent package and use implementation from that class.

请注意,这些列表实现不是线程安全的,这意味着在从多个线程适应它们时,可以获得竞争条件。如果您想使用来自多个线程的列表实现,我建议您学习java.util。并发包并使用该类的实现。

#3


3  

A LinkedList?

LinkedList吗?

#4


3  

You probably should use ArrayList instead of Vector for reasons explained in other answers.

您可能应该使用ArrayList而不是Vector,原因在其他答案中有解释。

However ...

然而……

I tried using Vector, but that shifts all elements over by when when you do an insert, and I need an array that can grow but the elements stay in place.

我尝试过使用向量,但是当你做插入的时候,所有的元素都会移动,我需要一个可以增长的数组,但是元素会保持不变。

When you do an insertElementAt(pos, elem), you have specifically asked for the element shifting. If you don't want the elements to be shifted, you should use set(pos, elem) instead. Or if you want to add the element at the end of the vector, you can also use add(elem).

当您执行insertElementAt(pos, elem)时,您特别要求元素移位。如果不希望元素移位,应该使用set(pos, elem)。或者如果想在向量的末尾添加元素,也可以使用add(elem)。

Incidentally, the previous paragraph applies to all implementations of List, not just Vector, though the implementation details and performance vary across the different kinds of List.

顺便说一下,前面的段落适用于列表的所有实现,而不仅仅是向量,尽管实现细节和性能在不同类型的列表中有所不同。

#5


2  

Check out ArrayList

看看ArrayList

#6


1  

I tried using Vector, but that shifts all elements over by when when you do an insert, and I need an array that can grow but the elements stay in place.

我尝试过使用向量,但是当你做插入的时候,所有的元素都会移动,我需要一个可以增长的数组,但是元素会保持不变。

You probably want to use ArrayList instead of Vector.

你可能想用ArrayList代替向量。

They both provide about the same interface, and you can replace elements with both of them by calling set(idx, element). That does not do any shifting around. It also does not allow you to grow the array, though: You can only insert at already occupied positions (not beyond the current size of the array), to add new elements at the end you have to use add(element).

它们都提供了相同的接口,您可以通过调用set(idx, element)来替换这两个元素。这不会有任何改变。不过,它也不允许扩展数组:您只能在已经占用的位置(不超过数组的当前大小)插入新元素,以便在最后使用add(element)添加新元素。

The difference between ArrayList and Vector is that Vector has synchronization code which you most likely do not need, which makes ArrayList a little faster.

ArrayList和Vector之间的区别是,Vector拥有您最可能不需要的同步代码,这使得ArrayList更快。

#7


1  

If you want to operate array data after all element had already inserted or deleted, there is a way that try to create a LinkedList or ArrayList, its simply resize, after the data input is finished, you can transfer the ArrayList to an Array, then do all the things you normally to Array.

如果你想操作数组数据毕竟已经插入或删除元素,有一种方法,试图创建一个LinkedList或ArrayList,其简单的调整,数据输入完成后,你可以转移ArrayList数组,然后做所有的事情你通常的数组。

#8


1  

ArrayList and LinkedList

ArrayList和链表

Space Complexity:

空间复杂度:

a) ArrayList: Allocates a chunk of memory when you initialize and doubles everytime it reaches it max size whenever you add an element dynamically.

a) ArrayList:初始化时分配一块内存,每次动态添加一个元素时,当它达到最大大小时加倍。

b) LinkedList: It allocates memory only everytime you add an item to the list.

b) LinkedList:它只在每次向列表中添加一个条目时分配内存。

Runtime Complexity:

运行时的复杂性:

a) ArrayList: Search is faster, insertion and deletion is slower compared to linked list

a) ArrayList:搜索速度快,插入和删除速度慢于链表

b) LinkedList: Insertion and deletion is faster, search is slower compared to array list

b) LinkedList:插入和删除速度更快,搜索速度慢于数组列表。

#9


0  

Use either ArrayList or LinkedList.

使用ArrayList或LinkedList。

#10


-3  

Using wonderful classes in Collections framework is the better than using arrays. But in case your question is from a "quizzing" perspective, here is what you should do. Create your own resize method such as:

在集合框架中使用优秀的类比使用数组要好。但如果你的问题是从“提问”的角度出发,你应该这么做。创建您自己的resize方法,例如:

  int[] oldArray = {1,2,3};

  int oldSize = java.lang.reflect.Array.getLength(oldArray);
  Class elementType = oldArray.getClass().getComponentType();
  Object newArray = java.lang.reflect.Array.newInstance(
         elementType,newSize);
  int preserveLength = Math.min(oldSize,newSize);
  if (preserveLength > 0)
      System.arraycopy (oldArray,0,newArray,0,preserveLength);

  oldArray = newArray;