Creating a List using ‘List.of()’ :
This method was introduced in java 9 as part of the java collection framework enhancements.
The “List.of()’ method can be used to create a list with up to 10 elements.
Steps to how to create a list using List.of() method in java
Step-1:
Import the List class:
import java.util.List;
Step-2:
call the List.of() Method:
we use the ‘List.of()’ method to create a list.This method takes a variable number of arguments representing the elements of the list.we can pass the elements directly into the method call.
List<Type> listName=List.of(element1,element2,.....elementN);
Step-3:
once created you can use the list or various operations such as accessing elements, iterating over tremor passing them to other methods.
Example:
import java.util.List; public class SimpleListExample{ public class void main(String[] args){ List<String> fruits=List.of("cherry","orange"); System.out.println("My List:"+mylist); } }
output:
fruits list:[cherry,orange]
In this Example:
1.We import the ‘List’ class from the ‘java.util’ package.
2.We create a list of strings named ‘fruits’ using ‘List.of(“cherry”,”orange”)’
3.We print the list to the console using ‘System.out.println’
characteristics of the List created by ‘List.of()’ method:
- Immutability
- null elements
- performance
Summary
- The ‘List.of()’ method provides an easy way to create immutable lists with a fixed set of elements.
- List created with ‘list.of()’ are immutable and do not allow null elements.
- these lists are efficient and optimised for read-only operations.
Notes:
1.The elements passed to ‘List.of()’ are used to initialise the list.
2.The resulting list is immutable, meaning its size and elements cannot be modified after creation.
3.If you try to add, remove,or change elements in the list after creation it will result in an ‘UnsupportedoperationException’.