67

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].
Chetan Bhasin
  • 3,503
  • 1
  • 23
  • 36
amv
  • 671
  • 1
  • 5
  • 3
  • 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` and add your values: `arl.add(Integer.valueOf(1); ...` – hage May 07 '12 at 07: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. – Baxissimo Aug 09 '16 at 01:25

12 Answers12

84

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.

Raul Rene
  • 10,014
  • 9
  • 53
  • 75
25
  1. Use Arrays.toString( arl.get(0) ).

  2. arl.get(0)[1]

trutheality
  • 23,114
  • 6
  • 54
  • 68
25

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

Wahib Ul Haq
  • 4,185
  • 3
  • 44
  • 41
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!!

mtebong
  • 121
  • 1
  • 3
  • @SumitRamteke - your edits effectively made the post NOT be an answer to the question. – mtebong Nov 30 '17 at 22:30
  • 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 – Sumit Ramteke Dec 01 '17 at 09:02
  • This helped me. I was banging my head against wall trying to figure out why ArrayList a = new ArrayList() 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? – KANJICODER Jun 20 '18 at 00:58
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);
    }
Everyone
  • 2,366
  • 2
  • 26
  • 39
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));
}
mayo
  • 3,845
  • 1
  • 32
  • 42
Nour
  • 1,458
  • 1
  • 18
  • 27
  • He's asking for list-of-array-of-int, not a list-of-int. – Baxissimo Aug 09 '16 at 01:23
  • 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 )) – Nour Aug 09 '16 at 05:52
  • 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. – composerMike Jun 02 '18 at 07:44
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.

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.

Anshuman Kumar
  • 464
  • 1
  • 6
  • 20
0

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

System.out.println("Arraylist contains:"+Arrays.toString(arl.get(0)));
clemens
  • 16,716
  • 11
  • 50
  • 65
Rahul Naik
  • 105
  • 1
  • 9
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);
Maddy
  • 4,525
  • 4
  • 33
  • 53
GIGO
  • 68
  • 9
0

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

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.

Sha
  • 921
  • 17
  • 46