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
-
Must I ask? "What programming language?"Kirk Woll– Kirk Woll2011-09-13 19:22:07 +00:00Commented Sep 13, 2011 at 19:22
-
The answer depends on what environment you are working in. You'll have to give us a clue!Bill Michell– Bill Michell2011-09-13 19:22:46 +00:00Commented Sep 13, 2011 at 19:22
-
Oh, sorry. I am working in Processing. It's java basically!Amrita– Amrita2011-09-13 19:28:26 +00:00Commented Sep 13, 2011 at 19:28
-
@Amrita, ha, I assumed you were asking a question about the concept of "processing", which seemed vague. Now I know it's also a programming language. :)Kirk Woll– Kirk Woll2011-09-14 21:16:15 +00:00Commented Sep 14, 2011 at 21:16
5 Answers
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.
8 Comments
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.
Comments
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.
Comments
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.