Dropping comparators for next release (LANG-532)

git-svn-id: https://svn.apache.org/repos/asf/commons/proper/lang/trunk@1199609 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Henri Yandell 2011-11-09 04:12:18 +00:00
parent 22861326c2
commit 9bb3361616
13 changed files with 0 additions and 1297 deletions

View File

@ -1,130 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.lang3.compare;
import java.io.Serializable;
import java.util.Comparator;
/**
* A {@link Comparator Comparator} that compares
* {@link Comparable Comparable} objects.
* <p />
* This Comparator is useful, for example,
* for enforcing the natural order in custom implementations
* of SortedSet and SortedMap.
* <p />
* Note: In the 2.0 and 2.1 releases of Commons Collections,
* this class would throw a {@link ClassCastException} if
* either of the arguments to {@link #compare(Object, Object) compare}
* were <code>null</code>, not {@link Comparable Comparable},
* or for which {@link Comparable#compareTo(Object) compareTo} gave
* inconsistent results. This is no longer the case. See
* {@link #compare(Object, Object) compare} for details.
*
* @since Commons Collections 2.0
* @version $Revision$ $Date$
*
* @see java.util.Collections#reverseOrder()
*/
public class ComparableComparator<E extends Comparable<? super E>> implements Comparator<E>, Serializable {
/** Serialization version. */
private static final long serialVersionUID=-291439688585137865L;
/** The singleton instance. */
@SuppressWarnings("rawtypes")
public static final ComparableComparator<?> INSTANCE = new ComparableComparator();
//-----------------------------------------------------------------------
/**
* Gets the singleton instance of a ComparableComparator.
* <p>
* Developers are encouraged to use the comparator returned from this method
* instead of constructing a new instance to reduce allocation and GC overhead
* when multiple comparable comparators may be used in the same VM.
*
* @param <E> the type of the enumeration
* @return the singleton ComparableComparator
*/
@SuppressWarnings("unchecked")
public static <E extends Comparable<? super E>> ComparableComparator<E> comparableComparator() {
return (ComparableComparator<E>) INSTANCE;
}
//-----------------------------------------------------------------------
/**
* Constructor whose use should be avoided.
* <p>
* Please use the {@link #comparableComparator()} method whenever possible.
*/
public ComparableComparator() {
super();
}
//-----------------------------------------------------------------------
/**
* Compare the two {@link Comparable Comparable} arguments.
* This method is equivalent to:
* <pre>((Comparable)obj1).compareTo(obj2)</pre>
*
* @param obj1 the first object to compare
* @param obj2 the second object to compare
* @return negative if obj1 is less, positive if greater, zero if equal
* @throws NullPointerException when <i>obj1</i> is <code>null</code>,
* or when <code>((Comparable)obj1).compareTo(obj2)</code> does
* @throws ClassCastException when <i>obj1</i> is not a <code>Comparable</code>,
* or when <code>((Comparable)obj1).compareTo(obj2)</code> does
*/
public int compare(E obj1, E obj2) {
return obj1.compareTo(obj2);
}
//-----------------------------------------------------------------------
/**
* Implement a hash code for this comparator that is consistent with
* {@link #equals(Object) equals}.
*
* @return a hash code for this comparator.
* @since Commons Collections 3.0
*/
@Override
public int hashCode() {
return "ComparableComparator".hashCode();
}
/**
* Returns <code>true</code> iff <i>that</i> Object is
* is a {@link Comparator Comparator} whose ordering is
* known to be equivalent to mine.
* <p>
* This implementation returns <code>true</code>
* iff <code><i>object</i>.{@link Object#getClass() getClass()}</code>
* equals <code>this.getClass()</code>.
* Subclasses may want to override this behavior to remain consistent
* with the {@link Comparator#equals(Object)} contract.
*
* @param object the object to compare with
* @return true if equal
* @since Commons Collections 3.0
*/
@Override
public boolean equals(Object object) {
return (this == object) ||
((null != object) && (object.getClass().equals(this.getClass())));
}
}

View File

