Reputation: 35
Hi all I'm having trouble at the moment with one of my methods at the moment.
ArrayList<ArrayList<UnigramLanguageModel>> arrayListReadCategoriesDC() throws IOException{
BufferedReader br = null;
String line="";
ArrayList<ArrayList<UnigramLanguageModel>> dcx = new ArrayList<ArrayList<UnigramLanguageModel>>();
ArrayList<UnigramLanguageModel> ulm = new ArrayList<UnigramLanguageModel>();
for(int i=0;i<7;i++){
br = new BufferedReader(new FileReader("C:\\Users\\mccluskm\\Desktop\\trainingSet\\"+dcP[i]+"\\"+dc[i]+".txt"));
while ((line = br.readLine()) != null){
String[] split = line.split(":");
ulm.add(new UnigramLanguageModel(split[0],Integer.parseInt(split[1]),true));
}
//System.out.println("Adding stage: "+ulm.size());
dcx.add(ulm);
//System.out.println("From within nested ArrayList: "+dcx.get(i).size());
ulm.clear();
}
br.close();
return dcx;
}
Here is my method where I read in from various files (which represent different categories). Each category gets its own ArrayList and then I want to return an ArrayList>
From within the main method I call it like this:
UnigramLanguageModel ulm = new UnigramLanguageModel ();
ArrayList<ArrayList<UnigramLanguageModel>> dc =ulm.arrayListReadCategoriesDC();
It returns an empty an arraylist holding 7 empty arraylists and I dont know why? If anyone could help I would really appreciate it!
Upvotes: 1
Views: 94
Reputation: 5463
The problem seems to be you are inserting the same reference into the topmost array list always. Instead of using ulm.clear
, create a new ulm object in the loop. That should resolve the issue.
Upvotes: 1
Reputation: 4604
I got your problem.
Please remove ulm.clear();
call from your code. This will solves your problem.
Morover declaring something like below is not good approach-
ArrayList<UnigramLanguageModel> ulm = new ArrayList<UnigramLanguageModel>();
Try instead below--
List<UnigramLanguageModel> ulm = new ArrayList<UnigramLanguageModel>();
Upvotes: 1