如何创建一个字符串数组而不在开始时指定其长度?
我想创建一个字符串数组,但一开始我不知道它的长度。就像数组长度取决于很多因素,只有当我向其中填充字符串/单词时才决定。但是,处理不允许我这样做,它要求我在开始时指定长度。我怎样才能摆脱这个?..感谢所有帮助。任何建议将不胜感激。 阿姆里塔
I want to create an array of strings, but I do not know the length of it in the beginning. It's like the array length depends on many factors and it's only decided when I fill strings/words into it. however, processing does not allow me to do that, it asks me to specify the length in the beginning. How can I get rid of this?..Thanks for all help. Any suggestion will be appreciated.
Amrita
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这样的东西就是你所需要的!您无需担心调整大小、复制内存中的内容或其他任何事情 - 列表只会根据需要扩展。所有性能细节都已得到考虑,除非您真的对它的工作原理感兴趣,否则您无需阅读这些细节即可使用它。
Something like that is all you need! You don't need to worry about resizing, copying stuff in memory or whatever - the list will just expand as it needs to. All of the performance details are taken care of and unless you're really interested in how it works, you don't need to read about those details to use it.
您可以使用ArrayList: http://processing.org/reference/ArrayList.html
You can use ArrayList: http://processing.org/reference/ArrayList.html
我将首先使用 ArrayList 并在必要时调整它的大小。 Java 为 ArrayList 预先分配了内存,因此并非每次调整大小都意味着将内容复制到内存中。访问 ArrayList 比访问 LinkedList 更快(它是 O(1) 而不是 O(n))。只有当你发现ArrayList的调整大小花费太多时间时,我才会考虑切换到LinkedList。
I would start by using ArrayList and resizing it when necessary. Java pre-allocates memory for ArrayList so that not every resize means that the contents are copied in memory. Access to ArrayList is faster than to LinkedList (it's O(1) instead of O(n)). Only if you find that the resizing of the ArrayList takes too much time, would I think of switching to LinkedList.
按照 @berry120 的建议使用类型化的 ArrayList(否则,您需要始终从 Object 转换为 String)。
另外,如果有帮助的话,Processing 有一些处理数组的函数(例如 append() 和 expand())。请查看处理参考中的数组函数。
场景 上面提到的数组函数使用 System.arraycopy(),如果有任何用处的话。
Use the typed ArrayList as @berry120 suggests (otherwise, you'll need to cast from Object to String all the time).
Also, if it helps, Processing has some functions for handling Arrays (like append() and expand()). Look under Array Functions in the Processing reference.
Behind the scenes the above mentioned Array Functions use System.arraycopy(), if that's of any use.
您需要使用 LinkedList 结构:这为您提供了一个易于扩展的容器数组,并在构造函数中采用初始容量,而不是设定的限制。这也比 ArrayList 更有效,每次超过当前容量时,ArrayList 都会复制其内容,而不是简单地添加内容。
You need to use a LinkedList structure: this gives you an easily expanded container array and takes an initial capacity in the constructor, rather than a set limit. This will also be more efficient than an ArrayList, which will copy it's contents every time you exceed the current capacity, rather than simply add to it.