是否可以在foreach循环中填充数组

时间:2015-09-05 07:10:57

标签: java arrays

我正在尝试使用名为ted的示例项填充一个subnetItems数组。我打开调试器,即使在存在for循环之后,看到数组中的项保持为null。我可以看到currentItem设置为等于ted,但它不会进入实际数组。我尝试在for循环中初始化currentItem以查看是否有帮助,但事实并非如此。

    int startHost = 0;
    int endHost = 0;
    int broadcast = 0;
    int subnetNumber = 0;
    String fullSubnetAddress = "Start address";
    String fullBroadcastAddress = "Broadcast Address";
    String fullStartHost = "startHost";
    String fullEndHost = "endHost";

    SubnetItem ted = new SubnetItem(subnetNumber, fullBroadcastAddress, fullStartHost, fullEndHost, fullBroadcastAddress);


    SubnetItem[] subnetArray = new SubnetItem[this.totalSubnets];

    for (SubnetItem currentSubnet : subnetArray)
    {
        currentSubnet = new SubnetItem();
        currentSubnet = ted;

    }

    System.out.println("Pause");

1 个答案:

答案 0 :(得分:4)

您不能使用foreach样式循环填充这样的数组。您需要使用带索引的旧样式循环:

for (int i = 0; i < subnetArray.length; i++) {
    subnetArray[i] = ted;
}

注意:这将在数组中的每个位置引用相同的对象。如果那不是您想要的,那么您必须为数组中的每个元素创建一个新的SubnetItem

for (int i = 0; i < subnetArray.length; i++) {
    subnetArray[i] = new SubnetItem(subnetNumber, fullBroadcastAddress, fullStartHost,
                                    fullEndHost, fullBroadcastAddress);
}