简体   繁体   English

Java使用循环从数组中删除重复项

[英]Java remove duplicates from array using loops

This is my current attempt to remove duplicates from an array holding integers, but this does not give me any results. 这是我当前的尝试,从包含整数的数组中删除重复项,但这没有任何结果。 It simply prints out nothing. 它只是什么都不打印。 Any help would be greatly appreciated. 任何帮助将不胜感激。

    public static void duplicate(int numbers[], int size)
    {
      for (int i = 0; i < size; i++){
        boolean duplicate = false;
        int b = 0;
        while (b < i){
          if (numbers[i] == numbers[b])
             duplicate = true;
          b++;}
        if (duplicate = false)
          System.out.print(numbers[i] + " ");}
    } 

Try this: 尝试这个:

public static void duplicate(int numbers[], int size)
{
  for (int i = 0; i < size; i++){
    boolean duplicate = false;
    int b = 0;
    while (b < i){
      if (numbers[i] == numbers[b])
         duplicate = true;
      b++;}
    if (duplicate == false)
      System.out.print(numbers[i] + " ");}
} 

You need to use == not = in your if statement. 您需要在if语句中使用== not =

You can also make use of HashSet or LinkedHashSet to Preserve the ordering 您还可以使用HashSet or LinkedHashSet to Preserve the ordering

public void removeDupInIntArray(int[] ints){
    Set<Integer> setString = new LinkedHashSet<Integer>();
    for(int i=0;i<ints.length;i++){
        setString.add(ints[i]);
    }
    System.out.println(setString);
}

最好的选择是使用Sets(Hash Linkedhash),从而避免重复

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM