Home | History | Annotate | Download | only in collect
      1 /*
      2  * Copyright (C) 2007 The Guava Authors
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  * http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 package com.google.common.collect;
     18 
     19 import com.google.common.annotations.GwtCompatible;
     20 
     21 import java.io.Serializable;
     22 import java.util.Iterator;
     23 
     24 import javax.annotation.Nullable;
     25 
     26 /**
     27  * An ordering which sorts iterables by comparing corresponding elements
     28  * pairwise.
     29  */
     30 @GwtCompatible(serializable = true)
     31 final class LexicographicalOrdering<T>
     32     extends Ordering<Iterable<T>> implements Serializable {
     33   final Ordering<? super T> elementOrder;
     34 
     35   LexicographicalOrdering(Ordering<? super T> elementOrder) {
     36     this.elementOrder = elementOrder;
     37   }
     38 
     39   @Override public int compare(
     40       Iterable<T> leftIterable, Iterable<T> rightIterable) {
     41     Iterator<T> left = leftIterable.iterator();
     42     Iterator<T> right = rightIterable.iterator();
     43     while (left.hasNext()) {
     44       if (!right.hasNext()) {
     45         return LEFT_IS_GREATER; // because it's longer
     46       }
     47       int result = elementOrder.compare(left.next(), right.next());
     48       if (result != 0) {
     49         return result;
     50       }
     51     }
     52     if (right.hasNext()) {
     53       return RIGHT_IS_GREATER; // because it's longer
     54     }
     55     return 0;
     56   }
     57 
     58   @Override public boolean equals(@Nullable Object object) {
     59     if (object == this) {
     60       return true;
     61     }
     62     if (object instanceof LexicographicalOrdering) {
     63       LexicographicalOrdering<?> that = (LexicographicalOrdering<?>) object;
     64       return this.elementOrder.equals(that.elementOrder);
     65     }
     66     return false;
     67   }
     68 
     69   @Override public int hashCode() {
     70     return elementOrder.hashCode() ^ 2075626741; // meaningless
     71   }
     72 
     73   @Override public String toString() {
     74     return elementOrder + ".lexicographical()";
     75   }
     76 
     77   private static final long serialVersionUID = 0;
     78 }
     79