[java] Java ArrayList for integers

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;

ArrayList<Integer[]> list = new ArrayList<>();
int x = 5
list.add(x);

But I'm unable to add anything to the ArrayList using this method. It works if I use Strings for the array list. Would I have to make it a String array and then somehow convert the array to integers?

EDIT: I have another question. I'd like the list to only hold 3 values. How would I do so?

This question is related to java arrays

The answer is


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<>();

Here there are two different concepts that are merged togather in your question.

First : Add Integer array into List. Code is as follows.

List<Integer[]> list = new ArrayList<>();
Integer[] intArray1 = new Integer[] {2, 4};
Integer[] intArray2 = new Integer[] {2, 5};
Integer[] intArray3 = new Integer[] {3, 3};
Collections.addAll(list, intArray1, intArray2, intArray3);

Second : Add integer value in list.

List<Integer> list = new ArrayList<>();
int x = 5
list.add(x);

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;
}

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.


you are not creating an arraylist for integers, but you are trying to create an arraylist for arrays of integers.

so if you want your code to work just put.

List<Integer> list = new ArrayList<>();
int x = 5;
list.add(x);

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.


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