assassinsweed1
assassinsweed1

Reputation: 47

Converting ArrayList<Integer> into int[] won't work in Java

I have been developing a program where I have to convert an ArrayList into an int[]. I do not get any syntax errors when I run the code. However, when I print the int[] to see if it does work, it prints out a random string which is "[I@2a139a55" How can I fix this?

I cannot use an int[] from the start. This program HAS to convert an ArrayList into int[].

        ArrayList<Integer> student_id = new ArrayList<Integer>();
       student_id.add(6666);
       student_id.add(7888);    

       int[] student_id_array = new int[student_id.size()];
       for (int i=0, len = student_id.size(); i < len; i ++){
            student_id_array[i] = student_id.get(i);
       }
       System.out.println(student_id_array);

Upvotes: 0

Views: 4262

Answers (3)

DimaSan
DimaSan

Reputation: 12684

You can do the converting your ArrayList<Integer> to int[] with one line in Java 8:

int[] student_id_array = student_id.stream().mapToInt(id -> id).toArray();

And if you want to output array's values instead of representation of your array (like [I@2a139a55) use Arrays.toString() method:

System.out.println(Arrays.toString(student_id_array));

Upvotes: 1

thetraveller
thetraveller

Reputation: 445

That because you are printing the memory address of that array.

try this :

   ArrayList<Integer> student_id = new ArrayList<Integer>();
   student_id.add(6666);
   student_id.add(7888);    

   int[] student_id_array = new int[student_id.size()];
   for (int i=0, len = student_id.size(); i < len; i ++){
        student_id_array[i] = student_id.get(i);
   }
   System.out.println(student_id_array[0]+" "+student_id_array[1]);

Output :

6666 7888

OR use for-loop if you populate the ArrayList later on.

Upvotes: 0

Aly
Aly

Reputation: 925

You are printing out the reference to the array. Use Arrays.toString(int[]).

Upvotes: 1

Related Questions