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
philanthropyphilanthropy 

apex basic syntax question

What is the difference between the following:

List<Movie__c> movieList {get; set;}

List<Movie__c> movieList = new List<Movie__c>{};

 I'm assuming the second will need getter and setter defined? I'm trying to learn when the new keyword is necessary and when it isn't.

 

Thanks!

AmitSahuAmitSahu

List<Movie__c> movieList {get; set;}

 

The above line is written if you want the movieList variable in the Apex class to be referred in the visual force page. You will do it by {!movieList}. If you don't use getter and setter you wont be able to use it in VF page.

 

List<Movie__c> movieList = new List<Movie__c>{};

 

The above line is creating a fresh list of Movie__c as the new keyword will define the list as a fresh copy.

 

So for the first one the new keyword is not required and the secord case this is required as you are creating a fresh copy of the list Movie__c.

philanthropyphilanthropy

Ok thanks for the reply, though I'm still a little confused.

 

Don't they both create a new list movieList?

AmitSahuAmitSahu

Yes both of them will create new list.

Chamil MadusankaChamil Madusanka

Hi,

 

Adding to previous post.

 

change the following code

 

List<Movie__c> movieList {get; set;}

 to

 

public List<Movie__c> movieList {get; set;}

 Otherwise it will not be worked.

 

If a reply to a post answers your question or resolves your problem, please mark it as the solution to the post so that others may benefit.

 

ShikibuShikibu

j020 wrote:

Yes both of them will create new list.


Not true! The property version (below) does not create a new list. It creates a variable, which has the type of a list, but its value is null.

 

List<Movie__c> movieList {get; set;}

 See this blog entry which compares properties to getters and setters.