Converting ArrayList to Array
Hi,
I am reading the data from a file and Storing in an array. The size of the file( in the sense no of lines) not known. So, for dynamic allocation of memory i used ArrayList.
Can u tell me the way to return this ArrayList variable and how to catch it in calling function.
I tried another method, storing all this data in an array and returning this array to calling function.
I am putting the code how I did.
import java.util.*;
import java.io.*;
public class ArrayCopying
{
public static void main(String [] args) throws IOException
{
String[] a=printOutputFile();
// printing the array a
for(int i=0;i<a.length;i++)
System.out.println(a[i]);
}
public static String[] printOutputFile()
{
String arr[]=null;
try
{
BufferedReader Source = new BufferedReader(new FileReader("PrintOutput.txt"));
ArrayList Hits = new ArrayList();
String line;
while ((line = Source.readLine()) != null)
{
String tkn[] =line.split(",");
for(int i=0;i<tkn.length;i++)
Hits.add(tkn[i]);
}
arr=new String[Hits.size()];
System.out.println(Hits.size()+" & "+arr.length); // Usage:checking purpose
for (int i=0; i<Hits.size(); i++)
System.out.println(Hits.get(i)); // Printing well
for (int i=0; i<Hits.size(); i++)
{
System.out.println(Hits.get(i)); // reading the 1st string later it displaying null
arr=(String [])Hits.toArray();
System.out.println(arr[i]);
}
}
catch(Exception e)
{
System.out.println("Exception: " + e);
}
return arr;
}
}