如何使用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输出结果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