0

Calling stream() off a collection vs. calling stream() off a method that returns a collection has different behavior, and I don't understand why. Using instance.field.stream() works as expected; using instance.getField().stream() raises an error. The error seems to be saying that stream() can see that the elements are objects, but can't use their interface. Can anyone help me understand why this is?

The sample code:

class Collection {

    // I would prefer to make this private
    public ArrayList<Element> stuff = new ArrayList();

    public Collection (){
        stuff.add(new Element("Rabbit"));
        stuff.add(new Element("Pig"));
        stuff.add(new Element("Bear"));
    }

    public class Element {

        private String name;

        public Element(String value){
            name = value;
        }

        public void speak(){
            System.out.println(name);
        }
    }

    // the get method
    public ArrayList getCollection(){
        return stuff;
    }

}

public class Main {

    public static void main (String[] args){

        Collection foo = new Collection();

        // this works fine, prints rabbit, pig, bear
        foo.stuff.stream().forEach(el -> el.speak());

        // this raises exception "cannot find symbol"
        // "symbol: method speak()""
        // "location: variable el of type Object"
  foo.getCollection().stream().forEach(el -> el.speak());

    }
}
MYX
  • 1
  • 1

0 Answers0