我正在尝试创建一个函数,允许您传入 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/