@ -1,168 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.lang3.compare;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
/**
* <p>A ComparatorChain is a Comparator that wraps one or
* more Comparators in sequence. The ComparatorChain
* calls each Comparator in sequence until either 1)
* any single Comparator returns a non-zero result
* (and that result is then returned),
* or 2) the ComparatorChain is exhausted (and zero is
* returned). This type of sorting is very similar
* to multi-column sorting in SQL, and this class
* allows Java classes to emulate that kind of behaviour
* when sorting a List.</p>
*
* <p>Instances of ComparatorChain are not synchronized.
* The class is not thread-safe at construction time, but
* it <i>is</i> thread-safe to perform multiple comparisons
* after all the setup operations are complete.</p>
*
* @since Commons Collections 2.0
* @version $Revision$ $Date$
*/
public class ComparatorChain<E> implements Comparator<E>, Serializable, Iterable {
/** The list of comparators in the chain. */
protected List<Comparator<E>> comparatorChain = null;
//-----------------------------------------------------------------------
/**
* Construct a ComparatorChain with a single Comparator,
* sorting in the forward order
*
* @param comparators Comparators in the Comparator chain
*/
public ComparatorChain(Comparator<E>... comparators) {
this.comparatorChain = new ArrayList<Comparator<E>>();
Collections.addAll(this.comparatorChain, comparators);
}
/**
* Construct a ComparatorChain from the Comparators in the
* List. All Comparators will default to the forward
* sort order.
*
* @param list List of Comparators
*/
public ComparatorChain(List<Comparator<E>> list) {
this.comparatorChain = new ArrayList<Comparator<E>>();
this.comparatorChain.addAll(list);
}
//-----------------------------------------------------------------------
/**
* Number of Comparators in the current ComparatorChain.
*
* @return Comparator count
*/
public int size() {
return comparatorChain.size();
}
/**
* Perform comparisons on the Objects as per Comparator.compare(o1,o2).
*
* @param o1 the first object to compare
* @param o2 the second object to compare
* @return -1, 0, or 1
*/
public int compare(E o1, E o2) {
// iterate over all comparators in the chain
Iterator<Comparator<E>> comparators = comparatorChain.iterator();
for (int comparatorIndex = 0; comparators.hasNext(); ++comparatorIndex) {
Comparator<E> comparator = comparators.next();
int retval = comparator.compare(o1,o2);
if (retval != 0) {
return retval;
}
}
// if comparators are exhausted, return 0
return 0;
}
//-----------------------------------------------------------------------
/**
* Iterate through the chained comparators.
*
* @return Unmodifiable iterator over the chained comparators
*/
public Iterator<Comparator<E>> iterator() {
return new UnmodifiableIterator(comparatorChain.iterator());
}
//-----------------------------------------------------------------------
/**
* Implement a hash code for this comparator that is consistent with
* {@link #equals(Object) equals}.
*
* @return a suitable hash code
* @since Commons Collections 3.0
*/
@Override
public int hashCode() {
int hash = 0;
if (comparatorChain != null) {
hash ^= comparatorChain.hashCode();
}
return hash;
}
/**
* Returns <code>true</code> iff <i>that</i> Object is
* is a {@link Comparator} whose ordering is known to be
* equivalent to mine.
* <p>
* This implementation returns <code>true</code>
* iff <code><i>object</i>.{@link Object#getClass() getClass()}</code>
* equals <code>this.getClass()</code>, and the underlying
* comparators and order bits are equal.
* Subclasses may want to override this behavior to remain consistent
* with the {@link Comparator#equals(Object)} contract.
*
* @param object the object to compare with
* @return true if equal
* @since Commons Collections 3.0
*/
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (object == null) {
return false;
}
if (object.getClass().equals(this.getClass())) {
ComparatorChain<?> chain = (ComparatorChain<?>) object;
return ( (comparatorChain == null ? chain.comparatorChain == null
: comparatorChain.equals(chain.comparatorChain)));
}
return false;
}
}

View File

