Amrita
Amrita

Reputation: 1

How do I create an array of strings without specifying its length in the beginning?

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

Upvotes: 0

Views: 3402

Answers (5)

George Profenza
George Profenza

Reputation: 51867

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.

Upvotes: 0

Michael Berry
Michael Berry

Reputation: 72344

List<String> strs = new ArrayList<String>();
strs.add("String 1");
strs.add("String 2");
strs.add("String 3");

System.out.println(strs.size()); //3
System.out.println(strs.get(1)); //String 2

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.

Upvotes: 4

quant_dev
quant_dev

Reputation: 6231

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.

Upvotes: 0

Andreas K&#246;berle
Andreas K&#246;berle

Reputation: 111042

You can use ArrayList: http://processing.org/reference/ArrayList.html

Upvotes: 0

Adrian Taylor
Adrian Taylor

Reputation: 452

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.

Upvotes: -2

Related Questions