0

Good afernoon:

I have recently created a certain class 'X' which contains a single attribute "network" which is defined as a map which uses a String as a key and another map for the value (double map). For this class, the "hashmap" implementation will be used.

The class looks approximately like this:

public class X { private Map<String, Map<String, Integer>> network; //Attribute public X() { network = new HashMap<>(); //An empty map is created } public int method1 { String string = "sentence"; int number = 2; String string2 = "another"; network.put(string, <string2, number>); //NOT WORKING - wrong syntax/wrong initialization? } } 

However, as I execute the network.put instruction contained within the function, the compiler automatically detects an error: "Expression expected". If possible, I would like to know whether I'm using the wrong syntax when adding a new key-value element into the map or if it's the initialization of the map that's causing the error.

All help is greatly appreciated. Thank you.

0

1 Answer 1

2

You need to do:

public class X { private Map<String, Map<String, Integer>> network; //Attribute public X() { network = new HashMap<>(); //An empty map is created } public int method1() { String string = "sentence"; int number = 2; String string2 = "another"; Map<String, Integer> map = new Hashmap<>(); map.put(string2, number); network.put(string, map) ; } } 

The idea is to create and initialize a new HashMap. Then add the key and value pair to it. Finally insert the map into the enclosing map.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much both of you for your answers, the problem is now fixed. Have a good one.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.