动态扩展 String 数组
例如,以下是内存中的一种当前实现
String Companies[] = {"Alice Berned","Beyonce Cathy","Kelly Boldt"};
要求是在运行时动态扩展该目录。记录可能多达数千条。数据结构应便于实现搜索、添加、删除等基本功能。
我的解决方案:
我的第一个想法是使用ArrayList,方便获取和添加。
问题: 有什么好的方法来解决这个问题吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 Java 中,数组一旦创建,就有固定的大小。创建数组后,无法动态添加元素。如果您想这样做并且确实需要使用数组,那么您唯一能做的就是创建一个具有所需新大小的新数组,将旧数组的元素复制到其中并添加新数据。那当然很麻烦。
如果不要求使用数组,请改用集合类:例如
ArrayList
或LinkedList
。请参阅:教程:集合
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 aLinkedList
.See: Tutorial: Collections
假设,当你说“易于获取和添加”时,“添加”指的是仅添加到集合的末尾,那么
ArrayList
确实是一个不错的选择。如果你也想添加到前面,那么
ArrayDeque
会更好。如果您希望能够添加到任意位置,那么两者都不是一个很好的选择。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.