#Comparing items in Java

9 messages · Page 1 of 1 (latest)

indigo sentinel
#

I want to create a generic function that can nearly always find the largest item in any array. Based on this https://stackoverflow.com/questions/25779184/explanation-of-generic-t-extends-comparable-super-t-in-collection-sort-com post, I think the following will work in most cases:

// Comparable<? super T>> should mean that the type either implements comparable to itself, its supertype, or its supertype implements comparable to itself, not sure
static <T extends Comparable<? super T>> T maxOf(List<T> list) { 
    if (list.isEmpty()) // Ensure list is not empty - any other checks I need?
        throw new IllegalArgumentException("Arguments must not be empty.");

    T max = list.get(0); // set the max value to the first value
    
    for (T element : list) { // For each element in the list
        if (max.compareTo(element) < 0) // check if the current max is lower
            max = element; // set max to the new highest element
    }
    
    return max;
}

is there anything I'm missing, need to account for, or need to change in order to make this as universal as possible, for any values that can be compared with eachother?

halcyon elkBOT
#

This post has been reserved for your question.

Hey @indigo sentinel! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

pliant kraken
#

Only thing I see is an unnecessary comparison of the first element twice, otherwise it looks good to me

indigo sentinel
#

I suppose I could do it by creating an iterator, iterating once to use the first element for the max variable, then using the iterator for the for loop, but im not sure if iterators will universally work for any class that implements List

proper hull
#

I'd also check that the list is not null before checking that the list isn't empty

indigo sentinel
#

Thanks! I think I'll go ahead and close this, I'll add the null checking, as well.

halcyon elkBOT