Either use a List
such as ArrayList
, or use String.split()
instead of StringTokenizer
, it will return a String[]
.
how to dynamically allocate size of string array in java
-
21-07-2023 - |
Question
hello I am beginner to work with java. I have following code, where I wanted to initialize the string array word[] dynamically consisting of size of total no. of tokens in all documents [] array. how should I do that?
String []result = {"Shipment of Gold damaged in fire","Delivery of silver arrived in silver truck","shipment of Gold arrived in Truck"};
String []documents = new String[result.length];
for (int k =0; k<result.length; ++k){
documents[k] = result[k].toLowerCase();
System.out.println("document["+k+"] :" + documents[k]);
}
/*step 2: Tokenize all documents and create vocabulary from it*/
int i=0;
String [] word = new String [30]; // how to do dynamic allocation here
int no_of_tokens=0;
for(String document:documents){
StringTokenizer st = new StringTokenizer(document," ");
System.out.print("tokens in document"+ i +":"+ st.countTokens()+"\n");
while(st.hasMoreTokens()) {
word[no_of_tokens]=st.nextToken();
System.out.print(word[no_of_tokens] + "\n");
no_of_tokens++;
}
i++;
}
Solution
OTHER TIPS
I would use a java.util.ArrayList instead of a static array. You can't resize a static array, but you can create a new, bigger, static array and then copy the initial contents over.
You can use an implementation of the List
interface, like ArrayList
for this case. It will resize automatically when it almost fills so you don't have to worry about figuring the right initial size.
You use it like this:
....
/*step 2: Tokenize all documents and create vocabulary from it*/
int i=0;
List<String> word = new ArrayList<String>(); // how to do dynamic allocation here
int no_of_tokens=0;
....
while(st.hasMoreTokens()) {
word.add(st.nextToken());
System.out.print(word.get(no_of_tokens) + "\n");
no_of_tokens++;
}
You may use ArrayList<String>
or LinkedList<String>
. The two differ in the overhead for add
ing elements (LinkedList is fast, ArrayList is slow) and get
ting elements via get(i) (LinkedList is slow, ArrayList is fast).