1package org.hamcrest.collection; 2 3import org.hamcrest.Description; 4import org.hamcrest.Matcher; 5import org.hamcrest.Factory; 6import org.hamcrest.TypeSafeMatcher; 7import static org.hamcrest.core.IsEqual.equalTo; 8 9public class IsArrayContaining<T> extends TypeSafeMatcher<T[]> { 10 11 private final Matcher<T> elementMatcher; 12 13 public IsArrayContaining(Matcher<T> elementMatcher) { 14 this.elementMatcher = elementMatcher; 15 } 16 17 public boolean matchesSafely(T[] array) { 18 for (T item : array) { 19 if (elementMatcher.matches(item)) { 20 return true; 21 } 22 } 23 return false; 24 } 25 26 public void describeTo(Description description) { 27 description 28 .appendText("an array containing ") 29 .appendDescriptionOf(elementMatcher); 30 } 31 32 @Factory 33 public static <T> Matcher<T[]> hasItemInArray(Matcher<T> elementMatcher) { 34 return new IsArrayContaining<T>(elementMatcher); 35 } 36 37 @Factory 38 public static <T> Matcher<T[]> hasItemInArray(T element) { 39 return hasItemInArray(equalTo(element)); 40 } 41 42} 43