Java的。更改ArrayList中内部数组的值

时间:2017-06-19 21:16:14

标签: java arrays arraylist

我是Java的新手。我正在尝试为简单的蛇游戏创建数据结构设计。我决定有一个动态大小的数组ArrayList,它包含整数,表示蛇“身体”的X和Y.我有一个非常庞大的解决方案(使用高级for循环)来解决在内部数组中设置新值的问题。

class ArrayListOfArrays {
    public static void main(String[] args) {

        // create an arraylist
        List<int[]> arrList = new ArrayList<>();

        // populate an arraylist
        arrList.add(new int[]{1, 2});
        arrList.add(new int[]{4, 5});

        // print arraylist before changing
        System.out.println("The value before changing: " + arrList.get(0)[0]); // prints 1

        // This is what I have come up with.
        // the loop changes the values of the first array in a given arraylist
        int i = 0;
        for (int[] intArray: arrList) {         
            if (i == 0) {
                intArray[0] = 9;
                intArray[1] = 8;                
            }
            i++;
            break;
        }


        // print arraylist after changing
        System.out.println("The value after changing: " + arrList.get(0)[0]); // prints 9
    }
}

是否有更短的解决方案来更改ArrayList内部数组中的值?类似的东西:

arrList.set(0, int[]{9, 8});

提前致谢!我将不胜感激任何帮助!

2 个答案:

答案 0 :(得分:0)

您可以使用=符号将新值设置为数组。如果你在ArrayList内有数组,你必须先得到它:

arrList.get(0)[0] = 9;

完整代码:

// create an arraylist
        List<int[]> arrList = new ArrayList<>();

        // populate an arraylist
        arrList.add(new int[] { 1, 2 });
        arrList.add(new int[] { 4, 5 });

        // print arraylist before changing
        System.out.println("The value before changing: " + arrList.get(0)[0]); // prints
                                                                                // 1

        arrList.get(0)[0] = 9;
        System.out.println("The value after changing: " + arrList.get(0)[0]); // prints
        // This is what I have come up with.
        // the loop changes the values of the first array in a given arraylist
        int[] is = arrList.get(0);
        for (int i = 0; i < is.length; i++) {
            is[i] = i * i;
        }

        // print arraylist after changing
        System.out.println("The value after changing: " + arrList.get(0)[0]); // prints
                                                                                // 9

答案 1 :(得分:0)

而不是数组更好地创建代表你蛇的一段的Segment类。这样的事情:

 public class Segment {
        private int x;
        private int y;

        public Segment (int x, int y) {
            this.x = x;
            this.y = y;
        }

        public void setNewPosition(int x, int y) {
            this.x = x;
            this.y = y;
        }
    }

这门课你很简单:

for (Segment segment : segments) {
     segment.setNewPosition(x, y);
}

P.S。在那之后你可能决定创建包含Snake实例序列的类Segment(现在将列表提供给类Snake),顺便说一句,这取决于游戏的逻辑,会有什么方法出现在Snake班。