Reputation: 155
I'm trying to print the transposed version of this matrix array but it is instead printing the memory locations. Any input on how to print the actual array?
This is what it prints: [[I@4b71bbc9, [I@17dfafd1, [I@5e8fce95]
import java.util.*;
class MatrixTranspose
{
public static void main (String [] args)
{
int [] [] m = {
{3, 6, 9},
{4, 1, 5},
{5, 8, 7},
};
System.out.println (Arrays.toString (transpose(m)));
}
public static int [] [] transpose (int [] [] x)
{
int start = 1;
for (int r = 0; r < x.length; r++)
{
for (int c = start; c < x[0].length; c++)
{
int temp = x[r][c];
x [r][c] = x[c][r];
x[c][r] = temp;
}
start++;
}
return x;
}
}
Upvotes: 1
Views: 273
Reputation: 93842
transpose(int[][] x)
returns a 2-dimensional array.
Use Arrays.deepToString(Object[] a)
instead :
If an element e is an array of a primitive type, it is converted to a string as by invoking the appropriate overloading of
Arrays.toString(e)
. If an element e is an array of a reference type, it is converted to a string as by invoking this method recursively.
System.out.println(Arrays.deepToString(transpose(m)));
Upvotes: 5
Reputation: 95968
Use Arrays#deepToString
instead.
In Java, each object has toString()
method, the default is displaying the class name representation, then adding @ and then the hashcode.
To better understand the output you're getting, see the implementation of Arrays#toString
:
3860 public static String toString(int[] a) { {
3861 if (a == null)
3862 return "null";
3863 int iMax = a.length - 1;
3864 if (iMax == -1)
3865 return "[]";
3866
3867 StringBuilder b = new StringBuilder();
3868 b.append('[');
3869 for (int i = 0; ; i++) {
3870 b.append(a[i]);
3871 if (i == iMax)
3872 return b.append(']').toString();
3873 b.append(", ");
3874 }
3875 }
the toString
is applied on an array, resulting the "weird" output you got.
Upvotes: 1