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
srikforcesrikforce 

how to add elements of List 1 to List 2

I have created List 1 and List 2

 

after creating objects to 2 diff classes I have added some elements.

 

List1.add(obj1);  // adding obj1 to the List 1

List2.add(obj2)  // adding obj2 to the List 2

 

Return type for both the Lists are different...

 

now I would like to return List 2 on debug logs but List 2 should contains elements of both List 1 and List 2...

 

Please try to resolve this..

thank u so much ,,,,, 

ChopaForceChopaForce

Hello srikforce,

 

Have you tried to change the type of List2 to List<SObject> ?

As long as the list is initialized to List<SObject> it will be fine. (Don't initialize your list by doing something like this: List<Sobject> list2 = [select ....];   because the collection type will be changed from SObject to the type of your soql query.

 

 

Try something like this:

 

List<Contact> list1 = [select id,name from Contact limit 10];
List<Sobject> list2 = new List<SObject>();

//populate list2 with accounts
for(Account a :  [select id, name from account limit 10])
{
list2.add(a);
}

//insert Contact into list2
for(Contact c : list1)
{
  list2.add(c);
}

for(Sobject obj : list2)
{
  //this will print something like: Contact:{Name=John Doe, Id=003S000000WG05EIAT}
  System.debug(obj);
}

 

Hope it helps,

 

Chopa