"error: no se puede encontrar el símbolo HashMap" [duplicado]

Trying to create (or rather learn) a HashMap in below fashion :

public class Demo{

     public static void main(String args[]){
        System.out.println("============Starting Hashmap============");


        //hashmap portion
        HashMap<String, Integer> myMap = new HashMap<String, Integer>();

        System.out.println("============Ending Hashmap============");
     }
}

I am using an online complier and have searched a lot, i found that my way of declaration is correct but something else is popping up the error
A continuación se muestra el error

Demo.java:8: error: cannot find symbol
                HashMap<String, Integer> myMap = new HashMap<String, Integer>();
                ^
   symbol:   class HashMap
   location: class Demo

   Demo.java:8: error: cannot find symbol
                HashMap<String, Integer> myMap = new HashMap<String, Integer>();
                                                     ^
      symbol:   class HashMap
      location: class Demo

2 errors

What i need help in : m just trying to get the basic of creating a hashmap and inserting some key and value in it, but above error stopped me in very first step.....any help in solving this is appreciated!! :)

preguntado el 12 de febrero de 14 a las 07:02

3 Respuestas

Necesita importar el HashMap en la clase

import java.util.HashMap;

public class Demo{

      public static void main(String args[]){
        System.out.println("============Starting Hashmap============");


        //hashmap portion
        HashMap<String, Integer> myMap = new HashMap<String, Integer>();

        System.out.println("============Ending Hashmap============");
     }
}

Respondido 12 Feb 14, 07:02

you need to import the HashMap to avoid the compile error

import java.util.HashMap;

Respondido 12 Feb 14, 07:02

java.util.HashMap<Character, Integer> map = new java.util.HashMap<>();

Use this if you can't import java.util.HashMap;

Respondido el 01 de Septiembre de 20 a las 14:09

99.98% of the time, this is the wrong thing to do. - Stephen C

@Stephen C, Could you please explain why it is so? - Ranjul Arumadi

Well 99.98% of the time you podemos importar java.util.HashMap. The remaining 0.02% is when your code or a 3rd-party library has done something crazy like defining its own version of HashMap (with the same name!!) AND the import would cause a collision. Referring to a class via it FQN when it is not necessary is just making your code verbose. An experienced Java programmer will tell you that's a bad thing. Just import it. - Stephen C

Sometimes in online coding interviews, the import and other lines will be read only and only one function will be given to complete. Now without using an import statement, how do you import the HashMap? - Jayasurya

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.