我正在尝试使用varargs。我已经声明了一个方法,该方法需要不确定数量的变量,例如:
private Subject carMonitor;
public AdvancedMonitor(Subject ... carMonitors){
for (Subject carMonitor : carMonitors){
this.carMonitor = carMonitor;
carMonitor.registerObserver(this);
}
}
但是,当我尝试在main方法中调用它时,除了一个参数外,我无法使用其他任何东西:
BigCar bigCar = new BigCar();
SmallCar smallCar = new SmallCar();
AdvancedMonitor doubleAdvancedDisplay1 = new AdvancedMonitor();
AdvancedMonitor doubleAdvancedDisplay2 = new AdvancedMonitor(bigCar);
AdvancedMonitor doubleAdvancedDisplay3 = new AdvancedMonitor(bigCar, smallCar);
仅第二个有效。为什么是这样?
与我的界面有关吗?
public interface Subject {
public void registerObserver(Observer o);
public void removeObserver(Observer o);
public void notifyObservers();
}
大型汽车界面-小型汽车目前大致相同:
public class BigCar implements Subject {
private ArrayList observers;
private int state;
public BigCar(){
observers = new ArrayList();
}
public void registerObserver(Observer o){
observers.add(o);
}
public void removeObserver(Observer o){
int i = observers.indexOf(o);
if (i >= 0){
observers.remove(i);
}
}
public void notifyObservers(){
for (int i = 0; i < observers.size(); i++){
Observer observer = (Observer)observers.get(i);
observer.update(state);
}
}
public void stateChanged() {
notifyObservers();
}
public void setState(int state){
this.state = state;
stateChanged();
}
}
最佳答案
我写以下代码:
public class Test {
public static class AdvancedMonitor {
private String carMonitor;
public AdvancedMonitor(String... carMonitors) {
for (String carMonitor : carMonitors) {
this.carMonitor = carMonitor;
System.out.println(this.carMonitor);
}
}
}
public static void main(String[] args) {
String bigCar = "bigCar";
String smallCar = "smallCar";
System.out.println("step 1");
AdvancedMonitor doubleAdvancedDisplay1 = new AdvancedMonitor();
System.out.println();
System.out.println("step 2");
AdvancedMonitor doubleAdvancedDisplay2 = new AdvancedMonitor(bigCar);
System.out.println();
System.out.println("step 3");
AdvancedMonitor doubleAdvancedDisplay3 = new AdvancedMonitor(bigCar, smallCar);
}
}
我有以下结果:
step 1
step 2
bigCar
step 3
bigCar
smallCar
我认为,一切正确。您的情况有什么问题?您使用
logging
还是System.out.println
调试问题?看起来您的问题不是Java变量引起的,但carMonitor.registerObserver(this)
中有一些例外。附言另外,您了解每个AdvancedMonitor都只有一个可变的carMonitor吗?并使用
new AdvancedMonitor(bigCar, smallCar);
结果仅在private String carMonitor;
中具有smallCar的AdvancedMonitor?P.P.S.在construstor中使用
this
也是一个坏主意,因为在运行construstor时对象并不是真正创建的。