1 package org.hamcrest.collection; 2 3 import org.hamcrest.Description; 4 import org.hamcrest.Matcher; 5 import org.hamcrest.Factory; 6 import org.hamcrest.TypeSafeMatcher; 7 import static org.hamcrest.core.IsEqual.equalTo; 8 9 public class IsArrayContaining<T> extends TypeSafeMatcher<T[]> { 10 11 private final Matcher<T> elementMatcher; 12 IsArrayContaining(Matcher<T> elementMatcher)13 public IsArrayContaining(Matcher<T> elementMatcher) { 14 this.elementMatcher = elementMatcher; 15 } 16 matchesSafely(T[] array)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 describeTo(Description description)26 public void describeTo(Description description) { 27 description 28 .appendText("an array containing ") 29 .appendDescriptionOf(elementMatcher); 30 } 31 32 @Factory hasItemInArray(Matcher<T> elementMatcher)33 public static <T> Matcher<T[]> hasItemInArray(Matcher<T> elementMatcher) { 34 return new IsArrayContaining<T>(elementMatcher); 35 } 36 37 @Factory hasItemInArray(T element)38 public static <T> Matcher<T[]> hasItemInArray(T element) { 39 return hasItemInArray(equalTo(element)); 40 } 41 42 } 43