I am new to Apex and Eclipse. I am getting the following error when trying to compile: Save error: Incompatible element type LIST for collection of Id


Set<ID> terrOut = new Set<ID>();
terrOut.add([Select t.Id From Territory__c t where t.Name = 'WI-Brown']);

Territory__c is a custom object. When I execute the SOQL in Eclipse Developer page, the code returns the value correctly.

Any help would be greatly appreciated.

Thank you.


To get around the incompatible argument type

Change This line

terrOut.add([Select t.Id From Territory__c t where t.Name = 'WI-Brown']);

to this

 terrOut.add([Select t.Id From Territory__c t where t.Name = 'WI-Brown' limit 1].Id);

You're trying to add Territory__c to an ID, which isn't a compatible type. Instead, you'll need a means of extracting the ID values. There are two practical ways to do this:

Set<ID> terrOut = new map<Id, Territory__c>([Select t.Id From Territory__c t where t.Name = 'WI-Brown']).keyset();

Set<Id> terrOut = new Set<Id>();
terrOut.addAll(new Map<Id, Territory>([Select t.Id FROM Territory__c t where t.Name = 'WI-Brown']).keyset());

However, you should only use either construct if you are expecting multiple Territory__c records. If you are only ever getting just one, it might be better to use just a single Id value, which may be easier to work with later:

Id terrOut;
Territory__c[] records = [SELECT t.Id FROM Territory__c t WHERE t.Name = 'WI-Brown'];
    terrOut = records[0].Id;
  • friendly bit of advice, like Sfdcfox here has done, I think it's a good practice to, whenever possible, query into a map rather than a list. If you're retrieving a collection, a map gives you all the benefits of a list plus they're id addressable (i.e. map.get('id here')) – Kevin P Sep 9 '13 at 19:22

You need to use addAll() instead of add(), because that query returns a collection.

  • Now I am getting incompatible argument type – user2569499 Sep 9 '13 at 18:09
  • 1
    Your original code implied that you were saving to a collection of sObjects. Now that it has been updated to show a collection of IDs this isn't the correct answer. – Michael Welburn Sep 9 '13 at 19:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.