java - 在整数数组的Arraylist中查找最大元素

标签 java arrays arraylist

我正在尝试创建一个函数,允许您传入 ArrayList 并返回最大元素。由于传入的数据类型不是原始数据,我一直无法找出正确的解决方案。我也尝试过将 ArrayList 转换为 ArrayList 但没有成功。这是迄今为止我的(不正确的)代码:

public static void maxArrayListValue(ArrayList<int[]> arrayList) {
    int maxArrayListValue = arrayList.get(0);   // set first arrayList element as highest

    for (int index=1; index < arrayList.size(); index++) {  // cycle through each arrayList element
        if (maxArrayListValue < arrayList.get(index)){      // if new element is > than old element
        maxArrayListValue = arrayList.get(index);           // replace with new maxValue
        maxArrayListIndex = index;                          // record index of max element
        }
    }
    return maxArrayListValue;
}

任何意见都将受到赞赏。

最佳答案

您的方法没有返回任何内容,我认为您想要迭代每个数组中的值。比如,

public static int maxArrayListValue(List<int[]> arrayList) {
    int maxVal = Integer.MIN_VALUE;
    for (int[] arr : arrayList) {
        for (int v : arr) {
            if (v > maxVal) {
                maxVal = v;
            }
        }
    }
    return maxVal;
}

关于java - 在整数数组的Arraylist中查找最大元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26331716/

相关文章:

java - 数据库查询 vs java 处理

c - c中的查找表

javascript - 从 JSON 数组中获取变量

javascript - 按属性值对对象的javascript数组进行排序并按条件重新排序

java - 将线程积添加到数组

java - 我应该如何处理这个IndexOutOfBounds异常?

java - 将变量传递给一个子类

java.lang.NoClassDefFoundError : Failed resolution of: Lcom/google/android/maps/GeoPoint

java - 在 java 中维护唯一数组的 ArrayList

java - 如何阻止数组在我的循环中显示所有空值?