Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Java Data Structures - Retired Exploring the Java Collection Framework Maps

Grigorij Schleifer
Grigorij Schleifer
10,365 Points

HashMap error in getCategoryCounts()

Here is my code:

   public Map<BlogPost, Integer> getCategoryCounts(){

    Map<String, Integer> countCategory = new HashMap<String, Integer>();

    for (BlogPost post: mPosts) {
      String category = post.getCategory();
      Integer count = countCategory.get(category);

      if (count == null) {
              count = 0;
        count++;
            }

            countCategory.put(category, count);
       }
  return countCategory;  
   }

and here the error:

./com/example/Blog.java:43: error: incompatible types: Map cannot be converted to Map
  return countCategory;  
         ^
Note: JavaTester.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
1 error

Can someone help me???

1 Answer

Seth Kroger
Seth Kroger
56,413 Points

The Map you have declared as the return type is different from the Map you are trying to return. I also see you are incrementing count only if it is null, not for every time you encounter the category.

Grigorij Schleifer
Grigorij Schleifer
10,365 Points

Hi Seth, you are the very best !!!!

Her my code that worked for me :

    public Map<String, Integer> getCategoryCounts(){

    Map<String, Integer> countCategory = new HashMap<String, Integer>();

    for (BlogPost post: mPosts) {
      String category = post.getCategory();
      Integer count = countCategory.get(category);
 if (count == null) {
              count = 0;
            }
            count++;
            countCategory.put(category, count);
       }
  return countCategory;  
   }