Reputation: 13
I want to print the object array as a string. here is my code.
I have followed instructions in this page but could not get it. https://www.java67.com/2014/03/how-to-print-array-in-java-example-tutorial.html
class Tiger extends Animal implements Comparable<Tiger>
{
@Override
public int compareTo(Tiger t)
{
return this.stripes-t.stripes;
}
int stripes;
Tiger(String color,String name,int stripes)
{
super(color,name);
this.stripes=stripes;
}
@Override
void move()
{
System.out.println("Tiger moving");
}
}
class Main1
{
public static void main(String[] args)
{
Tiger[] tigers={new Tiger("red","tiger_1",12),
new Tiger("red","tiger_2",8),
new Tiger("red","tiger_3",10)};
Arrays.sort(tigers);
System.out.println( Arrays.toString(tigers));
}
}
I have tried Arrays.toString. but the output is a quite like this : [Tiger@7d4991ad, Tiger@28d93b30, Tiger@1b6d3586]
Upvotes: 0
Views: 96
Reputation: 2375
Override the toString class inside the Tiger class. and whatever info you want to print of a tiger object just return the info as string. Then this string will be printed whenever you print a tiger class. For example the following implementation of toString will print the name property of a tiger object.
@Override
public String toString(){
return this.name:
}
Upvotes: 1
Reputation: 66
Override toString() in Tiger class
import java.util.*;
class Tiger implements Comparable<Tiger>
{
@Override
public int compareTo(Tiger t)
{
return this.stripes-t.stripes;
}
int stripes;
String color;
String name;
Tiger(String color,String name,int stripes)
{
this.color=color;
this.name=name;
this.stripes=stripes;
}
@Override
public String toString()
{
return color + " " + name + " " + stripes;
}
}
public class Main1
{
public static void main(String[] args)
{
Tiger[] tigers={new Tiger("red","tiger_1",12),
new Tiger("red","tiger_2",8),
new Tiger("red","tiger_3",10)};
Arrays.sort(tigers);
System.out.println( Arrays.toString(tigers));
}
}
Ouptput:-
[red tiger_2 8, red tiger_3 10, red tiger_1 12]
Upvotes: 0
Reputation: 2039
First you should override toString()
in class Tiger
Class Tiger{
....
..
@override
public String toString(){
return name+" "+ color;
}
}
then you can use tiger.toString
Upvotes: 0
Reputation: 117587
You need to override toString()
of Tiger
to customize the default implementation. Something ike:
@Override
public String toString()
{
return "Tiger{name=" + name + ", color=" + color + ", stripes=" + stripes + "}";
}
assuming name
and color
are inherited from Animal
.
Upvotes: 0