function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Adelchi PelizzoAdelchi Pelizzo 

Map Constructor

public class TEST {
Map<Integer, String> m1 = new Map<Integer, String>();
m1.put(1, 'First item');
m1.put(2, 'Second item');

}
Why do I get this error: Expecting Right Parenthesis found '1'  ??
Best Answer chosen by Adelchi Pelizzo
SantoshChitalkarSantoshChitalkar
Hi Adelchi,

This is because you didn't include it in method. Refer following code.
 
public class TEST {

    public static void firstMethod(){
        Map<Integer, String> m1 = new Map<Integer, String>();
        m1.put(1, 'First item');
        m1.put(2, 'Second item');
    }
}

Mark this as solve and choose best answer if your issue resolved.

Regards,
Santosh chitalkar

All Answers

SantoshChitalkarSantoshChitalkar
Hi Adelchi,

This is because you didn't include it in method. Refer following code.
 
public class TEST {

    public static void firstMethod(){
        Map<Integer, String> m1 = new Map<Integer, String>();
        m1.put(1, 'First item');
        m1.put(2, 'Second item');
    }
}

Mark this as solve and choose best answer if your issue resolved.

Regards,
Santosh chitalkar
This was selected as the best answer
sfdcchampionssfdcchampions
You are adding code directly to a class instead create a constructor and try again.

public class TEST {
    
   //constructor
    public TEST(){
        Map<Integer, String> m1 = new Map<Integer, String>();
        m1.put(1, 'First item');
        m1.put(2, 'Second item');
    }
}
Adelchi PelizzoAdelchi Pelizzo
Thanks, I thought I can use Map<> as class variable, so it can be used by all methods.
Adelchi
sfdcchampionssfdcchampions
Ok so in that case you can do either way.

public with sharing class TEST {
    Map<Integer, String> m1 = new Map<Integer, String>{1=>'First item',2=>'Second item'};
}

OR


public with sharing class TEST {
    Map<Integer, String> m1 = new Map<Integer, String>();
    //Constructor
    public TEST(){
        m1.put(1, 'First item');
        m1.put(2, 'Second item');
    }
}


Please mark this as resolved if this suffice.

Thanks
sfdcchampionssfdcchampions
Ignore with sharing in my example.
SantoshChitalkarSantoshChitalkar
Hi Adelchi,

In this case, refer following code,
 
public class TEST {
    public static Map<Integer, String> m2 = new Map<Integer, String>{};
    public static void firstMethod(){
        Map<Integer, String> m1 = new Map<Integer, String>();
        m1.put(1, 'First item');
        m1.put(2, 'Second item');
    }
}

Mark this issue as solved and choose best answer.

Regards,
Santosh Chitalkar