首页 > 解决方案 > 在Java中将状态和支出历史存储为列表的最佳方法是什么

问题描述

我的存储历史列表有问题。

基本上我有细胞矩阵,每个细胞都有状态、支出和历史。历史是一个包含可验证char state和的对象double payout,但是我在引用方面有很多问题。当我试图复制整个历史时,会创建一些我不知道如何处理的参考。

让我向您展示代码(我知道将两个对象作为一个单元格的复制方式很愚蠢,但我正在尝试一切可能的方法来摆脱这些引用):

public class Cell {

    public char state;
    public double payout;
    
    public class History{

        public char state='E';
        public double result;
        
        public History (char state, double result)
        {
            this.state=state;
            this.result=result;
        }
        public History (History history)
        {
            this.state=history.state;
            this.result=history.result;
        }
        public char getState()
        {
            return state;
        }
        public double getResult()
        {
            return result;
        }
    }


    public LinkedList<History> history;

    public Cell (Settings settings)
    {
        this.state=settings.state;
        this.payout=0;
        history= new LinkedList<History>();
    }
    public void copyCell ( Cell dest, Cell temp)
    {
        dest.state=temp.state;
        dest.payout=temp.payout;
        
        dest.history= new LinkedList<History>();
        
        for (int i =0; i<temp.history.size(); i++)
        {
            double result1=temp.history.get(i).result;
            char state1=temp.history.get(i).state;
            
            dest.history.add(new History (state1,result1));
        }
    }
}

我做错了什么?我想我不知道复制变量和引用对象之间的区别。有人可以解释一下吗?

标签: java

解决方案


关于存储历史支出的最佳方式,我将执行以下操作:

您需要 3 个组件 -和time数量。stateresult

  1. 需要时间,因此您可以按照自己喜欢的方式对历史记录进行排序,并可以从数据库中按照指定的顺序加载它。
  2. 我会使用linkedlist,因为它保持插入顺序
  3. 只需克隆整个列表即可轻松克隆历史 List<History> cloned = new LinkedList<>(oldList);

推荐阅读