Method returning empty list

0

I'm having a problem with a method in java. The intent is to split a HashMap into pages, and return an ArrayList with each page.

Code:

    public static ArrayList<HashMap<String, Key>> getKeysMap(HashMap<String, Key> map, int maxItemsPerPage) {

    int pageItemAt = 0;
    int pageItemsTotal = 0;
    int mapTotal = map.size();

    HashMap<String, Key> page = new HashMap<>();
    ArrayList<HashMap<String, Key>> pages = new ArrayList<>();

    for(Map.Entry<String, Key> entries : map.entrySet()) {

        System.out.print("  DEBUG:: " + entries.getKey() + " " + entries.getValue() + " " + pageItemAt + " " + pageItemsTotal);

        page.put(entries.getKey(), entries.getValue());
        pageItemAt++;
        pageItemsTotal++;

        if(pageItemAt % maxItemsPerPage == 0 || pageItemsTotal == mapTotal) {

            pages.add(page);
            pageItemAt = 1;
            page.clear();

            System.out.println("-------------");

        }   
    }

    System.out.println(pages);
    for(int i = 0; i < pages.size(); i++) {
        System.out.println(pages.get(i));
    }

    return pages;
}

Debug:

    
asked by anonymous 15.07.2017 / 20:50

1 answer

0

I think your problem is with adding HashMap to the ArrayList and then cleaning it via the clear method. Specifically in this section:

if(pageItemAt % maxItemsPerPage == 0 || pageItemsTotal == mapTotal) {

    pages.add(page);
    pageItemAt = 1;
    page.clear(); // Limpa o HashMap

    System.out.println("-------------");

}   

This section adds a reference to your HashMap in the ArrayList, and then deletes it using the clear method.

Variables of type HashMap are references to a value, and when you run the clear statement, you delete the HashMap referenced by the variable page , which is the same value that was stored in the ArrayList pages .

My suggested correction for you is this:

if(pageItemAt % maxItemsPerPage == 0 || pageItemsTotal == mapTotal) {

    pages.add(page);
    pageItemAt = 1;
    page = new HashMap<>(); // Novo HashMap para a variável page

    System.out.println("-------------");

}  

As with your example, the end result of your application is an ArrayList with multiple references for the same empty HashMap.

    
17.07.2017 / 23:47