Java ArrayList for integers

前端 未结 8 1174
陌清茗
陌清茗 2020-12-11 00:24

I have values that I\'d like to add into an ArrayList to keep track of what numbers have shown up. The values are integers so I created an ArrayList;

ArrayLi         


        
相关标签:
8条回答
  • 2020-12-11 01:03

    you should not use Integer[] array inside the list as arraylist itself is a kind of array. Just leave the [] and it should work

    0 讨论(0)
  • 2020-12-11 01:03

    Actually what u did is also not wrong your declaration is right . With your declaration JVM will create a ArrayList of integer arrays i.e each entry in arraylist correspond to an integer array hence your add function should pass a integer array as a parameter.

    For Ex:

    list.add(new Integer[3]);
    

    In this way first entry of ArrayList is an integer array which can hold at max 3 values.

    0 讨论(0)
  • 2020-12-11 01:10

    The [] makes no sense in the moment of making an ArrayList of Integers because I imagine you just want to add Integer values. Just use

    List<Integer> list = new ArrayList<>();
    

    to create the ArrayList and it will work.

    0 讨论(0)
  • 2020-12-11 01:14

    You are trying to add an integer into an ArrayList that takes an array of integers Integer[]. It should be

    ArrayList<Integer> list = new ArrayList<>();
    

    or better

    List<Integer> list = new ArrayList<>();
    
    0 讨论(0)
  • 2020-12-11 01:14

    How about creating an ArrayList of a set amount of Integers?

    The below method returns an ArrayList of a set amount of Integers.

    public static ArrayList<Integer> createRandomList(int sizeParameter)
    {
        // An ArrayList that method returns
        ArrayList<Integer> setIntegerList = new ArrayList<Integer>(sizeParameter);
        // Random Object helper
        Random randomHelper = new Random();
        
        for (int x = 0; x < sizeParameter; x++)
        {
            setIntegerList.add(randomHelper.nextInt());
        }   // End of the for loop
        
        return setIntegerList;
    }
    
    0 讨论(0)
  • 2020-12-11 01:18

    List of Integer.

    List<Integer> list = new ArrayList<>();
    int x = 5;
    list.add(x);
    
    0 讨论(0)
提交回复
热议问题