Click here to Skip to main content
15,888,610 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello everyone, I have a class of Animals, a AnimalGroup class and a Main class. The AnimalGroup class is instantiated and it has a list of Animals. I have a print method in the AnimalGroup class that prints a list of animals but it's printing the memory address of the content of the list so I want to write a toString method in the AnimalGroup class that would print the content of the animal list.
Animal class
public class Animals {
	
	String name;
	String classification;

	
	public Animals(String name, String classification) {
		this.name = name;
		this.classification = classification;
	}
	
	//Getters and Setters
}

AnimalGroup class
public class AnimalGroup {
	
	String name;

	public AnimalGroup(String name) {
		this.name = name;
	}

	//Getters and Setters

	public void printAnimalsList(List<Animals> animals) {
		for(Animals i : animals) {
			System.out.println(i);			
		}
		
		public Animals toString() {
			
		}
	}

I need to complete the toString method, thanks for any help.

What I have tried:

public class Main {

	public static void main(String[] args) {
		
		Animals lion = new Animals("Lion", "Mammal");
		Animals tiger = new Animals("Tiger", "Mammal");
		Animals snake = new Animals("Snake", "Reptile");
		
		List<Animals> animalsList = new ArrayList<>();
		animalsList.add(lion);
		animalsList.add(tiger);
		animalsList.add(snake);
		
		
		AnimalGroup animalGroup1 = new AnimalGroup("Group1");
		List<List<Animals>> animalsGroupList = new ArrayList<>();
		animalsGroupList.add(animalsList);
		animalGroup1.printAnimalsList(animalsList);

	}

}
Posted
Updated 3-Jul-22 17:23pm

1 solution

First, the toString() method should return a String not an Animals type (or any other type).
Second, you want to override the standard java Object toString() method for your class.
Third, you really want the toString() method in the Animals class instead of AnimalGroup.

Something like:
Java
@Override
public String toString() {
    return "Animal: " + name + ", Classification: " + classification;
}


Then in your AnimalGroup printAnimalsList() method change the println call to:
Java
System.out.println(i.toString());


You can get rid of the toString() method in the AnimalGroup class.
 
Share this answer
 
Comments
CPallini 4-Jul-22 2:33am    
5.
FreedMalloc 4-Jul-22 11:06am    
Thank you!
UT7 4-Jul-22 10:40am    
@FreedMalloc thanks a lot, it worked ! Thank you.
FreedMalloc 4-Jul-22 11:05am    
@tuns13yahooca, I'm glad I was able to help. Good luck!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900