| 1 | package com.hammurapi.extract; |
| 2 | |
| 3 | import java.util.Comparator; |
| 4 | |
| 5 | import com.hammurapi.common.Util; |
| 6 | |
| 7 | /** |
| 8 | * Comparator which uses extraction. |
| 9 | * @author Pavel Vlasov |
| 10 | * |
| 11 | * @param <V> |
| 12 | */ |
| 13 | public class ExtractorComparator<T,V extends Comparable<V>, C> implements Comparator<T> { |
| 14 | |
| 15 | private Extractor<T, V, C> extractor; |
| 16 | private C context; |
| 17 | |
| 18 | public ExtractorComparator(Extractor<T, V, C> extractor, C context) { |
| 19 | this.extractor = extractor; |
| 20 | this.context = context; |
| 21 | } |
| 22 | |
| 23 | @Override |
| 24 | public int compare(T o1, T o2) { |
| 25 | return extractor.extract(context, null, Util.wrap(o1)).compareTo(extractor.extract(context, null, Util.wrap(o2))); |
| 26 | } |
| 27 | |
| 28 | @Override |
| 29 | public int hashCode() { |
| 30 | final int prime = 31; |
| 31 | int result = 1; |
| 32 | result = prime * result + ((context == null) ? 0 : context.hashCode()); |
| 33 | result = prime * result + ((extractor == null) ? 0 : extractor.hashCode()); |
| 34 | return result; |
| 35 | } |
| 36 | |
| 37 | @Override |
| 38 | public boolean equals(Object obj) { |
| 39 | if (this == obj) |
| 40 | return true; |
| 41 | if (obj == null) |
| 42 | return false; |
| 43 | if (getClass() != obj.getClass()) |
| 44 | return false; |
| 45 | ExtractorComparator other = (ExtractorComparator) obj; |
| 46 | if (context == null) { |
| 47 | if (other.context != null) |
| 48 | return false; |
| 49 | } else if (!context.equals(other.context)) |
| 50 | return false; |
| 51 | if (extractor == null) { |
| 52 | if (other.extractor != null) |
| 53 | return false; |
| 54 | } else if (!extractor.equals(other.extractor)) |
| 55 | return false; |
| 56 | return true; |
| 57 | } |
| 58 | |
| 59 | } |