You need to sign in to do that
Don't have an account?
Kaity
.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?
.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
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.
.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
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