如何用一个对象填充一半的arrayList,用java填充另一个对象的一半?

时间:2013-09-25 19:24:25

标签: java arraylist

我的目标是让用户输入一个数字N,并且arrayList的大小为2N + 1.

最终我的n = 2的arrayList应该是" OO XX"。

public Board(int size)
    {
        tiles = new ArrayList<Tile>(size);

        for(int index = 0; index < size; index++)
        {
            tiles.add(new Tile('O')); 
            tiles.add(new Tile(' '));
            tiles.add(new Tile('X')); 

            System.out.print(tiles.get(index));
        }          

    }

上面的代码给了我&#34; O XO&#34;。 如何修改它以显示OO XX?

提前致谢!

4 个答案:

答案 0 :(得分:4)

如果你想在一个循环中完成它,你可以这样做:

for (int i = 0 ; i != 2*size+1 ; i++) {
    tiles.add(new Tile(i==size ? ' ' : (i<size ? 'O' : 'X')));
}

想法是计算总大小(即2*size+1),然后使用条件来决定我们中点的哪一侧。

答案 1 :(得分:2)

您在one-arg ArrayList(int) constructor中传递的参数不是列表的固定大小。这只是初始容量。如果您的尺寸已修复,那么您可以使用数组:

Tile[] tiles = new Tile[2 * n + 1];

然后使用Arrays#fill(Object[] a, int fromIndex, int toIndex, Object val)方法填充数组非常简单:

Arrays.fill(tiles, 0, n, new Tile('O'));
tiles[n] = new Tile(' ');
Arrays.fill(tiles, (n + 1), (2 * n + 1), new Tile('X'));

尽管如注释中所述,这将填充数组索引并引用同一对象。可以使用不可变的Tile正常工作,但不能使用可变的。{/ p>

答案 2 :(得分:1)

您对tiles的初始化很好,但其余逻辑需要一些工作。

for(int index = 0; index < size; index++) {
  tiles.add(new Tile('O')); 
}
tiles.add(new Tile(' ')); 
for (int index = 0; index < size; index++) {
  tiles.add(new Tile('X'));
}

或者,如果你觉得自己很可爱......

tiles.addAll(Collections.nCopies(size, new Tile('O')));
tiles.add(new Tile(' '));
tiles.addAll(Collections.nCopies(size, new Tile('X')));

...如果您希望稍后修改Tile个对象,那么该版本可能会出现问题。

答案 3 :(得分:1)

试试这个:

// it's not necessary to specify the initial capacity,
// but this is the correct way to do it for this problem
tiles = new ArrayList<Tile>(2*size + 1);

// first add all the 'O'
for (int index = 0; index < size; index++)
    tiles.add(new Tile('O'));
// add the ' '
tiles.add(new Tile(' '));
// finally add all the 'X'
for (int index = 0; index < size; index++)
    tiles.add(new Tile('X'));

// verify the result, for size=2
System.out.println(tiles);
=> [O, O,  , X, X]