1

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!

2
  • while ((line = br.readLine()) != null){ String[] split = line.split(":"); ulm.add(new UnigramLanguageModel(split[0],Integer.parseInt(split[1]),true)); } need to check this code part. Please check if underlying .txt file gets seperated properly with : seperator. Seven arraylists got added into another arraylist because of dcx.add(ulm); Commented Jul 9, 2015 at 10:13
  • I have checked the file is read correctly and the individual elements are added to the Object correctly. Yeh I am just curious as to why it is adding empty ArrayLists despite me populating them above? Commented Jul 9, 2015 at 10:18

2 Answers 2

1

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>();
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.