2015-11-18 21 views
2

我必須找到兩個Set對象之間的交集。查找路口

+0

什麼參數的類型?你的'Set'類或'java.util.Set'? –

+0

爲什麼編輯的實際實施?這個問題在目前的形式中幾乎沒有任何意義。 – Codor

回答

3

變量intCount在最裏面的if條件是本地的,這意味着只有第一個條目interArr被訪問。重新排列實施如下。

public int[] intersection(Set parSet) 
{ 
    int[] interArr = new int[numbers.length]; 
    int[] testArr = parSet.toArray(); 

    int intCount = 0; // initialization out of the loop 

    for(int index = 0; index < numbers.length; index++) 
    { 
     for(int compareInt = 0; compareInt < testArr.length; compareInt++) 
     { 
      if(numbers[index] == testArr[compareInt]) 
      { 
       interArr[intCount] = testArr[compareInt]; 
       intCount++; 
      }//end if 
     }//end inner for 
    }//end outter for 

    return interArr; 
}//end method intersection 
1

你是在正確的軌道上:使用嵌套循環做一個詳盡的搜索(雖然它可以使用Java集合來簡化),只有一些小問題:

1)你沒」牛逼定義toArray()方法類,所以假設你的意思是parSet.numbers當你調用parSet.toArray()

2)櫃檯intCount需要在循環之外,以免被設置爲0,在每一個ITER通貨膨脹。

所以正確的版本應該是:

public int[] intersection(Set parSet) { 
    int[] interArr = new int[numbers.length]; 
    int[] testArr = parSet.numbers; //you didn't define toArray() for the class Set 
    int intCount = 0; // move this variable out of the loop 
    for (int index = 0; index < numbers.length; index++) { 
     for (int compareInt = 0; compareInt < testArr.length; compareInt++) { 
      if (numbers[index] == testArr[compareInt]) { 
       interArr[intCount] = testArr[compareInt]; 
       intCount++; 
      }//end if 
     }//end inner for 
    }//end outter for 

    return interArr; 
}//end method intersection