How can I change the length of an array? [duplicate]

我的未来我决定 提交于 2019-12-02 23:09:37

问题


So I am assigned with a project where I have an array and as the user puts elements into this array it will have to double in length once it gets full. We are not permitted to use array lists or anything in the collections interface. What I was trying to do was to make a new array once the old one was full, and then I would copy the values over to the new array. The problem is I don't know how many times I will have to make a new array, so I was wondering how to go about solving this.


回答1:


Arrays are fixed length. If you want a data structure that has variable length use an ArrayList




回答2:


Since the poster explicitly stated the requirements of the homework exclude the use of Collections an alternative approach would be to use System.arraycopy(). In such an approach you only maintain a single array and as you add items to it you use System.arraycopy() to copy the old array into a new larger array. System.arraycopy() is relatively fast and is actually how ArrayList expands its size.

If you are concerned about the cost of using System.arraycopy() you could use it only when your array is full and create a new array with more space. E.g. Create and array of size 20. When it gets full copy it into and array of size 40. When that gets full copy it into an array of size 60...

Interestingly ArrayList increases its size by

int newCapacity = (oldCapacity * 3)/2 + 1;

when the old array is full. Presumably the writers of this put some considerable thought into how much to grow the array by when needed. It might be worth doing the same.



来源:https://stackoverflow.com/questions/28748692/how-can-i-change-the-length-of-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!