-1

I´m unable to create HashMap/ArrayList objects. If I try to create a new HashMap, IntelliJ is asking for initialCapacity and LoadFactor, which is supposed to be an int/float. If I declare a HashMap with String/String K/V the code is underlined, IntelliJ can recognise it as a new object, but the put method is missing or not recognised. I´m not sure what could cause it, I have reinstalled the JDK and IntelliJ but the problem remains. I have also opened some older rojects where anything written previously works fine, however new lines produce the same issue. Here is snippet of my code just as an example:


import java.util.*;

public class TestClass {
    HashMap<String, String> testMap = new HashMap<>("firstString", "secondString");
    testMap.put("first", "second");
}

screenshot

Some data that might be relevant: -java version "17.0.5" 2022-10-18 LTS -IntelliJ community IDEA 2022.2.3

Thanks a lot for the help in advance, and sorry for the bad formatting, I´ll make sure to improve it in the future.

  • Look at [the list of HashMap constructors](https://docs.oracle.com/en/java/javase/19/docs/api/java.base/java/util/HashMap.html#constructor-summary). See the problem? – VGR Nov 22 '22 at 23:28

1 Answers1

1

There is no constructor of HashMap that receives a sequence of keys and values.

Either use:

HashMap<String, String> testMap = new HashMap<>();
testMap.put("firstString", "secondString");
testMap.put("first", "second");

or

Map<String,String> testMap = Map.of("firstString", "secondString", "first", "second");

(although the latter is immutable)

Javier
  • 12,100
  • 5
  • 46
  • 57
  • Definietly eye opening, I should read documentations as everybody suggests it. Actually I ended up with this syntax after experimenting, as creating an empty HashMap didn’t work out. The issue is still there, it’s not the source of the problem. – Putterur Nov 22 '22 at 23:13
  • Just an update on it because someone might make the same mistake. The HashMap/ArrayList can be declared as a variable but adding elements is only possible in a constructor of the class or in a method. – Putterur Nov 23 '22 at 10:01