jagmohan's answer is right, but doesn't tell you how to fix it. List.contains() uses the equals() method of the items in the list to test whether or not it has found the item it is looking for. If you don't provide your own implementation of equals(), then you get a test for whether or not they are the same instance not whether or not their data is equal. So, add your own implementation like this:

public class SelectOption {
    public SelectOption(String value, String label, Boolean selected) {
        this.value = value;
        this.label = label;
        this.disabled = false;
        this.escapeItem = false;
        this.selected = selected;
    }

    @AuraEnabled
    public String label { get;set; }
    @AuraEnabled
    public String value { get;set; }
    @AuraEnabled
    public Boolean disabled { get;set; }
    @AuraEnabled
    public Boolean escapeItem { get;set; }
    @AuraEnabled
    public Boolean selected { get;set;}

    public Boolean equals(Object obj) {
        if (obj != null && obj instanceof SelectOption) {
            SelectOption otherSelectOption = (SelectOption) obj;
            return value == otherSelectOption.value
                    && label == otherSelectOption.label
                    && disabled == otherSelectOption.disabled
                    && escapeItem == otherSelectOption.escapeItem
                    && selected == otherSelectOption.selected;
        } else {
            return false;
        }
    }
    public override Integer hashCode() {
        return (value + label + disabled + escapeItem + selected).hashCode();
    }

}

Then your assertions come out correct.

Note: I've added an implementation of hashCode() as well, as suggested by Keith C. If you override one of hashCode() and equals(), you really need to override both, or you'll get unpredictable behaviour if your object is used in a Map or Set. Is it a good implementation of hashCode()? Well, it does the job. But, how to write an effective implementation of hashCode() is actually a pretty complicated question in itself.

See also:

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_collections_maps_keys_userdefined.htm

Answer from Aidan on Stack Exchange
🌐
CRS Info Solutions
crsinfosolutions.com › home › list class in salesforce apex
List Class in Salesforce Apex
Salesforce Training - In Apex, the List class is a collection type that represents a dynamically-sized array. It is part of the Salesforce Apex Collection framework and provides methods to manipulate lists of objects I have enrolled for Salesforce Admin and development online course at CRS info solutions. It’s really the best training i have ever taken and syllabus is highly professional
Rating: 5 ​
People also ask

What are List methods in Apex?
There are multiplelist methods in Apex such as, contains(), sort(), isEmpty(), indexOf(), equals(), add(), remove(), get(), and more.
🌐
s2-labs.com
s2-labs.com › home › lists in apex
Lists in Apex | Salesforce Developer Tutorials
When should you use List in Apex?
In Apex, a list should be used to store an ordered collection of elements that allows duplicates, and you want to navigate records in sequence.
🌐
s2-labs.com
s2-labs.com › home › lists in apex
Lists in Apex | Salesforce Developer Tutorials
What are the properties of List in Apex?
The two properties of List in Apex are: 1. They store data in sequential order. 2. They allow duplicacy or non-unique values.
🌐
s2-labs.com
s2-labs.com › home › lists in apex
Lists in Apex | Salesforce Developer Tutorials
🌐
Decodeforce
decodeforce.com › blogs › apex-list-methods-and-examples
Salesforce apex list class and methods with practice examples
List is one of the collections in apex. A list is an ordered collection of elements, where each element can be accessed by its index. Apex lists class provides a number of methods to handle groups of records in salesforce.
🌐
Salesforce Developers
developer.salesforce.com › docs › atlas.en-us.apexcode.meta › apexcode › langCon_apex_collections_lists.htm
Lists | Apex Developer Guide | Salesforce Developers
A list is an ordered collection of elements that are distinguished by their indices. List elements can be of any data type—primitive types, collections, sObjects, user-defined types, and built-in Apex types.
🌐
S2 Labs
s2-labs.com › home › lists in apex
Lists in Apex | Salesforce Developer Tutorials
April 27, 2026 - A list in Apex is an ordered collection of elements used to store data in sequence.
🌐
JanBask Training
janbasktraining.com › home › how to create list in salesforce and set methods: to ensure a bright career
How to Create List in Salesforce and Set Methods: To Ensure A Bright Career
July 9, 2024 - List(setToCopy): Creates a new instance of the List class by copying the elements from the specified Set. T is the data type of the elements in the Set and List and can be any data type. Here are quick details of Apex List methods in Salesforce, all of which are instance methods.
🌐
C# Corner
c-sharpcorner.com › home › technologies › salesforce › apex list in salesforce
Apex List In SalesForce
September 11, 2019 - The prerequisites for testing Apex Lists in SalesForce as, Register a Salesforce Free Trial account using the following link. ... Log into your SalesForce account and click the Developer Console. ... After creating Apex class ApexList, add a Listtest method for creating and testing the List and its methods.
Find elsewhere
🌐
Salesforcetrainingindia
salesforcetrainingindia.com › home › list class in salesforce apex
List Class in Salesforce Apex
October 1, 2024 - The List class in Salesforce Apex is a collection type that represents an ordered collection of elements. Lists are dynamic in nature, meaning their size can grow or shrink as needed.
Top answer
1 of 2
3

