如何在 Java 中创建可调整大小的数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2581972/
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
How can I make a resizable array in Java?
提问by Soren Johnson
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 中执行可调整大小的数组的最佳方法是什么?我尝试使用 Vector,但是当您执行插入操作时,所有元素都会移动,并且我需要一个可以增长但元素保持原位的数组。我确信对此有一个简单的答案,但我仍然不太确定。
回答by Alex Budovski
A LinkedList?
一个链表?
回答by Kevin Crowell
As an alternative, you could use an ArrayList. It is a resizable-array implementation of the List interface.
作为替代方案,您可以使用ArrayList。它是 List 接口的可调整大小的数组实现。
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”。
回答by Thilo
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.
我尝试使用 Vector,但是当您执行插入操作时,所有元素都会移动,并且我需要一个可以增长但元素保持原位的数组。
You probably want to use ArrayList instead of Vector.
您可能想使用 ArrayList 而不是 Vector。
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 更快一些。
回答by ring bearer
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:
在 Collections 框架中使用美妙的类比使用数组更好。但是,如果您的问题是从“测验”的角度提出的,那么您应该这样做。创建您自己的调整大小方法,例如:
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;
回答by Alfred
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 ArrayListlike 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.
就像三条指出的:“ An array is a static datastructure, so they can't grow
”。列表接口可以由一个数组支持(例如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. Theadd
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()
). - 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()
thenget()
.
- ArrayList:List 接口的可调整大小的数组实现。当您
size, isEmpty, get, set, iterator, and listIterator
在恒定时间内执行大量操作时,您应该使用此实现。该add
操作在摊销常数时间内运行,即添加 n 个元素需要 O(n) 时间。我认为您应该在执行更多查找(get()
)然后将项目添加到列表(add()
)时使用此实现。 - LinkedList:此实现不是由数组备份,而是将节点“链接”在一起。在我看来,当你正在做的越多,你应该使用这个实现
add()
再get()
。
Thread-safe implementations:
线程安全的实现:
Be aware that these list implementations aren't thread-safe which means it is possible to get race conditionswhen accesing them from multiple threads. If you want to use List implementations from multiple threads I would advise you to study the java.util.concurrentpackage and use implementation from that class.
请注意,这些列表实现不是线程安全的,这意味着从多个线程访问它们时可能会获得竞争条件。如果您想从多个线程使用 List 实现,我建议您研究java.util.concurrent包并使用该类的实现。
回答by jasonfungsing
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,它只是resize,数据输入完成后,你可以将ArrayList转移到一个Array,然后做你通常对 Array 做的所有事情。
回答by Stephen C
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.
我尝试使用 Vector,但是当您执行插入操作时,所有元素都会移动,并且我需要一个可以增长但元素保持原位的数组。
When you do an insertElementAt(pos, elem)
, you have specifically asked forthe 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)
.
当您执行 an 时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
.
顺便说一句,前一段适用于所有的实现List
,而不仅仅是Vector
,虽然实现细节和性能在不同种类的变化List
。
回答by rai.skumar
Use either ArrayList or LinkedList.
使用 ArrayList 或 LinkedList。
回答by user3088680
ArrayList and LinkedList
ArrayList 和 LinkedList
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:插入和删除比数组列表更快,搜索更慢