Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

โปรแกรม Java เพื่อหมุนองค์ประกอบของรายการ


ในบทความนี้ เราจะเข้าใจวิธีการหมุนเวียนองค์ประกอบของรายการ Listextends Collection และประกาศพฤติกรรมของคอลเล็กชันที่เก็บลำดับขององค์ประกอบ คอลเล็กชันเป็นเฟรมเวิร์กที่จัดเตรียมสถาปัตยกรรมในการจัดเก็บและจัดการกลุ่มของอ็อบเจ็กต์ Java Collections สามารถบรรลุการดำเนินการทั้งหมดที่คุณดำเนินการกับข้อมูล เช่น การค้นหา การเรียงลำดับ การแทรก การจัดการ และการลบ

ด้านล่างนี้เป็นการสาธิตสิ่งเดียวกัน -

สมมติว่าข้อมูลที่เราป้อนคือ

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

ที่นี่ เราเชื่อมโยงการดำเนินการทั้งหมดเข้าด้วยกันภายใต้ฟังก์ชัน 'หลัก'

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]