用作参数的变量的静态方法更改值

Static method changing value of the variable used as an argument

我在 PredictionUtil class 中创建了一个静态方法,用于从较小的列表生成新列表。新更新的列表不仅被分配给新变量,还被分配给较小的列表。我无法理解这个问题。

实用程序class:

public class PredictionUtils {

    public static List<PeriodEntity> predictPeriods(List<PeriodEntity> past){
        List<PeriodEntity> updated = past;
        if(past == null){
            return null;
        }
        int pastsize = past.size();
        long currentcycledur = generateCurrentCycleDuration(past);
        long currentperioddur = generateCurrentPeriodDuration(past);
        long laststartdate = past.get(pastsize-1).getStartTimestamp();
        for(int i = 1;i <= 20;i++){
            updated.add(new PeriodEntity(laststartdate+(currentcycledur*i),laststartdate+(currentcycledur*i)+currentperioddur));
        }
        return updated;
    }

    public static long generateCurrentCycleDuration(List<PeriodEntity> past){
        long cycleduration = 0L;
        long diff;
        int pastsize = past.size();

        if(pastsize == 1){
            return cycleduration = 2419200000L;
        }

        if(pastsize < 5) {
            for (int i = 0; i < pastsize - 1; i++) {
                diff = past.get(i + 1).getStartTimestamp() - past.get(i).getStartTimestamp();
                cycleduration += diff;
            }
            return (cycleduration/(pastsize-1));
        }else{
            for (int i = pastsize-1;i >= pastsize-4;i--) {
                diff = past.get(i).getStartTimestamp() - past.get(i-1).getStartTimestamp();
                cycleduration += diff;
            }
            return (cycleduration/4);
        }
    }

    public static long generateCurrentPeriodDuration(List<PeriodEntity> past){
        long periodduration = 0L;
        long diff;
        int pastsize = past.size();

        if(pastsize < 4){
            for(int i = 0;i < pastsize;i++){
                diff = past.get(i).getEndTimestamp()-past.get(i).getStartTimestamp();
                periodduration += diff;
            }
            return (periodduration/pastsize);
        }else{
            for(int i = pastsize-1;i >= pastsize-4;i--){
                diff = past.get(i).getEndTimestamp()-past.get(i).getStartTimestamp();
                periodduration += diff;
            }
            return (periodduration/4);
        }
    }
}

它的用途:

//Observable LiveData Elements
        calendarViewModel.getPastPeriods().observe(getViewLifecycleOwner(), new Observer<List<PeriodEntity>>() {
            @Override
            public void onChanged(final List<PeriodEntity> pastperiods) {

                nextPeriod = PredictionUtils.predictPeriods(pastperiods).get(pastperiods.size());

            }
        });

pastperiods和nextPeriod的值相同,为什么?

您不是在创建 List 的新实例,而是在引用输入。

List<PeriodEntity> updated = past;

因此,updatedpast 列表基本上是相同的列表。因此,每当您修改 updated 时,它也会更新 past.

为避免这种情况,为 updated 创建一个新的 ArrayList 并将 past 的现有数据复制到那里。

List<PeriodEntity> updated = new ArrayList<>(past);