-
Arrays
Hello Guys.
I want to know how do we initialize the String array in java, when we do not know what will be the size of the array.
like i want to store the following strings in the string array:
------------
102dwd d fdw f fwf
324 sdf sf sf sf s f
dfe4 34 4 r32
-------------------
i am taking these lines from the txt file, and I do not know the size of the array.
I have used: String Arr[];
but the compiler says that i have to initialize the array, but i do not know the size.
Any sort of information will be appreciated.
Regards
Harbir
-
I'd use an ArrayList like below:
Code:
import java.util.ArrayList;
public class projectMain {
public static void main(String[] args) {
ArrayList arraylist = new ArrayList();
String x = "hdfaldfadf";
String y = "1556fadsfa";
arraylist.add(x);
arraylist.add(y);
for(int a = 0; a < arraylist.size(); a++) {
System.out.println(arraylist.get(a));
}
}
}
-
Quote:
String x = "hdfaldfadf";
u r initializing the array, i can't do that, i do not know how many strings will come into the array.
-
Write to the string, add it to the ArrayList, then rewrite the string, and add to the ArrayList... repeat or just do arraylist.add("whatever");
-
On the whole I think an ArrayList would be your best bet, there are some other alternatives, but all of them involve you essentially rewriting what is done in ArrayList, so just use what you've been given over writing it for yourself.