I am trying to reverse an array of objects without making any new other object and without making a new array. I thought that reversing it would be the same as reversing a regular array which is what I did but it is not printing, it is only printing Box@4e0e2f2a
Box@73d16e93
Box@659e0bfd so I am not sure if maybe I am printing it wrong or did I reversed it incorrectly?
//method
static void reverseArray(Box[] b){
for (int i = b.length -1 ; i >= 0; i--){
System.out.println(b[i]);
}
}
//main
public static void main (String [] args){
Box [] b1 = new Box[3];
b1[0] = new Box(5,10);
b1[1] = new Box(20,30);
b1[2] = new Box(40,50);
b1[0].printInfo();
b1[1].printInfo();
b1[2].printInfo();
reverseArray(b1);
}
//class
class Box {
private double length;
private double width;
Box(double length, double width){
this.length=length;
this.width=width;
}
double getArea(){
return length*width;
}
void printInfo(){
System.out.println(length + " " + width);
}
}
>Solution :
In your
static void reverseArray(Box[] b){
for (int i = b.length -1 ; i >= 0; i--){
System.out.println(b[i]);
}
}
just replace b[i] with b[i].printInfo()