68

I'm new to the concept of arraylist. I've made a short program that is as follows:

ArrayList<int[]> arl=new ArrayList<int[]>();
int a1[]={1,2,3};
arl.add(0,a1);
System.out.println("Arraylist contains:"+arl.get(0));

It gives the output: Arraylist contains:[I@3e25a5

Now my questions are:

  1. How to display the correct value i.e. 1 2 3.
  2. How can I access the single element of array a1 i.e. if I want to know the value at a1[1].
2
  • 3
    Just to note: ArrayList doesn't mean "List of Arrays" but rather a list that uses an array internally. So you could use ArrayList<Integer> and add your values: arl.add(Integer.valueOf(1); ... Commented May 7, 2012 at 7:26
  • 1
    I interpret the question as desiring a list-of-array-of-integer. It seems pretty explicit about that. They are trying to get(0) and expecting that value to be [1,2,3]. Most of the answers seem to be answering the wrong question. Commented Aug 9, 2016 at 1:25

12 Answers 12

85

First of all, for initializing a container you cannot use a primitive type (i.e. int; you can use int[] but as you want just an array of integers, I see no use in that). Instead, you should use Integer, as follows:

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

For adding elements, just use the add function:

arl.add(1);  
arl.add(22);
arl.add(-2);

Last, but not least, for printing the ArrayList you may use the build-in functionality of toString():

System.out.println("Arraylist contains: " + arl.toString());  

If you want to access the i element, where i is an index from 0 to the length of the array-1, you can do a :

int i = 0; // Index 0 is of the first element
System.out.println("The first element is: " + arl.get(i));

I suggest reading first on Java Containers, before starting to work with them.

Sign up to request clarification or add additional context in comments.

Comments

26

More simple than that.

List<Integer> arrayIntegers = new ArrayList<>(Arrays.asList(1,2,3));

arrayIntegers.get(1);

In the first line you create the object and in the constructor you pass an array parameter to List.

In the second line you have all the methods of the List class: .get (...)

1 Comment

Note: this doesn't work if you trying to convert an int[] to a List<Integer>
25
  1. Use Arrays.toString( arl.get(0) ).

  2. arl.get(0)[1]

1 Comment

And answering question 2: arl.get(0)[i]
9

The setup:

    List<int[]> intArrays=new ArrayList<>();
    int anExample[]={1,2,3};
    intArrays.add(anExample);

To retrieve a single int[] array in the ArrayList by index:

    int[] anIntArray = intArrays.get(0); //'0' is the index
    //iterate the retrieved array an print the individual elements
    for (int aNumber : anIntArray ) { 
        System.out.println("Arraylist contains:" + aNumber );
    }

To retrieve all int[] arrays in the ArrayList:

    //iterate the ArrayList, get and print the elements of each int[] array  
    for(int[] anIntArray:intArrays) {
       //iterate the retrieved array an print the individual elements
       for (int aNumber : anIntArray) {
           System.out.println("Arraylist contains:" + aNumber);
       }
}

Output formatting can be performed based on this logic. Goodluck!!

3 Comments

@SumitRamteke - your edits effectively made the post NOT be an answer to the question.
I am sorry if it felt in that way. I hope you've disapproved my edit, though its anyway individual way of looking the solution. I have made changes in way to make it understand what you written is correct but in generic way. Just following community practise, don't take it otherwise
This helped me. I was banging my head against wall trying to figure out why ArrayList<long[2]> a = new ArrayList<long[2]>() Does not work. I find the Java syntax convoluted. I guess java considers long[1], long[2], long[3] to all be the same type?
5

In java, an array is an object. Therefore the call to arl.get(0) returns a primitive int[] object which appears as ascii in your call to System.out.

The answer to your first question is therefore

System.out.println("Arraylist contains:"+Arrays.toString( arl.get( 0 ) ) );

If you're looking for particular elements, the returned int[] object must be referenced as such. The answer to your second question would be something like

    int[] contentFromList = arl.get(0);
    for (int i = 0; i < contentFromList.length; i++) {
        int j = contentFromList[i];
        System.out.println("Value at index - "+i+" is :"+j);
    }

Comments

4

You have to use <Integer> instead of <int>:

int a1[] = {1,2,3};
ArrayList<Integer> arl=new ArrayList<Integer>();
for(int i : a1) {
    arl.add(i);        
    System.out.println("Arraylist contains:" + arl.get(0));
}

3 Comments

He's asking for list-of-array-of-int, not a list-of-int.
But if you read his questions you'd understand that he was new and was just trying to get the list of int and get the values by accessing specific indexes ))
I read it and it seems pretty clear he wants list-of-array-of-int. He is differentiating between arl[0] and a1[0] for example.
2

Everyone is right. You can't print an int[] object out directly, but there's also no need to not use an ArrayList of integer arrays.

Using,

Arrays.toString(arl.get(0))

means splitting the String object into a substring if you want to insert anything in between, such as commas.

Here's what I think amv was looking for from an int array viewpoint.

System.out.println("Arraylist contains: " 
    + arl.get(0)[0] + ", " 
    + arl.get(0)[1] + ", " 
    + arl.get(0)[2]);

This answer is a little late for amv but still may be useful to others.

Comments

1

For the more inexperienced, I have decided to add an example to demonstrate how to input and output an ArrayList of Integer arrays based on this question here.

    ArrayList<Integer[]> arrayList = new ArrayList<Integer[]>();
    while(n > 0)
    {
        int d = scan.nextInt();
       Integer temp[] = new Integer[d];
        for (int i = 0 ; i < d ; i++)
        {
            int t = scan.nextInt();
            temp[i]=Integer.valueOf(t);
        }
        arrayList.add(temp);
        n--;
    }//n is the size of the ArrayList that has been taken as a user input & d is the size 
    //of each individual array.

     //to print something  out from this ArrayList, we take in two 
    // values,index and index1 which is the number of the line we want and 
    // and the position of the element within that line (since the question
    // followed a 1-based numbering scheme, I did not change it here)

    System.out.println(Integer.valueOf(arrayList.get(index-1)[index1-1]));

Thanks to this answer on this question here, I got the correct answer. I believe this satisfactorily answers OP's question, albeit a little late and can serve as an explanation for those with less experience.

Comments

0

java.util.Arrays.toString() converts Java arrays to a string:

System.out.println("Arraylist contains:"+Arrays.toString(arl.get(0)));

Comments

0
ArrayList<Integer> list = new ArrayList<>();
int number, total = 0;

for(int i = 0; i <= list.size(); i++){
    System.out.println("Enter number " + (i + 1) + " or enter -1 to end: ");
    number = input.nextInt();

    list.add(number);

    if(number == -1){
        list.remove(list.size() - 1);
        break;
    }
}
System.out.println(list.toString());

for(int i: list){
    System.out.print(i + "  ");
    total+= i;
}
System.out.println();
System.out.println("The sum of the array content is: " + total);

Comments

0

Integer is wrapper class and int is primitive data type.Always prefer using Integer in ArrayList.

Comments

0
List<Integer> integerList = IntStream.range(0,100)
   .boxed()
   .toList();

This is one of the ways, you can initialize the fixed size ArrayList in Java using Java8+ - Stream API. integerList is going to contain integer values from 0 to 99.

1 Comment

Your response does not answer the question. Consider removal.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.