이 기사에서는 목록을 초기화하는 방법을 이해할 것입니다. 목록은 요소를 순차적으로 저장하고 액세스할 수 있도록 하는 정렬된 컬렉션입니다. 여기에는 요소를 삽입, 업데이트, 삭제 및 검색하는 인덱스 기반 메서드가 포함되어 있습니다. 중복 요소를 가질 수도 있습니다.
아래는 동일한 데모입니다 -
입력이 다음과 같다고 가정 -
Run the program
원하는 출력은 -
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]
알고리즘
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
예시 1
여기에서 모든 작업을 'main' 기능 아래에 묶습니다.
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());
}
} 출력
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]
예시 2
여기에서 객체 지향 프로그래밍을 나타내는 함수로 작업을 캡슐화합니다.
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();
}
} 출력
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]