Initialize a mutable list of strings example
To create a mutable list of strings in Java and add its required values, proceed as following:
- Import the util.List and util.ArrayList modules.
- Create a list Array.
- Use the ArrayList add method, to add the required values into your list Array.
- Optionally, print or manipulate elements (either add, remove, update, set) of your mutable list.
Here is the code to define a Java list of strings:
//import modules
import java.util.List;
import java.util.ArrayList;
public class CreateListOfStr {
public static void main(String[] args) {
// create list of strings
List<String> myStringList = new ArrayList<>();
// add string objects to the list
myStringList.add("Java");
myStringList.add("JavaScript");
myStringList.add("Python");
myStringList.add("Go");
// print the list elements
for (String myStr : myStringList) {
System.out.println(myStr);
}
}
}
Create an immutable string array
In case that you would like to create a read only copy of your list, which you can’t change, but can retrieve for read only purposes, use the code below. Note that you will need to import the Collection module into your environment to create your read only array.
To define your immutable array proceed as following:
- Imnport the util.List, ArrayList and Collections modules.
- Define a mutable array and add the relevant elements.
- Use the Collections module to define an immutable list.
//import modules
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
public class CreateReadOnlyListOfStr {
public static void main(String[] args) {
// create list of strings
List<String> myStringList = new ArrayList<>();
// add string objects to the list
myStringList.add("Java");
myStringList.add("JavaScript");
myStringList.add("Python");
myStringList.add("Go");
//create a read only view
List<String> myImmutableList = Collections.unmodifiableList(myStringList);
// print the immutable list elements
for (String myStr : myImmutableList) {
System.out.println(myStr);
}
}
}