使用 HashSet 存储数组元素,检查是否存在指定元素;使用 HashMap 存储元素及其出现的次数,检查是否存在指定键。

查找数组中出现的数字是 Java 中一个常见的任务。可以使用以下步骤来实现:
HashSet 是一种数据结构,它可以存储唯一元素。我们可以使用 HashSet 来存储数组中的元素,然后检查 HashSet 中是否存在某个元素。
<code class="java">import java.util.HashSet;
public class FindUniqueNumbers {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 2, 3};
// 创建 HashSet 来存储唯一元素
HashSet<Integer> uniqueNumbers = new HashSet<>();
// 遍历数组并向 HashSet 中添加元素
for (int num : arr) {
uniqueNumbers.add(num);
}
// 打印 HashSet 中的唯一元素
System.out.println(uniqueNumbers);
}
}</code>HashMap 是一种数据结构,它可以存储键值对。我们可以使用 HashMap 来存储数组中的元素及其出现的次数。通过检查 HashMap 中是否存在某个键,我们可以确定该元素是否在数组中出现过。
<code class="java">import java.util.HashMap;
public class FindUniqueNumbers {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 2, 3};
// 创建 HashMap 来存储元素及其出现的次数
HashMap<Integer, Integer> uniqueNumbers = new HashMap<>();
// 遍历数组并更新 HashMap 中的计数
for (int num : arr) {
if (uniqueNumbers.containsKey(num)) {
uniqueNumbers.put(num, uniqueNumbers.get(num) + 1);
} else {
uniqueNumbers.put(num, 1);
}
}
// 打印 HashMap 中的唯一元素
System.out.println(uniqueNumbers.keySet());
}
}</code>以上就是java求数组出现了哪些数字的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号