Wanted to know the difference between these two line

List<Int_No__c> outField = new List<Int_No__c>([select Id,Name, from Int_No__c where  Dir__c ='Out']); 

and the second way of declaring

List <Int_No__c> outField = [select Id,Name, from Int_No__c where  Dir__c ='Out']; 

It seems to me that they are same . Thanks in advance for looking


They are not the same.

You don't need to do this,

List<Int_No__c > outField = new List<Int_No__c >([select Id,Name, from Int_No__c where Dir__c ='Out']);// consumes more cpu power

You should always use the below method with a query.

List<Int_No__c > outField = [select Id,Name, from Int_No__c where Int_No__c ='Out'];

The constructor of the List class List<T>(listToCopy) creates a new instance of the List class by copying the elements from the specified list. T is the data type of the elements in both lists and can be any data type.

IF you want to copy some list to new instance then you can use like below

List<Integer> ls1 = new List<Integer>();
// Create a list based on an existing one
List<Integer> ls2 = new List<Integer>(ls1);
// ls2 elements are copied from ls1
System.debug(ls2);// DEBUG|(1, 2)


| improve this answer | |
  • 1
    thanks a lot Rahul ,its pretty clear now – user75937 Jan 3 at 5:36
  • most welcome!!! – rahul gawale Jan 3 at 6:00

FYI, I use the array syntax of [] for the type (that is syntactic sugar over list) as I think it makes this common-case code more symmetrical on the left and right sides:

Int_No__c[] outField = [select Id,Name, from Int_No__c where  Dir__c ='Out'];
| improve this answer | |
  • thanks a lot Keith yup will use this now on as this will make the code symmetric – user75937 Jan 3 at 5:37

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.