如何使用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
热门推荐
10 宝宝周岁可乐祝福语简短
11 离职横幅升职祝福语简短
12 妈妈祝福语简短16字
13 虎年开新车祝福语简短
14 怎么说祝福语简短
15 提早庆祝生日祝福语简短
16 祝妹妹毕业祝福语简短
17 炸鸡拼盘生日祝福语简短
18 简短祝福语大全暖心