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
KaityKaity 

.add and .addAll

In apex, while working with List, I have a query-

 

When do we use '.add' and '.addAll' method? Can anyone help me to educate this concept? I've gone through the Apex Guide, but didn't understand much. Thanks in advance?

Best Answer chosen by Admin (Salesforce Developers) 
souvik9086souvik9086

.add - Add one element in a list.

.addAll - Add a list to a list. Situations to add that

 

Suppose a list is coming as a argument in constructor and you need that list to be accessible in some method in the class. Then addAll can be used.

 

List<String> stringList = new List<String>();

public Constructor(List<String> strList){

stringList.addAll(strList);

}

 

If this post is helpful please throw Kudos.If this post solves your problem kindly mark it as solution.

Thanks

All Answers

Sonam_SFDCSonam_SFDC

Kaity,

 

.add method is used in List when you wish to add ONE element to the end of the list.

 

.addall method is used when you wish to add contents of an already existing List  to a List.

 

souvik9086souvik9086

.add - Add one element in a list.

.addAll - Add a list to a list. Situations to add that

 

Suppose a list is coming as a argument in constructor and you need that list to be accessible in some method in the class. Then addAll can be used.

 

List<String> stringList = new List<String>();

public Constructor(List<String> strList){

stringList.addAll(strList);

}

 

If this post is helpful please throw Kudos.If this post solves your problem kindly mark it as solution.

Thanks

This was selected as the best answer
manu manu 23manu manu 23
add is used to add one sobject/elemet
addAll is used to add more than one sobject/elemts
eg:
 list<account> acc=[select name from account limit 5];
        list<account> acc1=new list<account>();
        acc1.add(acc[0]);//only one account is added 
        acc1.addAll(acc);//multiple accounts are added