Method Returning Empty List

Asked

Viewed 750 times

1

I am having a problem with a java method. The intention 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:

Debug

1 answer

1

I believe your problem is the inclusion of Hashmap in Arraylist and subsequent cleaning by method clear. 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 via the method clear.

Hashmap type variables are references to a value and when executing the statement clear, you delete the Hashmap referenced by the variable page, which is the same value that was stored in Arraylist pages.

My suggestion of 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("-------------");

}  

The way your example looks, the end result of your application is an Arraylist with multiple references to the same empty Hashmap.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.