0
public class ArrayUtilities{
  public static void main(String[] args){
    int[] array1= {1,2,3,4,5,10,15,30,32};
    System.out.println(copy(array1));
  }
public static int[] copy(int[] array){
  int[] newArray = new int[array.length];
  for(int i = 0; i < array.length; i++){
    array[i] = newArray[i];
  }
  return newArray;
}
}

I had to write a method to copy an array. THe problem is whenever i run this code it gives me [I@68e4e358, instead of the array. Please help Thank you in advance!

user2826974
  • 199
  • 2
  • 7
  • 17

5 Answers5

5

Since the copy method returns an array you can :

  1. Use a for loop to print each item of the array (standard for loop or a for-each loop)
  2. Use Arrays.toString(copy(array1));
Alexis C.
  • 91,686
  • 21
  • 171
  • 177
  • im not allowed to use library method, so basically i have to write another method to print it? – user2826974 Oct 31 '13 at 16:00
  • 1
    @user2826974 Yes a for loop to go through all the elements of the array to print them one by one should do the trick =) – Alexis C. Oct 31 '13 at 16:01
  • but my method is supposed to return int[], if i print them, dont they become String? – user2826974 Oct 31 '13 at 16:37
  • @user2826974 Declare a new variable `int[] copy = copy(array1);` Then just write a loop that will go through the array `copy` and print each element. – Alexis C. Oct 31 '13 at 16:40
1

The reason you are seeing [I@68e4e358 is because that is the string representation of the array object itself, not the contents of the array. To print out the contents of the copied array, iterate over each of the elements and call System.out.println on the array index. For example -

copyOfArray = copy(array1);
for (int i = 0; i < copyOfArray.length; i++) {
  System.out.println(copyOfArray[i]);
}
spot35
  • 888
  • 4
  • 9
0

[I@68e4e358

toString() for arrays is not implemented as you need returns the type of the array ([[I) followed by its hash code.

For testing purpose you can use this method.

int[] array1= {1,2,3,4,5,10,15,30,32};
System.out.println(Arrays.toString(copy(array1)));

Or alternative you can do.

  int[] copy = copy(array1);
  for(int element : copy){
    System.out.println(element);
  }

This is one implementation i found in google perhaps it help you.

public static String toString(int[] a) {
    if (a == null)
        return "null";
    int iMax = a.length - 1;
    if (iMax == -1)
        return "[]";

    StringBuilder b = new StringBuilder();
    b.append('[');
    for (int i = 0; ; i++) {
        b.append(a[i]);
        if (i == iMax)
            return b.append(']').toString();
        b.append(", ");
    }
}
nachokk
  • 14,363
  • 4
  • 24
  • 53
0

Overide toString() and write your code there

Shoaib Chikate
  • 8,665
  • 12
  • 47
  • 70
0

Override the toString() method and inside its body print whatever u like related to array.

Scientist
  • 1,458
  • 2
  • 15
  • 31