Friday 12 February 2016

COMPILE ERROR: Invalid initial type List for Map

As we already know map will be very useful while writing code.

How will we create map<Id,Account> ?

Usually we will do using put method of map

map<Id,Account> map_Account = new map<Id,Account>();
for(Account acc:[Select id,name from account]){
    map_Account.put(acc.id,acc);


Instead of iteration we also can do other way for batter performance.
map<id,Account> account_map = new map<Id,Account>([select id,name from account]);
system.debug('printing-----'+account_map );

Now lets go for little advance, instead of static query what if want to use dynamic query like below

map<id,Account> account_map = new map<Id,Account>(database.query(sQuerry));
system.debug('printing-----'+account_map );

we will get an error message like "COMPILE ERROR: Invalid initial type List<SObject> for Map<Id,Account>"



To address above error we can use like 

map<id,sObject> account_map = new map<Id,sObject>(database.query(sQuerry));

Whenever we have to get some value from map we have to type cast to account that's all.

if(account_map.contains('Accountid') ){
Account acc = (Account)account_map.get(Accountid);
}

Keep exploring and sharing...

No comments: