0

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?

1
  • Do you need this list to persist between multiple executions of the application? Commented Aug 29, 2011 at 21:31

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

4 Comments

Note that creating a new array and copying the old array to it is exactly what ArrayList does.
Exactly why these classes seem to have been created is because of the limitations of Arrays. The do exactly what the OP wants.
@Jay That's true, but if you have to do that manually each time it's cumbersome, ofcourse. Collection classes are made exactly for when you need a dynamically resizeable collection, as Nicholas says.
@Jesper Sure. My intent wasn't to say that you should write code yourself to create new arrays and copy the data rather than use ArrayList. I was just trying to point out that ArrayList isn't magic, that it does exactly what you would have to do yourself if there was no ArrayList.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.