Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ArrayList Printing Values

I have two arraylists monkeyList and dogList. I am trying to print the values of the list using some test cases I created. However, when I use the toString() method it prints dog or monkey followed by an @ and a hexadecimal value. How do I get it to print the actual values I have stored in my test cases?

public static void printAnimals(String menuInput) {
    if (menuInput.equals("4")) {
        System.out.println("List of dogs:");
        for (Dog dog : dogList) {
            System.out.println(dog.toString());
        }
    }

    if (menuInput.equals("5")) {
        System.out.println("List of monkeys:");
        for (Monkey monkey : monkeyList) {
            System.out.println(monkey.toString());
        }
    }
    if (menuInput.equalsIgnoreCase("6")) {
        System.out.println("List of dogs available and in service:");
        for(Dog dog : dogList) {
            if(dog.getTrainingStatus().equalsIgnoreCase("in service") && !dog.getReserved()) {
                System.out.println(dog.toString());
            }
        }
        System.out.println("List of monkeys available and in service:");
        for(Monkey monkey : monkeyList) {
            if(monkey.getTrainingStatus().equalsIgnoreCase("in service") && !monkey.getReserved()) {
                System.out.println(monkey.toString());
            }
        }
    }
}

My output when typing 4, 5, 6 as menu options gives me this output respectively:
(4)
List of dogs:
Dog@64b8f8f4
Dog@2db0f6b2
Dog@3cd1f1c8

(5)
List of monkeys:
Monkey@3a4afd8d
Monkey@1996cd68
Monkey@3339ad8e

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

(6)
List of dogs available and in service:
List of monkeys available and in service:
Monkey@1996cd68

>Solution :

What you perceive is Java converting your object instance into a String. This is done by running the toString() method on that object.

The java.lang.Object’s toString method prints exactly what you describe.
Override this for your dog and monkey classes and you will get your custom behaviour.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading