开发者

Generic Comparator

开发者 https://www.devze.com 2023-04-12 16:11 出处:网络
This is for a school project.I have a Query<E> class that holds an element that is part of the Query condition.So if it\'s a GreaterQuery and the element is 10, all values greater than 10 pass t

This is for a school project. I have a Query<E> class that holds an element that is part of the Query condition. So if it's a GreaterQuery and the element is 10, all values greater than 10 pass the condition.

The constructor of this 开发者_运维百科Query object takes the element, and a Comparator object to be used to test the condition. If null is passed in, I need to create a Comparator to use for the comparison.

I have a match(E element) method that tests the condition. Here's bare bones version of it:

public boolean matches(E element)
{
    if (comparator == null)
    {

    }
}

What I thought I could do was write an anonymous Comparator class inside the if statement, though I'm not sure if that's even possible. The other problem I'm having is how to even compare to E objects without knowing anything about them. Also, I'm not sure of this, but there may be a pre condition that E extends Comparable. It's very late and I apologize if this makes no sense. But any help will be appreciated.


If E is guaranteed to implement Comparable<E>, you can do this:

if (comparator == null) {
    comparator = new Comparator<E>() {
        @Override
        public int compare(E lhs, E rhs) {
            return lhs.compareTo(rhs);
        }
    };
}


Since Java 8 there is a method in the standard library which does the exact thing that is showed in Chris' answer:

if (comparator == null) {
    comparator = Comparator.naturalOrder();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号