TheRapture87
TheRapture87

Reputation: 1423

CompareTo methods from comparable with list

I've written the answer to this question but on Netbeans it shows an error at this line:

        if (key.compareTo(obj) <= 1) 

The question is: Write a static method which takes a List or Set of objects which have a natural order, an object of the base type of the List or Set, and an integer n, and returns true if at least n objects in the List or Set are greater than the object argument according to their natural order, false otherwise.

My attempt:

public static <T extends Comparable<? super T>> boolean question9(List<T> list, List obj, int n) {

            int count = 0;
            for (T key : list) {
                if (key.compareTo(obj) <= 1) {
                    count++;
                }
            }
            if (n > count) {
                return false;
            } else {
                return true;
            }
        }

Upvotes: 0

Views: 321

Answers (1)

fge
fge

Reputation: 121780

Your assignment says (emphasis mine):

Write a static method which takes a List or Set of objects which have a natural order, an object of the base type of the List or Set

This does not mean that obj is a List or Set! This means that obj must be a T.

Also, your test is not good. The Comparable contract says that for two objects x and y, x is considered greater than y if x.compareTo(y) is greater than 0.

Therefore change your test to:

if (key.compareTo(obj) > 0)

Also, your final test can be simplified to:

return count >= n;

and you can even shortcut:

public static <T extends Comparable<? super T>> boolean question9(
    final Collection<T> collection, // assignment says List or Set
    final T obj, int n)
{
    int count = 0;
    for (final T element: collection) {
        if (element.compareTo(obj) <= 0)
            continue;
        if (++count >= n)
            return true;
    }
    return false;
}

Upvotes: 1

Related Questions