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

时间:2020-05-13 21:36:32

标签: java android static-methods android-livedata utility

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

实用程序类:

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());

            }
        });

过去期和nextPeriod的值相同,为什么?

1 个答案:

答案 0 :(得分:1)

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

List<PeriodEntity> updated = past;

因此,updatedpast列表基本上是相同的列表。因此,无论何时修改updated,它也会更新past

为避免这种情况,请为ArrayList创建一个新的updated,然后在其中复制past的现有数据。

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