Java删除数组中重复元素

x33g5p2x  于2022-10-06 转载在 Java  
字(1.2k)|赞(0)|评价(0)|浏览(730)

在这篇文章中,我们将写一个Java程序来删除数组中重复的整数元素。

我们有很多方法可以编写逻辑来删除数组中重复的整数元素。

  • 使用临时数组
  • 使用HashSet

###使用临时数组

要从一个数组中删除重复的元素,数组必须是按排序的顺序排列。如果一个数组没有被排序,你可以通过调用Arrays.sort(arr)方法进行排序。

  1. import java.util.Arrays;
  2. public class DuplicateFromArray {
  3. public static void main(final String[] args) {
  4. final int[] a = { 10, 20, 30, 40, 50, 50, 10, 20 };
  5. Arrays.sort(a);// sorting array
  6. removeDuplicate(a);
  7. }
  8. private static void removeDuplicate(final int[] a) {
  9. final int[] temp = new int[a.length];
  10. int j = 0;
  11. for (int i = 0; i < a.length - 1; i++) {
  12. if (a[i] != a[i + 1]) {
  13. temp[j++] = a[i];
  14. }
  15. }
  16. temp[j++] = a[a.length - 1];
  17. for (int i = 0; i < j; i++) {
  18. a[i] = temp[i];
  19. }
  20. for (int i = 0; i < j; i++) {
  21. System.out.println(temp[i]);
  22. }
  23. }
  24. }

输出:

  1. 10
  2. 20
  3. 30
  4. 40
  5. 50

使用HashSet

让我们使用HashSet提供的add()方法来删除数组中的重复部分。如果这个集合没有包含指定的元素,add()方法返回true。

  1. import java.util.HashSet;
  2. import java.util.Set;
  3. public class DuplicateFromArray {
  4. public static void main(final String[] args) {
  5. final Integer[] a = {10,20,30,40,50,50,10,20};
  6. removeDuplicates(a);
  7. }
  8. private static void removeDuplicates(final Integer[] a){
  9. final Set<Integer> set = new HashSet<Integer>();
  10. final Integer[] temp = new Integer[a.length];
  11. int j = 0;
  12. for (final Integer element : a) {
  13. if(set.add(element)){
  14. temp[j++] = element;
  15. }
  16. }
  17. // display temp array
  18. for (int i = 0; i < j; i++) {
  19. System.out.println(temp[i]);
  20. }
  21. }
  22. }

输出:

  1. 10
  2. 20
  3. 30
  4. 40
  5. 50

相关文章

最新文章

更多