Java - 对象中的ArrayList

标签 java types

我收到以下错误:

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

这是我的代码:

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


        }
    }

}

还有 Component.java 文件:

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


}

看来我的类型转换不起作用,并且对象 comp 仍然被视为 Component 的实例,而不是 Composite,这有一个变量 caseComponents。我该如何解决这个问题?

最佳答案

您需要使循环实际使用类型转换:

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

在您的代码中,comp 从未在任何地方实际使用过。

关于Java - 对象中的ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30203347/

相关文章:

java - 我应该使用 RoboGuice 还是其他依赖注入(inject)框架?

java - Google App Engine 退回通知不起作用

java - Spring Boot - @Async 被忽略

java - jackson JSON : Serialize Array of Objects as their parent type

java - 从 JAXB (WebService) 生成 XML 时出错

haskell - 如何在 GHCI 中查找多个导入方法的类型签名

C++ 相互递归变体类型

java - 在 Java SE6 中使用 <?> 进行模板化有什么作用?

javascript - Typescript:类型 '{}' 无法分配给类型 'Pick<T, K>' ,如何正确键入 javascript `pick` 函数?

python - 如何使用 ctypes 访问返回在 Delphi dll 中编码的自定义类型的函数?