如何使用 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
广告
数据结构
网络技术
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程语言
C++
C#
MongoDB
MySQL
JavaScript
PHP