1

I'm attempting to create a function that allows you to pass in a ArrayList and return the max element. I have been unable to figure out a correct solution because of the data type being passed in is not primitive. I've also tried converting the ArrayList to ArrayList without success. Here is my (incorrect) code thus far:

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;
}

Any input would be apprecieated.

2 Answers 2

1

Your method isn't returning anything, and I think you want to iterate the values in each array. Something like,

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

This worked perfectly. I just want to make sure I'm understanding this correctly; the first loops through each array in the arraylist and the second loops through each element in each array?
You have a List<int[]> so we first iterate the int[] contents of your List<> and then you have it!
1

You don't need a loop. Just use java.util.Collections.max(arrayList);

2 Comments

I'm not sure if this works, I thought you could only use collections on primitive data types? I get the error: "The method max(<? extends T>) in the type Collections is not applicable for the arguments (ArrayList<int[]>)".
If your collection elements don't have a natural ordering, you have to provide a Comparator as the second element.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.