+ Start a Discussion
West415West415 

Incompatible Element Type error when using add() method for a list

Hi,

I'm getting this error in my code:   Save error: Incompatible element type
 
List<Candidate__c> candidateList = new List<Candidate__c>();

Map<String,List<Candidate__c>> candidateMap = new Map<String,List<Candidate__c>>();


.......


candidateList.add( candidateMap.values() );

I did a system.debug() on my map and I see the candidate records.  I'm trying to extract the values out from the map and populate my list, but I get the error "Incompatible element type", I thought the values() method would return a list.

Any help appreciated.
 

Vivek DeshmaneVivek Deshmane
Hi,
Try below code and let me know,
 
List<Candidate__c> candidateList = new List<Candidate__c>();

Map<String,List<Candidate__c>> candidateMap = new Map<String,List<Candidate__c>>();


.......


candidateList.addAll( candidateMap.values() );
Use AddAll insteadd Add
Best regards,
-Vivek
West415West415
I get a slightly different error now "Incompatible argument type"....

I am populating the map using this code which includes the addAll() 

Any ideas why I'm getting this slightly different error?
 
List<Candidate__c> candidateList = new List<Candidate__c>();

Map<String,List<Candidate__c>> candidateMap = new Map<String,List<Candidate__c>>();

for(Candidate__c cand : c.Candidates__r) {

  candidateMap.put(cand.name,new List<Candidate_c> {cand});  

}

candidateList.addAll( candidateMap.values() );

 
Vivek DeshmaneVivek Deshmane
Hi ,
Refer below link and let me know if it works.
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_list.htm#apex_System_List_addAll
 
Vivek DeshmaneVivek Deshmane
Hi,
Try below code.
List<Candidate__c> candidateList = new List<Candidate__c>();

Map<String,List<Candidate__c>> candidateMap = new Map<String,List<Candidate__c>>();

for(Candidate__c cand : c.Candidates__r) {

  candidateMap.put(cand.name,new List<Candidate_c> {cand});  

}

for(String strKey :candidateMap.keyset())
{
   if(candidateMap.get(strKey) !=null)
   {
	for(Candidate__c cand :candidateMap.get(strKey))
	{
         candidateList.add(cand);
	} 
  }	
}