2017-06-02 190 views
-3

我試圖在這個數組中打印每個值的索引值。在Java數組中重複值的indexOf()

Integer[] i = { 0, 2, 3, 4, 4 }; 
    for (int each : i) { 
     System.out.print(Arrays.asList(i).indexOf(each) + " "); 
    } 

現在,我希望它說0, 1, 2, 3, 4,不0, 1, 2, 3, 3

我需要改變以獲得每個特定索引,而不是每個值的「第一次匹配」?

+0

我很困惑你試圖得到什麼,如果你一次遍歷一個數組,那麼在邏輯上,每次迭代的索引將與你的'i'值相同... – Reed

+1

@Aominè啊,謝謝你的澄清。 – Reed

回答

0

如果你在列表中有重複的值 - 你會在你的實現中返回第一個匹配值。爲了解決這個問題 - 你可以創建一個拷貝數組,當拷貝中找到值時 - 用「null」替換它。

下一次重複的值不會找到第1個重複項,並且會返回下一個索引。

Integer[] i = {0,2,3,4,4}; 
Integer[] copy = new Integer[i.length]; 
System.arraycopy(i, 0, copy, 0, i.length); 

     for (int each : i) { 
      int index = Arrays.asList(copy).indexOf(each); 
      System.out.print(index + " "); 
      copy[index] = null; 
     } 

輸出:0 1 2 3 4

當然現在可以重新排序初始陣列和它仍然會返回正確的索引。

1

不知道你想什麼你的代碼來完成,但如果你要打印的陣列的所有索引,而不是價值。如果你想獲得Index的,你可以做到這一點

Integer[] i = {0,2,3,4,4}; 
for (int index = 0; index < i.length; index++) 
{ 
    System.out.print(index + " "); 
} 
0

在陣列中特定項目,你可以做這樣的事情:

public static void main(String[] args){ 

    // Create example Arrays 
    Integer[] arrayOfIntegers = {1,2,3,4,5}; 
    String[] arrayOfStrings = {"A", "B", "C", "D",}; 

    /******Test*******/ 
    // what is the index of Integer 2 in the arrayOfIntegers 
    System.out.println(getIndex(arrayOfIntegers, 2)); 

    // what is the index of String "C" in the arrayOfStrings 
    System.out.println(getIndex(arrayOfStrings, "C")); 

    // what is the index of String "X" in the arrayOfIStrings 
    // which doesn't exist (expected value is -1) 
    System.out.println(getIndex(arrayOfStrings, "X")); 
} 

/** 
* This method to return the index of a given Object in 
* the array. It returns - 1 if doesn't exist 
* @param array 
* @param obj 
*/ 
public static int getIndex(Object[] array, Object obj){ 
    for(int i=0; i<array.length; i++){ 
     if(obj.equals(array[i])){ 
      return i; 
     } 
    } 
    return -1; 
} 

輸出

1 
2 
-1 

此外,如果你想返回發現了陣列中的重複項目的所有指數,你可以做這樣的事情:

/** 
* This method returns all indices of a given Object 
* in an ArrayList (which will be empty if did not found any) 
* @param array 
* @param obj 
*/ 
public static ArrayList<Integer> getIndices(Object[] array, Object obj){ 
    ArrayList<Integer> indices = new ArrayList<Integer>(); 
    for(int i=0; i<array.length; i++){ 
     if(obj.equals(array[i])){ 
      indices.add(i); 
     } 
    } 
    return indices; 
} 

測試

// Create example Array with duplicates 
String[] arrayHasDuplicates = {"A", "B", "C", "D", "B", "Y", "B"}; 
System.out.println(getIndices(arrayHasDuplicates, "B")); 

Output: 
[1, 4, 6]