In this article, we will understand how to initialize a list. A list is an ordered collection that allows us to store and access elements sequentially. It contains the index-based methods to insert, update, delete and search the elements. It can also have the duplicate elements.
Below is a demonstration of the same −
Suppose our input is −
Run the program
The desired output would be −
Initializing an integer list The elements of the integer list are: [25, 60] Initializing a string list The elements of the string list are: [Java, Program]
Algorithm
Step 1 - START Step 2 - Declare an integer list namely integer_list and a string list namely string_list Step 3 - Define the values. Step 4 - Use the List<Integer> integer_list = new ArrayList<Integer>() to initialize the integer list. Step 5 - Use List<String> string_list = new ArrayList<String>() to initialize the integer list. Step 6 - Use the function .add() to add items to the list. Step 7 - Display the result Step 8 - Stop
Example 1
Here, we bind all the operations together under the ‘main’ function.
import java.util.*;
public class Demo {
public static void main(String args[]) {
System.out.println("Required packages have been imported");
System.out.println("\nInitializing an integer list");
List<Integer> integer_list = new ArrayList<Integer>();
integer_list.add(25);
integer_list.add(60);
System.out.println("The elements of the integer list are: " + integer_list.toString());
System.out.println("\nInitializing a string list");
List<String> string_list = new ArrayList<String>();
string_list.add("Java");
string_list.add("Program");
System.out.println("The elements of the string list are: " + string_list.toString());
}
}Output
Required packages have been imported Initializing an integer list The elements of the integer list are: [25, 60] Initializing a string list The elements of the string list are: [Java, Program]
Example 2
Here, we encapsulate the operations into functions exhibiting object-oriented programming.
import java.util.*;
public class Demo {
static void initialize_int_list(){
List<Integer> integer_list = new ArrayList<Integer>();
integer_list.add(25);
integer_list.add(60);
System.out.println("The elements of the integer list are: " + integer_list.toString());
}
static void initialize_string_list(){
List<String> string_list = new ArrayList<String>();
string_list.add("Java");
string_list.add("Program");
System.out.println("The elements of the string list are: " + string_list.toString());
}
public static void main(String args[]) {
System.out.println("Required packages have been imported");
System.out.println("\nInitializing an integer list");
initialize_int_list();
System.out.println("\nInitializing a string list");
initialize_string_list();
}
}Output
Required packages have been imported Initializing an integer list The elements of the integer list are: [25, 60] Initializing a string list The elements of the string list are: [Java, Program]