Java数组去重的方法有:使用HashSet去除重复元素;使用Arrays.sort()和双指针跳过重复元素;使用for循环和Set存储并添加不重复元素。

Java中使用数组去重
数组去重是指删除数组中重复的元素,只保留唯一的元素。在 Java 中,可以使用以下方法实现数组去重:
1. 使用 HashSet
HashSet 是 Java 提供的集合类,它可以自动去除重复元素。我们可以将数组元素添加到 HashSet 中,然后将 HashSet 转换为数组即可得到不重复的元素。
立即学习“Java免费学习笔记(深入)”;
<code class="java">int[] arr = {1, 2, 3, 4, 5, 1, 2, 3};
// 创建 HashSet 并将数组元素添加到其中
Set<Integer> set = new HashSet<>();
for (int num : arr) {
set.add(num);
}
// 将 HashSet 转换为数组
int[] newArr = new int[set.size()];
int index = 0;
for (int num : set) {
newArr[index++] = num;
}</code>2. 使用 Arrays.sort() 和双指针
Arrays.sort() 方法可以对数组进行排序。对数组排序后,我们可以使用双指针遍历数组,跳过重复元素。
<code class="java">int[] arr = {1, 2, 3, 4, 5, 1, 2, 3};
// 对数组排序
Arrays.sort(arr);
// 使用双指针跳过重复元素
int[] newArr = new int[arr.length];
int slow = 0, fast = 0;
while (fast < arr.length) {
if (arr[slow] != arr[fast]) {
newArr[slow++] = arr[fast];
}
fast++;
}
// 调整数组长度
newArr = Arrays.copyOf(newArr, slow);</code>3. 使用 for 循环和 Set
我们可以使用 for 循环遍历数组,并使用 Set 来存储遇到的元素。如果Set中不包含该元素,则将其添加到 Set 和结果数组中。
<code class="java">int[] arr = {1, 2, 3, 4, 5, 1, 2, 3};
// 创建 Set 并初始化结果数组
Set<Integer> set = new HashSet<>();
int[] newArr = new int[arr.length];
int index = 0;
// 遍历数组并添加到 Set 中
for (int num : arr) {
if (!set.contains(num)) {
set.add(num);
newArr[index++] = num;
}
}
// 调整数组长度
newArr = Arrays.copyOf(newArr, index);</code>以上就是java怎么用数组去重的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号