@ -1,44 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.lang3.compare;
import java.util.Comparator;
/**
* Provides convenient static utility methods for <Code>Comparator</Code>
* objects.
*
* @since Commons Collections 2.1
* @version $Revision$ $Date$
*/
class ComparatorUtils {
/**
* ComparatorUtils should not normally be instantiated.
*/
public ComparatorUtils() {
}
/**
* Comparator for natural sort order.
*
* @see ComparableComparator#INSTANCE
*/
@SuppressWarnings("unchecked")
public static final Comparator NATURAL_COMPARATOR = ComparableComparator.<Comparable>comparableComparator();
}

View File

@ -1,243 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.lang3.compare;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* A Comparator which imposes a specific order on a specific set of Objects.
* Objects are presented to the FixedOrderComparator in a specified order and
* subsequent calls to {@link #compare(Object, Object) compare} yield that order.
* For example:
* <pre>
* String[] planets = {"Mercury", "Venus", "Earth", "Mars"};
* FixedOrderComparator distanceFromSun = new FixedOrderComparator(planets);
* Arrays.sort(planets); // Sort to alphabetical order
* Arrays.sort(planets, distanceFromSun); // Back to original order
* </pre>
* <p>
* Once <code>compare</code> has been called, the FixedOrderComparator is locked
* and attempts to modify it yield an UnsupportedOperationException.
* <p>
* Instances of FixedOrderComparator are not synchronized. The class is not
* thread-safe at construction time, but it is thread-safe to perform
* multiple comparisons after all the setup operations are complete.
*
* @since Commons Collections 3.0
* @version $Revision$ $Date$
*/
public class FixedOrderComparator<T> implements Comparator<T> {
/**
* Unknown object behavior enum.
* @since Commons Collections 5
*/
public static enum UnknownObjectBehavior {
BEFORE, AFTER, EXCEPTION;
}
/** Internal map of object to position */
private final Map<T, Integer> map = new HashMap<T, Integer>();
/** Counter used in determining the position in the map */
private int counter = 0;
/** Is the comparator locked against further change */
private boolean isLocked = false;
/** The behaviour in the case of an unknown object */
private UnknownObjectBehavior unknownObjectBehavior = UnknownObjectBehavior.EXCEPTION;
// Constructors
//-----------------------------------------------------------------------
/**
* Constructs an empty FixedOrderComparator.
*/
public FixedOrderComparator() {
super();
}
/**
* Constructs a FixedOrderComparator which uses the order of the given array
* to compare the objects.
* <p>
* The array is copied, so later changes will not affect the comparator.
*
* @param items the items that the comparator can compare in order
* @throws IllegalArgumentException if the array is null
*/
public FixedOrderComparator(T[] items) {
super();
if (items == null) {
throw new IllegalArgumentException("The list of items must not be null");
}
for (T item : items) {
add(item);
}
}
/**
* Constructs a FixedOrderComparator which uses the order of the given list
* to compare the objects.
* <p>
* The list is copied, so later changes will not affect the comparator.
*
* @param items the items that the comparator can compare in order
* @throws IllegalArgumentException if the list is null
*/
public FixedOrderComparator(List<T> items) {
super();
if (items == null) {
throw new IllegalArgumentException("The list of items must not be null");
}
for (T t : items) {
add(t);
}
}
// Bean methods / state querying methods
//-----------------------------------------------------------------------
/**
* Returns true if modifications cannot be made to the FixedOrderComparator.
* FixedOrderComparators cannot be modified once they have performed a comparison.
*
* @return true if attempts to change the FixedOrderComparator yield an
* UnsupportedOperationException, false if it can be changed.
*/
public boolean isLocked() {
return isLocked;
}
/**
* Checks to see whether the comparator is now locked against further changes.
*
* @throws UnsupportedOperationException if the comparator is locked
*/
protected void checkLocked() {
if (isLocked()) {
throw new UnsupportedOperationException("Cannot modify a FixedOrderComparator after a comparison");
}
}
/**
* Gets the behavior for comparing unknown objects.
*
* @return {@link UnknownObjectBehavior}
*/
public UnknownObjectBehavior getUnknownObjectBehavior() {
return unknownObjectBehavior;
}
/**
* Sets the behavior for comparing unknown objects.
*
* @param unknownObjectBehavior the flag for unknown behaviour -
* UNKNOWN_AFTER, UNKNOWN_BEFORE or UNKNOWN_THROW_EXCEPTION
* @throws UnsupportedOperationException if a comparison has been performed
* @throws IllegalArgumentException if the unknown flag is not valid
*/
public void setUnknownObjectBehavior(UnknownObjectBehavior unknownObjectBehavior) {
checkLocked();
if (unknownObjectBehavior == null) {
throw new IllegalArgumentException("Unknown object behavior must not be null");
}
this.unknownObjectBehavior = unknownObjectBehavior;
}
// Methods for adding items
//-----------------------------------------------------------------------
/**
* Adds an item, which compares as after all items known to the Comparator.
* If the item is already known to the Comparator, its old position is
* replaced with the new position.
*
* @param obj the item to be added to the Comparator.
* @return true if obj has been added for the first time, false if
* it was already known to the Comparator.
* @throws UnsupportedOperationException if a comparison has already been made
*/
public boolean add(T obj) {
checkLocked();
Integer position = map.put(obj, new Integer(counter++));
return (position == null);
}
/**
* Adds a new item, which compares as equal to the given existing item.
*
* @param existingObj an item already in the Comparator's set of
* known objects
* @param newObj an item to be added to the Comparator's set of
* known objects
* @return true if newObj has been added for the first time, false if
* it was already known to the Comparator.
* @throws IllegalArgumentException if existingObject is not in the
* Comparator's set of known objects.
* @throws UnsupportedOperationException if a comparison has already been made
*/
public boolean addAsEqual(T existingObj, T newObj) {
checkLocked();
Integer position = map.get(existingObj);
if (position == null) {
throw new IllegalArgumentException(existingObj + " not known to " + this);
}
Integer result = map.put(newObj, position);
return (result == null);
}
// Comparator methods
//-----------------------------------------------------------------------
/**
* Compares two objects according to the order of this Comparator.
* <p>
* It is important to note that this class will throw an IllegalArgumentException
* in the case of an unrecognised object. This is not specified in the
* Comparator interface, but is the most appropriate exception.
*
* @param obj1 the first object to compare
* @param obj2 the second object to compare
* @return negative if obj1 is less, positive if greater, zero if equal
* @throws IllegalArgumentException if obj1 or obj2 are not known
* to this Comparator and an alternative behavior has not been set
* via {@link #setUnknownObjectBehavior(UnknownObjectBehavior)}.
*/
public int compare(T obj1, T obj2) {
isLocked = true;
Integer position1 = map.get(obj1);
Integer position2 = map.get(obj2);
if (position1 == null || position2 == null) {
switch (unknownObjectBehavior) {
case BEFORE:
return position1 == null ? position2 == null ? 0 : -1 : 1;
case AFTER:
return position1 == null ? position2 == null ? 0 : 1 : -1;
case EXCEPTION:
Object unknownObj = (position1 == null) ? obj1 : obj2;
throw new IllegalArgumentException("Attempting to compare unknown object "
+ unknownObj);
default: //could be null
throw new UnsupportedOperationException("Unknown unknownObjectBehavior: "
+ unknownObjectBehavior);
}
}
return position1.compareTo(position2);
}
}

View File

@ -1,178 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.lang3.compare;
import java.io.Serializable;
import java.util.Comparator;
/**
* A Comparator that will compare nulls to be either lower or higher than
* other objects.
*
* @since Commons Collections 2.0
* @version $Revision$ $Date$
*/
public class NullComparator<E> implements Comparator<E>, Serializable {
/** Serialization version. */
private static final long serialVersionUID = -5820772575483504339L;
/**
* The comparator to use when comparing two non-<code>null</code> objects.
**/
private final Comparator<E> nonNullComparator;
/**
* Specifies whether a <code>null</code> are compared as higher than
* non-<code>null</code> objects.
**/
private final boolean nullsAreHigh;
//-----------------------------------------------------------------------
/**
* Construct an instance that sorts <code>null</code> higher than any
* non-<code>null</code> object it is compared with. When comparing two
* non-<code>null</code> objects, the {@link ComparableComparator} is
* used.
**/
@SuppressWarnings("unchecked")
public NullComparator() {
this(ComparatorUtils.NATURAL_COMPARATOR, true);
}
/**
* Construct an instance that sorts <code>null</code> higher than any
* non-<code>null</code> object it is compared with. When comparing two
* non-<code>null</code> objects, the specified {@link Comparator} is
* used.
*
* @param nonNullComparator the comparator to use when comparing two
* non-<code>null</code> objects. This argument cannot be
* <code>null</code>
*
* @exception NullPointerException if <code>nonNullComparator</code> is
* <code>null</code>
**/
public NullComparator(Comparator<E> nonNullComparator) {
this(nonNullComparator, true);
}
/**
* Construct an instance that sorts <code>null</code> higher or lower than
* any non-<code>null</code> object it is compared with. When comparing
* two non-<code>null</code> objects, the {@link ComparableComparator} is
* used.
*
* @param nullsAreHigh a <code>true</code> value indicates that
* <code>null</code> should be compared as higher than a
* non-<code>null</code> object. A <code>false</code> value indicates
* that <code>null</code> should be compared as lower than a
* non-<code>null</code> object.
**/
@SuppressWarnings("unchecked")
public NullComparator(boolean nullsAreHigh) {
this(ComparatorUtils.NATURAL_COMPARATOR, nullsAreHigh);
}
/**
* Construct an instance that sorts <code>null</code> higher or lower than
* any non-<code>null</code> object it is compared with. When comparing
* two non-<code>null</code> objects, the specified {@link Comparator} is
* used.
*
* @param nonNullComparator the comparator to use when comparing two
* non-<code>null</code> objects. This argument cannot be
* <code>null</code>
*
* @param nullsAreHigh a <code>true</code> value indicates that
* <code>null</code> should be compared as higher than a
* non-<code>null</code> object. A <code>false</code> value indicates
* that <code>null</code> should be compared as lower than a
* non-<code>null</code> object.
*
* @exception NullPointerException if <code>nonNullComparator</code> is
* <code>null</code>
**/
public NullComparator(Comparator<E> nonNullComparator, boolean nullsAreHigh) {
this.nonNullComparator = nonNullComparator;
this.nullsAreHigh = nullsAreHigh;
if (nonNullComparator == null) {
throw new NullPointerException("null nonNullComparator");
}
}
//-----------------------------------------------------------------------
/**
* Perform a comparison between two objects. If both objects are
* <code>null</code>, a <code>0</code> value is returned. If one object
* is <code>null</code> and the other is not, the result is determined on
* whether the Comparator was constructed to have nulls as higher or lower
* than other objects. If neither object is <code>null</code>, an
* underlying comparator specified in the constructor (or the default) is
* used to compare the non-<code>null</code> objects.
*
* @param o1 the first object to compare
* @param o2 the object to compare it to.
* @return <code>-1</code> if <code>o1</code> is "lower" than (less than,
* before, etc.) <code>o2</code>; <code>1</code> if <code>o1</code> is
* "higher" than (greater than, after, etc.) <code>o2</code>; or
* <code>0</code> if <code>o1</code> and <code>o2</code> are equal.
**/
public int compare(E o1, E o2) {
if(o1 == o2) { return 0; }
if(o1 == null) { return (this.nullsAreHigh ? 1 : -1); }
if(o2 == null) { return (this.nullsAreHigh ? -1 : 1); }
return this.nonNullComparator.compare(o1, o2);
}
//-----------------------------------------------------------------------
/**
* Implement a hash code for this comparator that is consistent with
* {@link #equals(Object)}.
*
* @return a hash code for this comparator.
**/
@Override
public int hashCode() {
return (nullsAreHigh ? -1 : 1) * nonNullComparator.hashCode();
}
/**
* Determines whether the specified object represents a comparator that is
* equal to this comparator.
*
* @param obj the object to compare this comparator with.
*
* @return <code>true</code> if the specified object is a NullComparator
* with equivalent <code>null</code> comparison behavior
* (i.e. <code>null</code> high or low) and with equivalent underlying
* non-<code>null</code> object comparators.
**/
@Override
public boolean equals(Object obj) {
if(obj == null) { return false; }
if(obj == this) { return true; }
if(!obj.getClass().equals(this.getClass())) { return false; }
NullComparator<?> other = (NullComparator<?>) obj;
return ((this.nullsAreHigh == other.nullsAreHigh) &&
(this.nonNullComparator.equals(other.nonNullComparator)));
}
}

View File

@ -1,122 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.lang3.compare;
import java.io.Serializable;
import java.util.Comparator;
/**
* Reverses the order of another comparator by reversing the arguments
* to its {@link #compare(Object, Object) compare} method.
*
* @since Commons Collections 2.0
* @version $Revision$ $Date$
*
* @see java.util.Collections#reverseOrder()
*/
public class ReverseComparator<E> implements Comparator<E>, Serializable {
/** Serialization version from Collections 2.0. */
private static final long serialVersionUID = 2858887242028539265L;
/** The comparator being decorated. */
private final Comparator<E> comparator;
//-----------------------------------------------------------------------
/**
* Creates a comparator that compares objects based on the inverse of their
* natural ordering. Using this Constructor will create a ReverseComparator
* that is functionally identical to the Comparator returned by
* java.util.Collections.<b>reverseOrder()</b>.
*
* @see java.util.Collections#reverseOrder()
*/
public ReverseComparator() {
this(null);
}
/**
* Creates a comparator that inverts the comparison
* of the given comparator. If you pass in <code>null</code>,
* the ReverseComparator defaults to reversing the
* natural order, as per
* {@link java.util.Collections#reverseOrder()}</b>.
*
* @param comparator Comparator to reverse
*/
@SuppressWarnings("unchecked")
public ReverseComparator(Comparator<E> comparator) {
this.comparator = comparator == null ? ComparatorUtils.NATURAL_COMPARATOR : comparator;
}
//-----------------------------------------------------------------------
/**
* Compares two objects in reverse order.
*
* @param obj1 the first object to compare
* @param obj2 the second object to compare
* @return negative if obj1 is less, positive if greater, zero if equal
*/
public int compare(E obj1, E obj2) {
return comparator.compare(obj2, obj1);
}
//-----------------------------------------------------------------------
/**
* Implement a hash code for this comparator that is consistent with
* {@link #equals(Object) equals}.
*
* @return a suitable hash code
* @since Commons Collections 3.0
*/
@Override
public int hashCode() {
return "ReverseComparator".hashCode() ^ comparator.hashCode();
}
/**
* Returns <code>true</code> iff <i>that</i> Object is
* is a {@link Comparator} whose ordering is known to be
* equivalent to mine.
* <p>
* This implementation returns <code>true</code>
* iff <code><i>object</i>.{@link Object#getClass() getClass()}</code>
* equals <code>this.getClass()</code>, and the underlying
* comparators are equal.
* Subclasses may want to override this behavior to remain consistent
* with the {@link Comparator#equals(Object) equals} contract.
*
* @param object the object to compare to
* @return true if equal
* @since Commons Collections 3.0
*/
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (null == object) {
return false;
}
if (object.getClass().equals(this.getClass())) {
ReverseComparator<?> thatrc = (ReverseComparator<?>) object;
return comparator.equals(thatrc.comparator);
}
return false;
}
}

