【问题标题】:it only in insert the last matrix in the linkedlist它仅在链表中插入最后一个矩阵
【发布时间】:2018-03-24 11:49:16
【问题描述】:

我想在 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   |

【问题讨论】:

  • 不清楚EmptyOther 类指的是什么。需要分享清晰易懂的方式或尝试重新构建您的问题

标签: java matrix linked-list add


【解决方案1】:

这是因为您的 Object 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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-11
    • 1970-01-01
    相关资源
    最近更新 更多