2017-10-10 73 views
1

我有一個方法,可以很好地找到通用數組中的最小元素。但是,當我嘗試相同的方法但略有不同時,每次運行它都會返回0.我不知道爲什麼。查找通用數組方法中的最大元素,整數,字符串,字符

我想解決這個問題的方法看起來接近下面的這個方法。我不想導入Generic.max或使用集合,我想以更簡單的方式來完成它,如下所示。

如何使用類似於下面的方法來查找最大值?當我嘗試將< 0更改爲> 0時,它不起作用。我怎麼能讓這個最小的方法成爲最大的方法?

public static <E extends Comparable<E> > int getSmallesElement(E[] list) { 
     int minIndex = 0; 
     // Iterate from i+1 ti i-1 
     for (int index = minIndex + 1; index <= list.length - 1; index++) { 
      minIndex = (list[index].compareTo(list[minIndex]) < 0)? index : minIndex; 
     }// end for 

     return minIndex; 
    }// end getSmallest method 

就像我說的,如果我可以使用條件像我這將是偉大的第一種方法。我是新來的泛型,我試圖讓這些方法適用於整數,字符串和字符數組。

謝謝。

+0

'maxIndex = maxIndex;'... – Amit

+0

什麼是Generic.max? – shmosel

+0

根據你的代碼,只有一個元素的數組的最小/最大索引是什麼?沒有任何元素的數組? –

回答

0

你改寫了你的條件表達式爲if語句,但您沒有正確做到這一點:你想maxIndex = index,而不是index = maxIndex

而不是對在if的兩個分支每個迭代分配maxIndex,你只能在「真」分支分配給它,而完全放棄了「假」分支:

for(int index = maxIndex + 1; index <= list.length -1; index++) { 
    if (list[maxIndex].compareTo(list[index]) < 0) { 
     maxIndex = index; 
    } 
} 
0

你重置該index作爲循環去,而不是僅僅設置maxIndex

public static <E extends Comparable<E> > int getLargestElement(E[] list) { 
    int maxIndex = 0; 
    for(int index = 1; index <= list.length -1; index++) { 
     if (list[index].compareTo(list[maxIndex]) > 0) { 
      maxIndex = index; 
     } 
    } 
    return maxIndex; 
} 
+0

我不知道爲什麼,但我仍然返回0 –

+0

這段代碼應該工作。請分享您觀察到的輸入返回'0'。 – Mureinik

-1

我發現的東西,終於奏效。

public static <E extends Comparable<E> > E getLargestElement(E[] list) { 
     E max = list[0]; // set first value in array as current max 
     for(int i = 1; i < list.length; i++) { 
      if(list[i].compareTo(max) > 0) { 
       max = list[i]; 
      } 
     }// end for 
     return max; 
    } 

有人可以向我解釋爲什麼其他答案和我試圖使用的方法保持返回0嗎?它聽起來很合適,所有的答案也是如此,但它們並沒有奏效。

相關問題