Adding integers to an int array

前端 未结 7 847
我在风中等你
我在风中等你 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:23

    You cannot use the add method on an array in Java.

    To add things to the array do it like this

    public static void main(String[] args) {
    int[] num = new int[args.length];
    for (int i = 0; i < args.length; i++){
        int neki = Integer.parseInt(s);
        num[i] = neki;
    
    }
    

    If you really want to use an add() method, then consider using an ArrayList instead. This has several advantages - for instance it isn't restricted to a maximum size set upon creation. You can keep adding elements indefinitely. However it isn't quite as fast as an array, so if you really want performance stick with the array. Also it requires you to use Integer object instead of primitive int types, which can cause problems.

    ArrayList Example

    public static void main(String[] args) {
        ArrayList num = new ArrayList();
        for (String s : args){
            Integer neki = new Integer(Integer.parseInt(s));
            num.add(s);
    }
    

提交回复
热议问题