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

목록의 요소를 회전하는 Java 프로그램

<시간/>

이 기사에서는 목록의 요소를 회전하는 방법을 이해합니다. 목록은 컬렉션을 확장하고 요소 시퀀스를 저장하는 컬렉션의 동작을 선언합니다. 컬렉션은 개체 그룹을 저장하고 조작하기 위한 아키텍처를 제공하는 프레임워크입니다. Java 컬렉션은 검색, 정렬, 삽입, 조작 및 삭제와 같은 데이터에 대해 수행하는 모든 작업을 수행할 수 있습니다.

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

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

Input list: [100, 150, 200, 250, 300]

원하는 출력은 -

The list after one rotation: [150, 200, 250, 300, 100]

알고리즘

Step 1 - START
Step 2 - Declare a list namely input_list
Step 3 - Define the values.
Step 4 - Iterate through the list, and use the ‘get’ method to get the element at a specific index.
Step 5 - Assign this variable to a new variable ‘temp’.
Step 6 - Iterate through the list from the end, and fetch the element at a specific index. Use the ‘set’ method to set the value at ‘temp’.
Step 7 - Display the result
Step 8 - Stop

예시 1

여기에서 모든 작업을 'main' 기능 아래에 묶습니다.

import java.util.*;
public class Demo {
   public static void main(String[] args){
      List<Integer> input_list = new ArrayList<>();
      input_list.add(100);
      input_list.add(150);
      input_list.add(200);
      input_list.add(250);
      input_list.add(300);
      System.out.println("The list is defined as: " + Arrays.toString(input_list.toArray()));
      for (int i = 0; i < 4; i++) {
         int temp = input_list.get(4);
         for (int j = 4; j > 0; j--) {
            input_list.set(j, input_list.get(j - 1));
         }
         input_list.set(0, temp);
      }
      System.out.println( "The list after one rotation: " +          Arrays.toString(input_list.toArray()));
   }
}

출력

The list is defined as: [100, 150, 200, 250, 300]
The list after one rotation: [150, 200, 250, 300, 100]

예시 2

여기에서 객체 지향 프로그래밍을 나타내는 함수로 작업을 캡슐화합니다.

import java.util.*;
public class Demo {
   static void rotate(List<Integer> input_list){
      for (int i = 0; i < 4; i++) {
      int temp = input_list.get(4);
      for (int j = 4; j > 0; j--) {
         input_list.set(j, input_list.get(j - 1));
      }
      input_list.set(0, temp);
   }
   System.out.println("\nThe list after one rotation: " +    Arrays.toString(input_list.toArray()));
   }
   public static void main(String[] args){
      List<Integer> input_list = new ArrayList<>();
      input_list.add(100);
      input_list.add(150);
      input_list.add(200);
      input_list.add(250);
      input_list.add(300);
      System.out.println("The list is defined as: " + Arrays.toString(input_list.toArray()));
      rotate(input_list);
   }
}

출력

The list is defined as: [100, 150, 200, 250, 300]
The list after one rotation: [150, 200, 250, 300, 100]