Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java Java Data Structures Exploring the Java Collection Framework Maps

Grigorij Schleifer
Grigorij Schleifer
10,364 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,407 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,364 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;  
   }