Pass a list to another list

apexlist

can someone help me with a question, I have a list with data that I get from a custom object, and I want to pass this data to another list created within the class….showing the code makes it easier to explain

global  class ClassName{
 public List<CustomObj__c> listCustomObj;
 public List<TemporaryCustomObj> listTemporaryCustomObj=new List<TemporaryCustomObj>();
 
 public List<CustomObj__c>getCustomObj(){
          if(listCustomObj==null){
           listCustomObj=[Select Id, field__c,field2__c FROM CustomObj__c];
          }
//What I'm trying to do is pass the data from list1 to list2 but I'm getting an error,
// "listCustomObj.addAll(listTemporaryCustomObj)" gave an error (I imagine because they are different types of list list)
//This was my last try
        
        Integer j=0;
        for(CustomObj__c i :listCustomObj){
           listTemporaryCustomObj[j]=listCustomObj[j];
           j=j+1;



}
public class TemporaryCustomObj{
 public String fieldd1   {get;set;}
 public String fieldd2  {get;set;}

}

Thank you who can help..

Best Answer

You can't generally just assign one arbitrary data type to another. For example, the following is also invalid:

TemporaryCustomObj value = new CustomObj__c();

What you need to do is to translate the data to the correct object. Consider this:

public class TemporaryCustomObj {
  public String field1;
  public String field2;
  // A constructor to load the data from the record
  public TemporaryCustomObj(CustomObj__c source) {
    field1 = source.field1__c;
    field2 = source.field2__c;
  }
}

Now, in your main code, you can:

for(CustomObj__c record: listCustomObj) {
  listTemporaryCustomObj.add(new TemporaryCustomObj(record));
}

We use the constructor of TemporaryCustomObj to load the data into the object. In this way, we're converting the data into a compatible type for the list.