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!

4

5 回答 5

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));
于 2013-10-31T15:58:43.463 回答
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]);
}
于 2013-10-31T16:06:01.320 回答
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(", ");
    }
}
于 2013-10-31T16:00:35.620 回答
0

Overide toString() and write your code there

于 2013-10-31T16:01:29.490 回答
0

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

于 2013-10-31T16:01:54.307 回答