Oops Null Pointer

Java programming related

EasyMock Generic(ish) Collection Matcher

I wanted to check that a collection is basically the same as another without knowing the collection type. I can only really check that the same elements are present, like a basic set.

The code below is based on the code here but with generics where possible (the matches method is not generic in EasyMock 2.5):

private static class CollectionMatcher<T> implements IArgumentMatcher {
    private Collection<T> collection;
    private String notFound = "";

    public CollectionMatcher(Collection<T> collection) { this.collection = collection; }

    public static <T> Collection<T> collectionEq(Collection<T> collection) {
        reportMatcher(new CollectionMatcher<T>(collection));
        return null;

    public void appendTo(StringBuffer buffer) {
        buffer.append(notFound).append(" not found in {");
        String comma = "";
        for (Object o : collection) {
            comma = ",";

    public boolean matches(Object otherCollection) {
        if (!(otherCollection instanceof Collection)) return false;

        Collection<T> other = (Collection<T>) otherCollection;
        if (other.size() != collection.size()) return false; // Optionally check sizes
        for (T o : other) {
            if (!collection.contains(o)) {
                notFound = o.toString();
                return false;
        return true;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: