-1

我对 for 循环有以下方法。我担心这样做会导致内存泄漏。我的问题:对于 for 循环中的每个循环,该newInstance()方法是否会分配新的内存块?如果是这样,我是否应该VehicleImpl在进入 for 循环之前创建一个实例并尝试为此VehicleImpl实例设置新值。

private List<VehicleImpl> setVehicles(JsonInput input) {
    List<VehicleImpl> vehicles = new ArrayList<VehicleImpl>();

    Break lunch = Break.Builder.newInstance("Lunch")
            //timewindow(start time, end time), so lunch timewindow(start, start + duration)
            .setTimeWindow(TimeWindow.newInstance(input.getLunch().getStart(),
                    input.getLunch().getStart() + input.getLunch().getDuration()))
            //Lunch has highest priority
            .setPriority(1)
            //Lunch takes serviceTime
            .setServiceTime(input.getLunch().getDuration())
            .build();

    VehicleType type =  VehicleTypeImpl.Builder.newInstance("vehicleType")
            .setCostPerDistance(input.getCosts().getCostPerMeter())
            .setCostPerTransportTime(input.getCosts().getCostPerTransportSecond())
            .setCostPerServiceTime(input.getCosts().getCostPerServiceTime())
            .build();

    for(int i = 0; i < input.getNoVehicles(); i++) {
                                                //Name vehicle by index
        VehicleImpl vehicle = VehicleImpl.Builder.newInstance("vehicle " + String.valueOf(i+1))
                //The first location - depot location is indexed as 0 in Matrices
                .setStartLocation(Location.newInstance(i))
                .setBreak(lunch)
                .setLatestArrival(input.getOperating())
                .setType(type)
                .build();
        vehicles.add(vehicle);
    }
    return vehicles;
}
4

1 回答 1

0

这里没有泄漏内存。在 for 循环的每次迭代中,只有一个临时引用变量被创建和销毁。您可以通过在 for 循环之前声明该变量来避免这种情况。

于 2017-11-29T09:11:29.570 回答