2

I just want to know what is the difference between these two statements.

1) list<account> acc = new list<account>([select id,name,Site from account limit 5]);

2) list<account> acc4 = [select id,name,Site from account limit 10];

Both gave the same output.

  • 2
    There is no difference (except for the difference in the queries). In the first case you use the explicit constructor of List, but in the second case, the list is constructed in the same way. – rael_kid Jan 6 '16 at 12:20
3

The query [select id,name,Site from account limit 10] will return a list of accounts. In example 2, you are directly assigning that list to a variable acc4. In example 1, you take that list of Accounts and use it as input for a list constructor, making an identical list of Accounts from the list returned from the query.

| improve this answer | |
  • 1
    I would always use the second syntax, as it achieves the same result in a cleaner way – mkorman Jan 6 '16 at 13:31
  • The second syntax is actually much more efficient in addition to being cleaner. – Adrian Larson Jan 6 '16 at 18:25
1

I suggest a 3rd syntax which recognises the mostly interchangeability of array and list syntax and looks a bit tidier (and more consistent):

account[] accs = [select id,name,Site from account limit 10];

or better still if no update is to be done just iteration of the collection:

for (account acc : [select id,name,Site from account limit 10]) {
    ....
}
| improve this answer | |
  • Yes, I'm with Keith on this one :) ... for(account acc : [SOQL]{} is better because it is also bulkify ready. – Carlos Naranjo Jan 6 '16 at 19:01

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.