View File

@ -1,61 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.lang3.compare;
import java.util.Iterator;
/**
* Decorates an iterator such that it cannot be modified.
* <p>
* Attempts to modify it will result in an UnsupportedOperationException.
*
* @since Commons Collections 3.0
* @version $Revision: 1148801 $ $Date: 2011-07-20 07:44:46 -0700 (Wed, 20 Jul 2011) $
*/
final class UnmodifiableIterator<E> implements Iterator<E> {
/** The iterator being decorated */
private final Iterator<E> iterator;
//-----------------------------------------------------------------------
/**
* Constructor.
*
* @param iterator the iterator to decorate
*/
public UnmodifiableIterator(Iterator<E> iterator) {
super();
if (iterator == null) {
throw new IllegalArgumentException("Iterator must not be null");
}
this.iterator = iterator;
}
//-----------------------------------------------------------------------
public boolean hasNext() {
return iterator.hasNext();
}
public E next() {
return iterator.next();
}
public void remove() {
throw new UnsupportedOperationException("remove() is not supported");
}
}

View File

@ -1,27 +0,0 @@
<!-- $Id$ -->
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<BODY>
<p>
This package contains implementations of the
{@link java.util.Comparator Comparator} interface.
<p>
You may also consider using
{@link org.apache.commons.collections.ComparatorUtils ComparatorUtils},
which is a single class that uses static methods to construct instances
of the classes in this package.
</BODY>

