开发者

extend an array of String dynamically

For example, here is one current implementation in memory

String companies[] = {"Alice Berned","Beyonce Cathy","Kelly Boldt"};

The requirement is to extend this directory dynamically at runtime. The records could be as many as thousands. The data structure should facilitate basic functionalities such as search, add,开发者_开发问答 delete.

My solution:

My first thought is to use ArrayList, easy to get and add.

Question: Are there any good way to approach the problem?


Arrays, once created, have a fixed size in Java. After you've created an array, there is no way to add elements dynamically. If you want to do that and you really need to use an array, then the only thing you can do is create a new array with the required new size, copy the elements of the old array to it and add the new data. That's ofcourse cumbersome.

If it is not a requirement that you use an array, use a collection class instead: for example an ArrayList or a LinkedList.

See: Tutorial: Collections


Assuming that, when you say "easy to get and add", the "add" refers to adding to the end of the collection only, then ArrayList is indeed a good option.

If you want to add to the front as well, then ArrayDeque is better. And if you want to be able to add to an arbitrary location, then neither is a very good choice.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