An alternative way to declare a List in Apex is with the array notation, an opening and closing square bracket, []
.
Lists declared this way behave no differently than what we've seen so far in this course. All the same methods are still available and work the same way. Some folks prefer this syntax because they think it's more concise and less laborious to type out.
Instead of using the List
keyword:
List<Integer> numbers = new List<Integer> {1, 2, 3};
we can use the array notation:
Integer[] numbers = new Integer[] {1, 2, 3};
The method we've learned so far still work the same:
Integer[] numbers = new Integer[] {1, 2, 3}; Integer listSize = numbers.size(); // 3
To declare an empty list using the array notation, simply keep the {}
empty.
Integer[] numbers = new Integer[] {};
Compare that to the syntax for the List
keyword:
List<Integer> numbers = new List<Integer>();
Okay, I lied. There is one thing you can't do with the array notation. You can't initialize a list with another list:
List<Integer> firstList = new List<Integer>{1,2,3}; Integer[] secondList = new Integer[] {firstList}; // Initial expression is of incorrect type, expected: Integer but was: List<Integer>
If you need to do this, you'll need to initialize using the list syntax, but you don't necessarily need to declare using the list syntax. This is valid syntax:
List<Integer> firstList = new List<Integer>{1,2,3}; Integer[] secondList = new List<Integer>(firstList);
Personally, I'd keep it consistent. But the options there if you need it.