如何使用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 周岁祝福语学生文案简短
13 订婚领证祝福语简短精辟
14 导师获奖祝福语大全简短
15 新婚购房祝福语简短精辟
16 牛年祝福语简短的爱人
17 送芒果的祝福语简短
18 送给学长毕业祝福语简短