Search code examples
javaiteratorcompositeiterable

Java - How to check if an object is an instance of a class in the class definition


Code:

public class Composite extends Component implements Iterable<Component>{

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


    @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);

            for(Component c : first.caseComponents){
                q.add(c);
            }
        }
    }

I'm trying to do a breadth first print of a tree of the Composite design pattern. I have declared a method that is supposed to be called by the "root" of the tree. In the tree, there will be objects of the classes Composite and Leaf. These both inherit from Component, but are of course different. Composite is a container objects as well as an object itself, while Leaf is just one object. I want to change my code so that the line for(Component c : first.caseComponents) is only executed if first is an instance of Composite, otherwise it would try to iterate over a Leaf which is not possible. How can I make it so that the for statement is only entered if first is a Composite?


Solution

  • Use instanceof to check if comp is an instance of Composite.

    eg:

    if (comp instanceof Composite) { 
        //do something
    }