Adding integers to an int array

前端 未结 7 862
我在风中等你
我在风中等你 2021-02-05 01:57

I am trying to add integers into an int array, but Eclipse says:

cannot invoke add(int) on the array type int[]

Which is completely

7条回答
  •  终归单人心
    2021-02-05 02:14

    An array has a fixed length. You cannot 'add' to it. You define at the start how long it will be.

    int[] num = new int[5];
    

    This creates an array of integers which has 5 'buckets'. Each bucket contains 1 integer. To begin with these will all be 0.

    num[0] = 1;
    num[1] = 2;
    

    The two lines above set the first and second values of the array to 1 and 2. Now your array looks like this:

    [1,2,0,0,0]
    

    As you can see you set values in it, you don't add them to the end.

    If you want to be able to create a list of numbers which you add to, you should use ArrayList.

提交回复
热议问题