    001package com.hammurapi.extract;
    002
    003import java.util.Comparator;
    004
    005import com.hammurapi.common.Util;
    006
    007/**
    008 * Comparator which uses extraction.
    009 * @author Pavel Vlasov
    010 *
    011 * @param <V>
    012 */
    013public class ExtractorComparator<T,V extends Comparable<V>, C> implements Comparator<T> {
    014
    015        private Extractor<T, V, C> extractor;
    016        private C context;
    017
    018        public ExtractorComparator(Extractor<T, V, C> extractor, C context) {
    019                this.extractor = extractor;
    020                this.context = context;
    021        }
    022
    023        @Override
    024        public int compare(T o1, T o2) {
    025                return extractor.extract(context, null, Util.wrap(o1)).compareTo(extractor.extract(context, null, Util.wrap(o2)));
    026        }
    027
    028        @Override
    029        public int hashCode() {
    030                final int prime = 31;
    031                int result = 1;
    032                result = prime * result + ((context == null) ? 0 : context.hashCode());
    033                result = prime * result + ((extractor == null) ? 0 : extractor.hashCode());
    034                return result;
    035        }
    036
    037        @Override
    038        public boolean equals(Object obj) {
    039                if (this == obj)
    040                        return true;
    041                if (obj == null)
    042                        return false;
    043                if (getClass() != obj.getClass())
    044                        return false;
    045                ExtractorComparator other = (ExtractorComparator) obj;
    046                if (context == null) {
    047                        if (other.context != null)
    048                                return false;
    049                } else if (!context.equals(other.context))
    050                        return false;
    051                if (extractor == null) {
    052                        if (other.extractor != null)
    053                                return false;
    054                } else if (!extractor.equals(other.extractor))
    055                        return false;
    056                return true;
    057        }
    058
    059}