Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Collection<Generic Type> Sorting without Collections

I'm really stuck on an assignment for school. We are learning about Generic Types, and maybe this is me not just understanding them fully, but as part of one of the first methods we have to implement:

We have:

public static <T> T min(Collection<T> c, Comparator<T> comp) {
        return null
}

And the requirements:

Selects the minimum value from the Collection c, as defined by the supplied Comparator comp. This method throws an IllegalArgumentException if either c or comp is null, and it throws a NoSuchElementException if c is empty. The Collection c is not changed by this method.

So I've gotten to here:

public static <T> T min(Collection<T> c, Comparator<T> comp)
            throws IllegalArgumentException, NoSuchElementException {
        if (c != null && comp != null) {
            if (!c.isEmpty()) {

            } else {
                throw new NoSuchElementException();
            }
        } else {
            throw new IllegalArgumentException();
        }
    }

We have to sort using a comparator, but CANNOT use the Collections class. I really just need some direction to start, I'm not asking you to do the assignment for me!

like image 252
acupofjose Avatar asked Aug 31 '26 09:08

acupofjose


1 Answers

It should be easy. Comparator is used to compare two elements not for sorting. Sorting is not necessary here. You don't want to change the collection, just find the minimum value. You can just take first one and iterate over the collection comparing choosen element to others, switching choosen element to another when it's bigger. This is the way to find the minimum.

like image 133
Patryk Dobrowolski Avatar answered Sep 03 '26 06:09

Patryk Dobrowolski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!