jagmohan's answer is right, but doesn't tell you how to fix it. List.contains() uses the equals() method of the items in the list to test whether or not it has found the item it is looking for. If you don't provide your own implementation of equals(), then you get a test for whether or not they are the same instance not whether or not their data is equal. So, add your own implementation like this:

public class SelectOption {
    public SelectOption(String value, String label, Boolean selected) {
        this.value = value;
        this.label = label;
        this.disabled = false;
        this.escapeItem = false;
        this.selected = selected;
    }

    @AuraEnabled
    public String label { get;set; }
    @AuraEnabled
    public String value { get;set; }
    @AuraEnabled
    public Boolean disabled { get;set; }
    @AuraEnabled
    public Boolean escapeItem { get;set; }
    @AuraEnabled
    public Boolean selected { get;set;}

    public Boolean equals(Object obj) {
        if (obj != null && obj instanceof SelectOption) {
            SelectOption otherSelectOption = (SelectOption) obj;
            return value == otherSelectOption.value
                    && label == otherSelectOption.label
                    && disabled == otherSelectOption.disabled
                    && escapeItem == otherSelectOption.escapeItem
                    && selected == otherSelectOption.selected;
        } else {
            return false;
        }
    }
    public override Integer hashCode() {
        return (value + label + disabled + escapeItem + selected).hashCode();
    }

}

Then your assertions come out correct.

Note: I've added an implementation of hashCode() as well, as suggested by Keith C. If you override one of hashCode() and equals(), you really need to override both, or you'll get unpredictable behaviour if your object is used in a Map or Set. Is it a good implementation of hashCode()? Well, it does the job. But, how to write an effective implementation of hashCode() is actually a pretty complicated question in itself.

See also:

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_collections_maps_keys_userdefined.htm

2 of 2
1

The following two statements create two objects

SelectOption alaska1 = new SelectOption('Alaska', 'Alaska', false);
SelectOption alaska2 = new SelectOption('Alaska', 'Alaska', false);

These objects are added to states list along with california object. There are 3 objects in the states list.

On this line, contains method checks if noDupStates list contains the reference which so variable is holding.

Boolean stateNotInList = !noDupStates.contains(so);

Both alaska1 and alaska2 are referring to different objects and contains method compares their references only, not the values contained in the properties of the objects.

That's why noDupStates list also ends up with 3 SelectOption objects and the assertion fails. The debug statement also shows there are 3 objects in noDupStates list.

