如何使用 java 在陣列中計算唯一元素?


Set 介面不允許重複元素,因此建立 set 物件並嘗試將每個元素使用 add() 方法新增到其中,如果遇到重複的元素,此方法將返回 false −

如果你嘗試將陣列的所有元素新增到 Set 中,它只會接受唯一元素 −

示例

import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class CountingUniqueElements {
   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 count = 0;
      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));
      System.out.println("indices of duplicate elements in the array are elements :: ");
      Set set = new HashSet();

      for(int i = 0; i<myArray.length; i++) {
         if(set.add(myArray[i])) {
            count++;
            System.out.println("Index :: "+i+" Element :: "+myArray[i]);
         }
      }
   }
}

輸出

Enter the size of the array that is to be created ::
6
Enter the elements of the array ::
45
45
45
69
32
69
The array created is :: [45, 45, 45, 69, 32, 69]
indices of duplicate elements in the array are elements ::
Index :: 0 Element :: 45
Index :: 3 Element :: 69
Index :: 4 Element :: 32

更新於: 30-Jul-2019

859 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.