Megu
Megu

Reputation: 5

not generic Error in Java HashMap

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);      

    }

}

Upvotes: 0

Views: 630

Answers (3)

Przemysław Moskal
Przemysław Moskal

Reputation: 3609

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.

Upvotes: 0

Marvin
Marvin

Reputation: 14255

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<>();

Upvotes: 2

SLaks
SLaks

Reputation: 887415

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.

Upvotes: 0

Related Questions