🌐
LinkedIn
linkedin.com › pulse › list-methods-apex-amit-khandelwal
List Methods in APEX
December 22, 2021 - Creating a List; Initializing the list (Creates a new instance of the List class. A list can hold elements of any data type Integer); Adding to Integer values to the list.
🌐
Cloud Prism
cloud-prism.com › home › apex beginner › lists in apex
Lists in Apex | Cloud Prism
December 12, 2023 - As discussed in the “Variables in Apex” article, we’ve declared a variable with the List type and then initialized the variable with the new List(); value. Therefore, list is just a data type like Contact or Person! It has all the attributes of a data type: You can create new variables of this type, you use the new keyword and the class has methods.
🌐
Greytrix
greytrix.com › blogs › salesforce › 2023 › 01 › 18 › get-list-of-apex-class-by-using-apextypeimplementor
Get list of apex class by using apextypeimplementor
June 5, 2024 - system.debug([SELECT Id, InterfaceNamespacePrefix, InterfaceName, InterfaceApexClassId, IsConcrete, ClassNamespacePrefix, ClassName, ApexClassId, DurableId FROM ApexTypeImplementor where InterfaceName='Implementation Class Name']) Similarly, for example:- If you want to get the List of Schedulable Apex Class then the below-mentioned code snippet can be used to get all the Schedulable Apex classes present in the org.
🌐
S2 Labs
s2-labs.com › home › lists initialization in apex
Lists Initialization in APEX | Salesforce Developer Tutorials
April 27, 2026 - List initialization in Apex Salesforce is a way to declare List variables and create instances using the ‘new’ keyword.
🌐
Code With Sally
codewithsally.com › home › blog archive › beginner’s guide to salesforce apex: an introduction to collections – lists, sets, and maps
Beginner’s Guide to Salesforce Apex: An Introduction to Collections - Lists, Sets, and Maps
March 20, 2024 - An Apex List is a collection of multiple items, much like a to-do list where you can add new tasks, remove completed ones, and prioritize the order in which you want to complete them.
🌐
Forcetalks
forcetalks.com › home › salesforce® discussions › what is list class in salesforce?
What is List Class in Salesforce? - Forcetalks
August 2, 2018 - List Class is a collection type class in Salesforce, which contains all the list method and constructors.
Top answer
1 of 5
11

You can't instantiate a List like that using an integer. You don't need to explicitly specify how much items are going into the list when it is created. Instead, just remove the integer:

//Instantiate the list
String[] myArray = new List<String>();

You're logic in your loop seems to be incorrect as well. Specifically, myArray's size will always be 0 when you instantiate it. Change your loop logic to:

for(Integer i=0;i<length;i++) {
   // code
}

You want to generate a List of strings based on the i variable. You will want to change your internal logic to:

//Populate the array
myArray.add('Test ' + i);

// Write value to the debug log
System.debug(myArray[i]);

Finally, you want to return that Array. You need to change your method so the return type is no longer void by changing its signature:

public static String[] generateStringArray(Integer length)

then it is just a matter of returning that array at the end of your method:

return myArray;

This would bring it all together as:

public class StringArrayTest {
    //Public Method
    public static String[] generateStringArray(Integer length) {
        //Instantiate the list
        String[] myArray = new List<String>();

        //Iterate throught the list
        for(Integer i=0;i<length;i++) {
            //Populate the array
            myArray.add('Test ' + i);

            // Write value to the debug log
            System.debug(myArray[i]);
        } //end loop

        return myArray;
    }//end method       
}// end class

Some more info on Arrays and Lists, Loops, and Class methods for future reference.

2 of 5
4

Problem is on the following line

String[] myArray = new List<String>(length);

Lists in Apex do not have constructor for creating lists of predefined length (see doc). This should solve the problem:

String[] myArray = new List<String>();

P.S. to satisfy your requirements, you will also have to change for-loop condition like this:

for(Integer i=0;i<length;i++) {
🌐
TutorialsPoint
tutorialspoint.com › apex › apex_collections.htm
Apex - Collections
List can contain any number of records of primitive, collections, sObjects, user defined and built in Apex type. This is one of the most important type of collection and also, it has some system methods which have been tailored specifically ...
🌐
Codingwiththeforce
codingwiththeforce.com › home › course catalog › the apex master class › what are lists in apex? (apex master class ep. 17)
What Are Lists in Apex? (Apex Master Class Ep. 17) – Coding With The Force
Both forms work. The square bracket version is less typing and reads fine, so most people use it. Ask for a position that doesn’t exist and you get List index out of bounds, which is Apex’s way of saying “there is nothing there, what are you doing.”
Published: August 10, 2026
🌐
Stack Overflow
stackoverflow.com › questions › 26801180 › how-to-define-and-print-a-list-in-apex-class
salesforce - how to define and print a list in apex class - Stack Overflow
public class listpgm { list <integer>Teacher__c =new list(); } ... Save this answer. ... Show activity on this post. ... List<Account> accs = new List<Account>();//Creating a List for Account Object. ... List<ObjectName__c> Cust_Object = new List<ObjectName__c>();//Creating a List for Custom Object. It depends how you want to display the list in User Interface.You can bind List to <apex:repeat>,<apex:Pageblocktable>,<apex:datatable>...and you can bind list to <apex:SelectList>.