Home | History | Annotate | Download | only in collection
      1 package org.hamcrest.collection;
      2 
      3 import java.util.Arrays;
      4 
      5 import org.hamcrest.Description;
      6 import org.hamcrest.Matcher;
      7 import org.hamcrest.TypeSafeMatcher;
      8 
      9 public class IsArray<T> extends TypeSafeMatcher<T[]> {
     10     private final Matcher<T>[] elementMatchers;
     11 
     12     public IsArray(Matcher<T>[] elementMatchers) {
     13         this.elementMatchers = elementMatchers.clone();
     14     }
     15 
     16     public boolean matchesSafely(T[] array) {
     17         if (array.length != elementMatchers.length) return false;
     18 
     19         for (int i = 0; i < array.length; i++) {
     20             if (!elementMatchers[i].matches(array[i])) return false;
     21         }
     22 
     23         return true;
     24     }
     25 
     26     public void describeTo(Description description) {
     27         description.appendList(descriptionStart(), descriptionSeparator(), descriptionEnd(),
     28                                Arrays.asList(elementMatchers));
     29     }
     30 
     31     /**
     32      * Returns the string that starts the description.
     33      *
     34      * Can be overridden in subclasses to customise how the matcher is
     35      * described.
     36      */
     37     protected String descriptionStart() {
     38         return "[";
     39     }
     40 
     41     /**
     42      * Returns the string that separates the elements in the description.
     43      *
     44      * Can be overridden in subclasses to customise how the matcher is
     45      * described.
     46      */
     47     protected String descriptionSeparator() {
     48         return ", ";
     49     }
     50 
     51     /**
     52      * Returns the string that ends the description.
     53      *
     54      * Can be overridden in subclasses to customise how the matcher is
     55      * described.
     56      */
     57     protected String descriptionEnd() {
     58         return "]";
     59     }
     60 
     61     public static <T> IsArray<T> array(Matcher<T>... elementMatchers) {
     62         return new IsArray<T>(elementMatchers);
     63     }
     64 }
     65