View File

@ -1,59 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.lang3.compare;
import static org.junit.Assert.*;
import java.io.File;
import java.util.Comparator;
import org.junit.Before;
import org.junit.Test;
/**
* <p>
* Tests the methods in the {@link org.apache.commons.lang3.compare.ComparableComparator} class.
* </p>
*
* @version $Id: RangeTest.java 1147537 2011-07-17 06:10:37Z mbenson $
*/
public class ComparableComparatorTest {
@Before
public void setUp() {
}
//-----------------------------------------------------------------------
@Test
public void testUse() {
Comparator cc = new ComparableComparator();
// ensure same as Comparable
assertEquals( "Not same as Integer.compareTo", new Integer(5).compareTo(2), cc.compare(5, 2) );
assertEquals( "Not same as String.compareTo", "aardvark".compareTo("green"), cc.compare("aardvark", "green") );
assertEquals( "Not same as File.compareTo", new File("dir/file").compareTo(new File("dir/file2")),
cc.compare(new File("dir/file"), new File("dir/file2")) );
}
public void testEquals() {
assertEquals( "Same instance wasn't equal", ComparableComparator.INSTANCE, ComparableComparator.INSTANCE);
assertEquals( "Different instance wasn't equal", ComparableComparator.INSTANCE, new ComparableComparator());
assertFalse( "Null was equal", ComparableComparator.INSTANCE.equals(null) );
}
}

