它仅在链表中插入最后一个矩阵

it only in insert the last matrix in the linkedlist

我想在 LinkedList 中插入许多包含许多对象的矩阵,例如 EmptyOther 但它只插入最后一个矩阵,请帮忙

public LinkedList<Object[][]> addMatrices()
{
    LinkedList<Object[][]> l=new LinkedList<>();
    Object[][] o=new Object[2][2];
    o[0][0]=new Empty(2);
    o[0][1]=new Other();    
    o[1][0]=new Empty(4);
    o[1][1]=new Empty(6);
    l.add(o);
    o[0][0]=new Empty(4);
    o[0][1]=new Other();    
    o[1][0]=new Empty(5);
    o[1][1]=new Empty(1);
    l.add(o);
    for(Object[][] oo:l)
    {

        for(int x=0;x<oo.length;x++){
            for(int y=0;y<oo[x].length;y++)
                {System.out.print("\t"+oo[x][y]+" ");
            System.out.print("\t|");}
            System.out.println(System.lineSeparator());
        }
        System.out.println(System.lineSeparator());
    }
    return l;
}

输出:

4   |   -1  |

5   |   1   |


4   |   -1  |

5   |   1   |

应该是这样的:

2   |   -1  |

4   |   6   |


4   |   -1  |

5   |   1   |

发生这种情况是因为您的对象 o 是通过引用 LinkedList l 添加的。所以你实际上覆盖了第一个添加的对象,看起来好像只添加了最后一个。

这样试试:

public LinkedList<Object[][]> addMatrices()
{
    LinkedList<Object[][]> l=new LinkedList<>();
    Object[][] o=new Object[2][2];
    o[0][0]=new Empty(2);
    o[0][1]=new Other();    
    o[1][0]=new Empty(4);
    o[1][1]=new Empty(6);
    l.add(o);

    Object[][] o2=new Object[2][2];
    o2[0][0]=new Empty(4);
    o2[0][1]=new Other();    
    o2[1][0]=new Empty(5);
    o2[1][1]=new Empty(1);
    l.add(o2);

    for(Object[][] oo:l)
    {

       for(int x=0;x<oo.length;x++){
           for(int y=0;y<oo[x].length;y++) {
               System.out.print("\t"+oo[x][y]+" ");
               System.out.print("\t|");}
               System.out.println(System.lineSeparator());
           }
           System.out.println(System.lineSeparator());
       }
    return l;
}