查找通用数组方法中的最大元素,整数,字符串,字符

问题描述:

我有一个方法,可以很好地找到通用数组中的最小元素。但是,当我尝试相同的方法但略有不同时,每次运行它都会返回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

根据你的代码,只有一个元素的数组的最小/最大索引是什么?没有任何元素的数组? –

你改写了你的条件表达式为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; 
    } 
} 

你重置该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

我发现的东西,终于奏效。

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吗?它听起来很合适,所有的答案也是如此,但它们并没有奏效。