简体   繁体   中英

Trouble adding to an ArrayList of ArrayLists

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!

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>();

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM