简体   繁体   English

转换ArrayList <Integer> int []在Java中不起作用

[英]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[]. 我一直在开发一个程序,其中我必须将ArrayList转换为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? 但是,当我打印int []以查看它是否有效时,它会打印出一个随机字符串,即“ [I @ 2a139a55””。如何解决此问题?

I cannot use an int[] from the start. 我不能从一开始就使用int []。 This program HAS to convert an ArrayList into int[]. 该程序必须将ArrayList转换为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 are printing out the reference to the array. 您正在打印对数组的引用。 Use Arrays.toString(int[]) . 使用Arrays.toString(int[])

You can do the converting your ArrayList<Integer> to int[] with one line in Java 8: 您可以使用Java 8中的一行将ArrayList<Integer>转换为int[]

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: 如果要输出数组的值而不是数组的表示形式( 例如[I@2a139a55 ),请使用Arrays.toString()方法:

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

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. 或者for-loop如果稍后要填充ArrayList使用for-loop

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM