gpt4 book ai didi

Java varargs 要求不定数量的变量

转载 作者:行者123 更新时间:2023-11-30 07:37:00 26 4
gpt4 key购买 nike

我正在尝试应用可变参数。我已经声明了一个需要无限数量变量的方法,如下所示:

private Subject carMonitor;

public AdvancedMonitor(Subject ... carMonitors){
for (Subject carMonitor : carMonitors){
this.carMonitor = carMonitor;
carMonitor.registerObserver(this);
}
}

但是,当我尝试在主方法中调用它时,除了一个参数之外我无法使用任何其他参数:

    BigCar bigCar = new BigCar();
SmallCar smallCar = new SmallCar();
AdvancedMonitor doubleAdvancedDisplay1 = new AdvancedMonitor();
AdvancedMonitor doubleAdvancedDisplay2 = new AdvancedMonitor(bigCar);
AdvancedMonitor doubleAdvancedDisplay3 = new AdvancedMonitor(bigCar, smallCar);

只有第二个有效。这是为什么?

enter image description here

与我的界面有关吗?

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

在我看来,都正确。你的情况有什么问题吗?您使用 loggingSystem.out.println 来调试您的问题吗?看来您的问题不在于 Java varagrs,但在 carMonitor.registerObserver(this) 中出现了一些异常。

P.S. 另外,您知道每个 AdvancedMonitor 都只有一个变量 carMonitor 吗?并使用 new AdvancedMonitor(bigCar,smallCar); 结果你只有在 private String carMonitor; 中使用smallCar的AdvancedMonitor?

P.P.S. 在 construstor 中使用 this 也是个坏主意,因为运行 contrustor 时并没有真正创建对象。

关于Java varargs 要求不定数量的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35245437/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com