View File

@ -1,71 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.lang3.compare;
import static org.junit.Assert.*;
import java.util.Comparator;
import java.util.Iterator;
import org.junit.Before;
import org.junit.Test;
/**
* <p>
* Tests the methods in the {@link org.apache.commons.lang3.compare.ComparatorChain} class.
* </p>
*
* @version $Id: RangeTest.java 1147537 2011-07-17 06:10:37Z mbenson $
*/
public class ComparatorChainTest {
@Test
public void testUse() {
// Sorts ABC-123 by numbers and then letters
ComparatorChain cc = new ComparatorChain(
new ComparableComparator<String>() {
public int compare(String o1, String o2) {
return super.compare(o1.substring(4), o2.substring(4));
}
},
ComparableComparator.INSTANCE
);
assertTrue("Comparison failed", cc.compare( "ABC-123", "ABC-124" ) < 0 );
assertTrue("Comparison failed", cc.compare( "ZZZ-123", "AAA-124" ) < 0 );
assertTrue("Comparison failed", cc.compare( "ABC-123", "ABD-123" ) < 0 );
assertTrue("Comparison failed", cc.compare( "ABC-123", "ABC-123" ) == 0 );
}
@Test
public void testIterate() {
Comparator c1 = ComparableComparator.INSTANCE;
Comparator c2 = new ComparableComparator();
Comparator c3 = new NullComparator();
Comparator c4 = new ReverseComparator();
Iterable cc = new ComparatorChain(c1, c2, c3, c4);
Iterator itr = cc.iterator();
assertEquals( "Iteration failed", c1, itr.next() );
assertEquals( "Iteration failed", c2, itr.next() );
assertEquals( "Iteration failed", c3, itr.next() );
assertEquals( "Iteration failed", c4, itr.next() );
assertFalse( "Iteration failed", itr.hasNext() );
}
}

