-2

Im a beginner programmer and i want to make a copy function that clones an array in to another one, for example: if i have this array already declared [1,2,3,4,5] i want the function to clone that array. Here is my code but when compiling im obtaining the array address. By the way im not programming with objects yet.

static int[] copy(int[] collection) {

    int  result[] = new int [collection.length];    
    for(int i = 0; i<collection.length; i++) {
        result[i]=collection[i];
    }

    return result;
}

if i print it like this i obtain the address, something like "[I@76ccd017"

public static void main(String[] args){
    int[] nums = {1,2,3,4,5};
    System.out.println(copy(nums)); 
}
Pshemo
  • 122,468
  • 25
  • 185
  • 269
Kavany
  • 11
  • 1
  • 2
    This code is correct, are you talking about printing? See https://stackoverflow.com/questions/409784/whats-the-simplest-way-to-print-a-java-array – Joakim Danielson Nov 15 '20 at 11:46
  • What do you mean by "but when compiling im obtaining the array address"? – Pshemo Nov 15 '20 at 11:47
  • when im compiling and i want to print it in the main prints something like "[I@76ccd017" – Kavany Nov 15 '20 at 11:54
  • 1
    @Kavany compiling will not generate anything like "[I@76ccd017". That's what you get when *running* your code. And you will get it when you use something like `System.out.println` so please [edit] your question to add that part of your code. – Federico klez Culloca Nov 15 '20 at 11:59

2 Answers2

3

Your code is correct. If you want to print this array to the console, you must print each of its numbers separately. There are 2 ways to do this:

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

Or

System.out.println(Arrays.toString(array));
Артём
  • 43
  • 3
0

I am guessing you are talking about showing the elements in the array. If you are trying to do that, you will have to loop through each of the array elements and then print the values one after the other. You can use the following code to do the same.

static void PrintArray(int[] inputArray) {
   for(int i = 0; i<collection.length; i++) {
        System.out.print(result[i] + " ");
    }
    System.out.println();
}

All you are actually doing different is, instead of copying the values you are printing the same.