Java ArrayList for integers

2020-02-06 05:23发布

问题:

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?

回答1:

List of Integer.

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


回答2:

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


回答3:

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


回答4:

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



回答5:

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.



回答6:

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.



回答7:

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


标签: java arrays