View File

@ -1,52 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.lang3.compare;
import static org.junit.Assert.*;
import java.util.Comparator;
import java.util.Arrays;
import org.junit.Before;
import org.junit.Test;
/**
* <p>
* Tests the methods in the {@link org.apache.commons.lang3.compare.FixedOrderComparator} class.
* </p>
*
* @version $Id: RangeTest.java 1147537 2011-07-17 06:10:37Z mbenson $
*/
public class FixedOrderComparatorTest {
@Before
public void setUp() {
}
//-----------------------------------------------------------------------
@Test
public void testJavadocExample() {
String[] planets = {"Mercury", "Venus", "Earth", "Mars"};
String[] modified = {"Mercury", "Venus", "Earth", "Mars"};
Comparator distanceFromSun = new FixedOrderComparator(planets);
Arrays.sort(modified); // Sort to alphabetical order
Arrays.sort(modified, distanceFromSun); // Back to original order
assertArrayEquals("Did not sort to fixed order", planets, modified);
}
}

View File

@ -1,55 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.lang3.compare;
import static org.junit.Assert.*;
import java.util.Comparator;
import org.junit.Before;
import org.junit.Test;
/**
* <p>
* Tests the methods in the {@link org.apache.commons.lang3.compare.NullComparator} class.
* </p>
*
* @version $Id: RangeTest.java 1147537 2011-07-17 06:10:37Z mbenson $
*/
public class NullComparatorTest {
@Before
public void setUp() {
}
//-----------------------------------------------------------------------
@Test
public void testNullHigh() {
Comparator c = new NullComparator(true);
assertEquals("Null was not treated as high", -1, c.compare(new Object(), null) );
assertEquals("Null was not treated as high", 1, c.compare(null, new Object()) );
}
@Test
public void testNullLow() {
Comparator c = new NullComparator(false);
assertEquals("Null was not treated as low", 1, c.compare(new Object(), null) );
assertEquals("Null was not treated as low", -1, c.compare(null, new Object()) );
}
}

