2

I want to call a method using a collection of objects that all implement the same interface. Is this possible?

public class GenericsTest {
    public void main() {
        ArrayList<Strange> thisWorks = new ArrayList<>();
        isAllStrange(thisWorks);
        ArrayList<Person> thisDoesNot = new ArrayList<>();
        isAllStrange(thisDoesNot);
    }

    public boolean isAllStrange(ArrayList<Strange> strangeCollection) {
        for (Strange object : strangeCollection) {
            if (object.isStrange())
                return true;
        }
        return false;
    }

    public interface Strange {
        public boolean isStrange();
    }

    public class Person implements Strange {
        public boolean isStrange() {
            return true;
        }
    }
}
Trevor Allred
  • 888
  • 2
  • 13
  • 22

2 Answers2

5

You can do this using the <? extends Interface> notation:

public boolean isAllStrange(List<? extends Strange> strangeCollection) {
    for (Strange object : strangeCollection) {
        if (object.isStrange())
            return true;
    }
    return false;
}

Also, do not use ArrayList directly, instead use List. More of this:

Community
  • 1
  • 1
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
1

Read about WildCard in Genrics.

You can do this using

<? extends Strange >
vikiiii
  • 9,246
  • 9
  • 49
  • 68