0

I want to iterate over an object implementing Collection.

class A implemets Collection{
    private final Collection p= new ArrayList();
    @Override
    public boolean add(Object e) {
        return p.add(e);
    }

    public void remove() { }
    //
}

In the main method, I added two Objects to the collection A.

A a = new A();
B b = new B();
B b1 = new B();
a.add(b);
a.add(b1);

I want to iterate over all the Bs in A using foreach. I used iterator and it worked but I specifically wanted to use foreach or enhanced for loop like:

a.foreach(eachB -> { eachB.getSomeValueFromGetterMethodInB(); })

But, its throwing me error "he method getSomeValueFromGetterMethodInB() is undefined for the type Object". Am I missing some basic concept here? Is it one of the limitations of foreach that I cannot iterate over Collection implementation? Any suggestions will be appreciated? Thanks

Siddharth Shankar
  • 489
  • 1
  • 10
  • 21
  • 1
    Your collection has raw types. The eachB is an Object and thus does not have the method you're calling on it. Use generics (or cast the element to the desired type). – Alowaniak Jul 22 '19 at 21:46

1 Answers1

2

You have to declare the Collection with the specific type of objects it'll contain:

private final Collection<B> p = new ArrayList<>();

And also, indicate the type you're using for implementing Collection:

class A implements Collection<B>

.. Which will also require an adjustment in the add() method:

public boolean add(B e) {
    return p.add(e);
}
Óscar López
  • 232,561
  • 37
  • 312
  • 386