View File

@ -1,87 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.lang3.compare;
import static org.junit.Assert.*;
import java.util.Comparator;
import org.junit.Before;
import org.junit.Test;
/**
* <p>
* Tests the methods in the {@link org.apache.commons.lang3.compare.ReverseComparator} class.
* </p>
*
* @version $Id: RangeTest.java 1147537 2011-07-17 06:10:37Z mbenson $
*/
public class ReverseComparatorTest {
@Before
public void setUp() {
}
//-----------------------------------------------------------------------
@Test
public void testUse() {
ReverseComparator rc = new ReverseComparator();
// back to front tests
assertTrue("Comparison wasn't reversed", rc.compare( 2, 1 ) < 0 );
assertTrue("Comparison wasn't reversed", rc.compare( 1, 2 ) > 0 );
assertTrue("Comparison wasn't reversed", rc.compare( "baa", "aardvark" ) < 0 );
assertTrue("Comparison wasn't reversed", rc.compare( "aardvark", "baa" ) > 0 );
}
@Test
public void testTwoCallsCancel() {
ReverseComparator rc = new ReverseComparator(new ReverseComparator());
// back to front tests
assertTrue("Reversal wasn't cancelled out", rc.compare( 1, 2 ) < 0 );
assertTrue("Reversal wasn't cancelled out", rc.compare( 2, 1 ) > 0 );
assertTrue("Reversal wasn't cancelled out", rc.compare( "aardvark", "baa" ) < 0 );
assertTrue("Reversal wasn't cancelled out", rc.compare( "baa", "aardvark" ) > 0 );
}
@Test
public void testEquality() {
ReverseComparator rc1 = new ReverseComparator();
ReverseComparator rc2 = new ReverseComparator(rc1);
ReverseComparator rc3 = new ReverseComparator(rc1);
// test same instance
assertTrue("Same instance wasn't equal", rc1.equals(rc1));
assertEquals("Equal instance has different hash code", rc1.hashCode(), rc1.hashCode());
// test null not equal
assertFalse("Null was equal", rc1.equals(null));
// test diff subcomparator not equal
assertFalse("Was equal despite different nested comparators", rc1.equals(rc2));
// test same subcomparator equal
assertTrue("Wasn't equal despite same nested comparator", rc2.equals(rc3));
assertEquals("Same subcomparator had different hash code", rc2.hashCode(), rc3.hashCode());
// test different type not equal
assertFalse("Was equal despite not being same class", rc1.equals(this));
}
}