Я получаю следующее сообщение об ошибке:Java - ArrayList в объекте
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. Как я могу это исправить?
Ваше сообщение об ошибке не соответствует опубликованному коду, у которого нет 'for (Component c: first.caseComponents) {' line. –
@NathanTuggy: Он был там. Теперь отредактирован до фиксированной версии. Не знаю, о чем сейчас вопрос .... – Thilo