如何移除 Java 陣列中重複的元素?


要檢測陣列中的重複值,需要將陣列的每個元素與其餘所有元素比較,如果匹配的話,則得到重複元素。

一種解決方案是使用兩個迴圈(巢狀),其中內迴圈從 i+1 開始(其中 i 是外迴圈的變數)以避免重複。

Apache Commons 提供了一個名為 org.apache.commons.lang3 的庫,以下是向專案新增庫的 Maven 依賴項。

<dependencies>
   <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-lang3</artifactId>
      <version>3.0</version>
   </dependency>
</dependencies>

此軟體包提供了一個名為 ArrayUtils 的類,使用此類的 remove() 方法可以刪除給定陣列中檢測到的重複元素。

示例

import java.util.Arrays;
import java.util.Scanner;
import org.apache.commons.lang3.ArrayUtils;
public class DeleteDuplicate {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the size of the array that is to be created::");
      int size = sc.nextInt();
      int[] myArray = new int[size];
      System.out.println("Enter the elements of the array ::");
      for(int i=0; i<size; i++) {
         myArray[i] = sc.nextInt();
      }
      System.out.println("The array created is ::"+Arrays.toString(myArray));
      for(int i=0; i<myArray.length-1; i++) {
         for (int j=i+1; j<myArray.length; j++) {
            if(myArray[i] == myArray[j]) {
               myArray = ArrayUtils.remove(myArray, j);
            }
         }
      }
      System.out.println("Array after removing elements ::"+Arrays.toString(myArray));
   }
}

輸出

Enter the size of the array that is to be created ::
6
Enter the elements of the array ::
232
232
65
47
89
42
The array created is :: [232, 232, 65, 47, 89, 42]
Array after removing elements :: [232, 65, 47, 89, 42]

更新於: 30-Jul-2019

3K+ 次瀏覽

啟動你的 職業生涯

完成課程即可獲得認證

開始學習
廣告
© . All rights reserved.