public static String toStringFor(){
int[] x={3, 45, 17, 2, -1, 44, 9, 23, 67, 2, -6, -23, -100, 12, 5, 1212};
String array = x.toString();
return array;
}
I keep getting
[I@62aba879
public static String toStringFor(){
int[] x={3, 45, 17, 2, -1, 44, 9, 23, 67, 2, -6, -23, -100, 12, 5, 1212};
String array = x.toString();
return array;
}
I keep getting
[I@62aba879
What you are seeing is the hashcode of the array instance. You can't simply use toString()
on an array and expect to give you a nice result. In fact, each object has its own toString()
method that can be implemented in various ways. This is how the implementation of toString()
on an array looks like:
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
You will have to iterate through the elements and create the final string yourself. Here's a way to do it in Java 8:
int[] x={3, 45, 17, 2, -1, 44, 9, 23, 67, 2, -6, -23, -100, 12, 5, 1212};
String result = Arrays.stream(x)
.mapToObj(String::valueOf)
.collect(Collectors.joining(" "));
System.out.println("result = " + result);
This creates a stream of values from your array and collects them into a String separated with space.
Another version with a for loop:
StringJoiner sj = new StringJoiner(" ");
for (int i : x) {
sj.add(String.valueOf(i));
}
System.out.println("result =" + sj.toString());
You can also iterate the array using:
for (int i = 0; i < x.length; i++) {
...
}
You should use a for and StringJoiner(credits to @sm4) to help with that purpose
public static String toStringFor(){
int[] x={3, 45, 17, 2, -1, 44, 9, 23, 67, 2, -6, -23, -100, 12, 5, 1212};
StringJoiner sj=new StringJoiner(" ");
for (int i = 0; i < x.length; i++) {
sj.add(String.valueOf(x[i]));
}
return sj.toString();
}
toString
returns a string holding some abbreviation characters followed by the hexadecimal representation of a hash, unless overridden. Arrays don't override this, so you got the toString
of the object that the array is.
You need to write custom code to accomplish your goal. Perhaps you could loop through the array, appending the String
representation of each array element to a StringBuilder
along with some characters for formatting, and output the toString
of the resulting StringBuilder
from your method that performs that task.
The problem here is that you're calling toString()
on the array object - not on the elements within the array.
Use Arrays.toString(int[] a)
instead.
In order to generate a string representation of the array, which is separated by space, it helps, if you handle the first array item independently and then add all further elements prefixed by a space.
int[] x = {1, 2, 3, 4};
int i = 0;
String arr = String.valueOf(x[i++]);
for (; i < x.length; i++)
arr += " " + x[i];
Doing so leaves no trailing space at the end of the string.