0

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);
  • You cannot print an array directly. You have to use `System.out.println(java.util.Arrays.toString(student_id_array));` – marstran Oct 22 '16 at 22:45
  • Possible duplicate of [How to convert List to int\[\] in Java?](http://stackoverflow.com/questions/960431/how-to-convert-listinteger-to-int-in-java) – MordechayS Oct 22 '16 at 22:46

3 Answers3

1

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

Aly
  • 847
  • 1
  • 6
  • 30
1

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));
DimaSan
  • 12,264
  • 11
  • 65
  • 75
0

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.

thetraveller
  • 445
  • 3
  • 10