acupofjose
acupofjose

Reputation: 2159

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!

Upvotes: 3

Views: 229

Answers (2)

borjab
borjab

Reputation: 11655

Pseudocode of what you need to add to your example:

  • Save the first element in a variable call "minimum". As it is declared generic the type of the object is T.
  • Iterate the collection (Clue: every collection has an iterator)
  • Compare each element with the "minimum" found. If lower than assign it to the minimum.
  • Return the variable minimum.

I won't put the code as it is homework and you need to familiarize with the syntax.

Upvotes: 2

Patryk Dobrowolski
Patryk Dobrowolski

Reputation: 1595

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.

Upvotes: 6

Related Questions