Computer >> 컴퓨터 >  >> 프로그램 작성 >> Java

다양한 유형의 컬렉션을 사용하는 Java 프로그램

<시간/>

이 기사에서는 다양한 유형의 컬렉션을 사용하는 방법을 이해할 것입니다.

아래는 동일한 데모입니다 -

입력이 다음과 같다고 가정 -

Input list: [101, 102, 103, 104, 105]

원하는 출력은 -

The list after removing an element:
101 102 103 105

알고리즘

Step 1 - START
Step 2 - Declare a list namely input_collection.
Step 3 - Define the values.
Step 4 - Using the function remove(), we send the index value of the element as parameter, we remove the specific element.
Step 5 - Display the result
Step 6 - Stop

예시 1

여기서는 ArrayList의 사용을 보여줍니다. 배열 목록은 초기 크기로 생성됩니다. 이 크기를 초과하면 컬렉션이 자동으로 확대됩니다. 개체가 제거되면 배열이 축소될 수 있습니다.

import java.util.*;
public class Demo {
   public static void main(String[] args){
      ArrayList<Integer> input_collection = new ArrayList<Integer>();
      for (int i = 1; i <= 5; i++)
      input_collection.add(i + 100);
      System.out.println("The list is defined as: " +input_collection);
      input_collection.remove(3);
      System.out.println("\nThe list after removing an element: ");
      for (int i = 0; i < input_collection.size(); i++)
      System.out.print(input_collection.get(i) + " ");
   }
}

출력

The list is defined as: [101, 102, 103, 104, 105]

The list after removing an element:
101 102 103 105

예시 2

여기에서는 연결 리스트를 사용하는 방법을 보여줍니다. java.util.LinkedList 클래스 작업은 이중 연결 목록에서 기대할 수 있는 작업을 수행합니다. 목록에 대한 색인을 생성하는 작업은 시작 또는 끝 중 지정된 색인에 더 가까운 것부터 목록을 순회합니다.

import java.util.*;
public class Demo {
   public static void main(String[] args){
      LinkedList<Integer> input_collection = new LinkedList<Integer>();
      for (int i = 1; i <= 5; i++)
      input_collection.add(i + 100);
      System.out.println("The list is defined as: " +input_collection);
      input_collection.remove(3);
      System.out.println("\nThe list after removing an element");
      for (int i = 0; i < input_collection.size(); i++)
      System.out.print(input_collection.get(i) + " ");
   }
}

출력

The list is defined as: [101, 102, 103, 104, 105]

The list after removing an element
101 102 103 105