我想在 LinkedList 中插入许多充满许多对象的矩阵,例如Empty
和Other
但它只插入最后一个矩阵,请帮忙
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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句