Reputation: 2159
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
Reputation: 11655
Pseudocode of what you need to add to your example:
I won't put the code as it is homework and you need to familiarize with the syntax.
Upvotes: 2
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