What is wrong with this code I'm getting wrong output. I don't know what's wrong, I hope you could help me:
public class Main{
public static void main(String[] args){
int[] data={11,22,33,55,22,88,99,77};
SortingAlgo algo=new SortingAlgo();
data=algo.selectionSort(data);
System.out.println("numbers are"+ data);
}
}
Other class
public class SortingAlgo{
public int[] selectionSort(int[] data){
int lenD = data.length;
int j = 0;
int tmp = 0;
for(int i=0;i<lenD;i++){
j = i;
for(int k = i;k<lenD;k++){
if(data[j]>data[k]){
j = k;
}
}
tmp = data[i];
data[i] = data[j];
data[j] = tmp;
}
return data;
}
}
This is my out put:
numbers are[I@2e4b1dd8
The output is completely fine. The arrays don't override
toString()
method, so it invokes theObject#toString()
method, which generates that kind of representation. The output is of the form:For arrays, the
Class#getName()
method uses some encoding for different element type to generate unique class name. The encoding rule is specified in the documentation.To get the human readable representation, you can use
Arrays#toString()
method:The toString() for arrays is broken. You need
The same applies for Arrays.equals(), Arrays.hashCode(). The Array, Arrays, ArrayUtils classes add functionality you might like arrays to have.
http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html
http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Array.html
http://docs.oracle.com/javase/7/docs/api/java/sql/Array.html
http://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/ArrayUtils.html
However, you may find that you really want ArrayList instead.
data
is an array ofint
s. You should useArrays#toString()
, which is implemented this way:Make sure that you understand it, it will help you to understand arrays.
You can loop on the array and manually print it:
This way you have control on which values to print, e.g. even values:
Regarding the output you are getting, this is the explanation about it:
In Java, each object has
toString()
method, the default is displaying the class name representation, then adding@
and then the hashcode.