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); 
2
  • You cannot print an array directly. You have to use System.out.println(java.util.Arrays.toString(student_id_array)); Commented Oct 22, 2016 at 22:45
  • Possible duplicate of How to convert List<Integer> to int[] in Java? Commented Oct 22, 2016 at 22:46

3 Answers 3

1

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

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

Comments

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

1 Comment

Nice stream usage :D
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.