Printing the Object Arrays As a String

Shreesh Bhat :

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]

Md Golam Rahman Tushar :

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:
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=238174&siteId=1