0

I am getting the below error for HashMap in the Java code.

Error - "The type HashMap is not generic; it cannot be parameterized with arguments <>"

package com.example.map;

import java.util.Map;
import java.util.HashMap;

public class HashMap {

    public static void main(String[] args) {
        // compilation error here                vvvvvvv
        Map<Integer, String> mapHttpErrors = new HashMap<>();

        mapHttpErrors.put(200, "OK");
        mapHttpErrors.put(303, "See Other");
        mapHttpErrors.put(404, "Not Found");
        mapHttpErrors.put(500, "Internal Server Error");

        System.out.println(mapHttpErrors);      

    }

}
2
  • 1
    Looks like the same reason this person failed when using ArrayList -- you named your class the same name as the type you're attempting to use. Commented Dec 5, 2017 at 21:33
  • change the name of your class Commented Dec 5, 2017 at 21:33

3 Answers 3

2

You have named your own class HashMap as well.

When you write new HashMap the compiler thinks you're referring to your own class which indeed does not specify any generic parameters.

You can (and in fact: should) either change the name of your class to something else or explicitly refer to java.util.HashMap in your code:

Map<Integer, String> mapHttpErrors = new java.util.HashMap<>();
Sign up to request clarification or add additional context in comments.

1 Comment

To state the obvious, creating a class with the same name as a commonly used java.util class is highly confusing. Changing the name of your class to be HashMapTest or LocalHashMap or ... would certainly be appropriate.
0

As the error is telling you, your HashMap class isn't generic, so your code makes no sense.

You should not make classes with the same names as built-in classes.

1 Comment

Thank you. I just tried changing the class name and got rid of this error.
0

In the following line HashMap refers to the public class you created:

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

Naming your class with exact the same name as classes from official Java API is often a very bad idea. But if you're sure that instead of that, you still want to keep the old name, here is the way you can use the HashMap from java.util package:

Map<Integer, String> mapHttpErrors = new java.util.HashMap<>();

But again, remember that naming your classes as you did in your program is rather a bad idea.

2 Comments

Instead of typing "Sorry this should be a comment" just delete the answer and write it as a comment...
I can't find this option in mobile app, and I just wanted to be quick to don't get tons of downvotes... Yeah they actually started...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.