簡體   English   中英

Java使用循環從數組中刪除重復項

[英]Java remove duplicates from array using loops

這是我當前的嘗試,從包含整數的數組中刪除重復項,但這沒有任何結果。 它只是什么都不打印。 任何幫助將不勝感激。

    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] + " ");}
    } 

嘗試這個:

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] + " ");}
} 

您需要在if語句中使用== not =

您還可以使用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