欢迎访问宙启技术站
智能推送

如何在Java中对数组进行去重操作?

发布时间:2023-11-19 06:35:40

在Java中,对数组进行去重操作有多种方法。下面将介绍两种常见的解决方案。

解决方案一:使用Set集合进行去重。

1. 创建一个Set集合对象,例如HashSet。

2. 遍历数组,将数组中的元素逐一添加到Set集合中。

3. 遍历结束后,Set集合中的元素即为去重后的数组元素。

4. 将Set集合转换为数组。

5. 返回去重后的数组。

示例代码如下:

import java.util.HashSet;
import java.util.Set;

public class ArrayDeduplication {
    public static int[] deduplicate(int[] array) {
        Set<Integer> set = new HashSet<>();
        for (int i : array) {
            set.add(i);
        }
        int[] deduplicatedArray = new int[set.size()];
        int index = 0;
        for (int i : set) {
            deduplicatedArray[index] = i;
            index++;
        }
        return deduplicatedArray;
    }

    public static void main(String[] args) {
        int[] array = {1, 2, 2, 3, 4, 4, 5};
        int[] deduplicatedArray = deduplicate(array);
        for (int i : deduplicatedArray) {
            System.out.println(i);
        }
    }
}

输出结果为:

1
2
3
4
5

解决方案二:使用双重循环进行去重。

1. 遍历数组,对每一个元素进行判断。

2. 如果该元素 次出现,则将其加入到一个新的数组中。

3. 如果该元素已经出现过,则跳过该元素。

4. 遍历结束后,新的数组中的元素即为去重后的数组元素。

5. 返回去重后的数组。

示例代码如下:

public class ArrayDeduplication {
    public static int[] deduplicate(int[] array) {
        int len = array.length;
        int[] deduplicatedArray = new int[len];
        int count = 0;
        for (int i = 0; i < len; i++) {
            boolean isDuplicate = false;
            for (int j = 0; j < i; j++) {
                if (array[i] == array[j]) {
                    isDuplicate = true;
                    break;
                }
            }
            if (!isDuplicate) {
                deduplicatedArray[count++] = array[i];
            }
        }
        int[] result = new int[count];
        System.arraycopy(deduplicatedArray, 0, result, 0, count);
        return result;
    }

    public static void main(String[] args) {
        int[] array = {1, 2, 2, 3, 4, 4, 5};
        int[] deduplicatedArray = deduplicate(array);
        for (int i : deduplicatedArray) {
            System.out.println(i);
        }
    }
}

输出结果为:

1
2
3
4
5

以上是两种常用的对Java数组进行去重的方法,可以根据不同的需求选择适合的方法进行使用。