简体   繁体   中英

Random Integer filling an array is not producing only integers

I have code to fill an array with 10 integers but for some reason it is not only filling it with integers. EX. [I@5483cd or [I@1690726 Anyone know why?

public static void main(String[] args) {
    int[] array = new int[10];
    int length = array.length;

    for (int i = 0; i < length; i++) {
        array[i] = (int)(Math.random () * 10); 
    }
    System.out.println(array);
}

System.out.println(array) is printing the hashcode for the array, not the values inside the array. Iterate over the values in the array and print those, like this:

for (int val : array)
{
   System.out.println(val);
}

Even simpler, use: Arrays.toString(array) . See What's the simplest way to print a Java array?

As other answers say, println is printing hashcode of the array. If you want to see array's contents, you can iterate over every element and print it OR you can use Arrays.toString() methods.

import java.util.Arrays;
System.out.println(Arrays.toString(array));

If you have multidimensional arrays, use Arrays.deepToString() . Explore Arrays class for more such utility methods.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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