我收到以下错误:
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/