Shhua
Shhua

Reputation: 21

Java - ArrayList in object

I'm getting the following error:

cannot find symbol
                for(Component c : first.caseComponents){
                                       ^
  symbol:   variable caseComponents
  location: variable first of type Component

Here is my code:

import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
import java.lang.Iterable;
import java.util.LinkedList;
import java.util.Queue;


public class Composite extends Component implements Iterable<Component>{

    private List<Component> caseComponents = new ArrayList<Component>();

    public Composite(String nameIn, int weightIn) {
        super(nameIn, weightIn);
    }


    @Override
    public Iterator<Component> iterator(){
        return new CompIterator();
    }

    private class CompIterator implements Iterator{
        int index = 0;

        @Override
        public boolean hasNext(){
            if(index<caseComponents.size()){
                return true;
            }
            return false;
        }

        @Override
        public Object next() {
            if(this.hasNext()){
                return caseComponents.get(index++);
            }
            return null;
        }
    }


    public String breadthFirst() {
        Queue<Component> q = new LinkedList<Component>();
        StringBuilder stringRep = new StringBuilder();
        q.add(this);

        while(q.element()!=null){
            Component first = q.remove();
            System.out.println(first.name);
            if (first instanceof Composite){
                Composite comp = (Composite)first;
                for(Component c : comp.caseComponents){

                    q.add(c);
                }
            }


        }
    }

}

And also the Component.java file:

public abstract class Component {

    protected String name;
    protected int weight;

    public Component(String nameIn, int weightIn){
        this.name=nameIn;
        this.weight=weightIn;

    }

    public abstract int getWeight();    //abstract method.

    public abstract String toString();


}

It seems that my type casting does not work and the object comp is still seen as an instance of Component instead of Composite, which has a variable caseComponents. How can I fix this?

Upvotes: 1

Views: 83

Answers (1)

Thilo
Thilo

Reputation: 262474

You need to make the loop actually use the typecast:

if (first instanceof Composite){
    Composite comp = (Composite)first;
    // use "comp" here: 
    for(Component c : comp.caseComponents){
             q.add(c);
    }
}

In your code, comp was never actually used anywhere.

Upvotes: 1

Related Questions