Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning Objects with toString() method

Tags:

java

class

I have a main method that is calling a class method;

CourseListQ2 list = new CourseListQ2();

list.addCourse(new Course("Structure and Modelling", "Chemistry", 1));
list.addCourse(new Course("Design in Engineering", "Engineering", 1));
......

In this class that I wrote, I created an array of objects from the main method, and subsequently expanded it and deleted values I didn't need. Then, I wrote a toString method that was suppose to return each object on a new line:

public String toString(){
      return  Arrays.toString(arrayCourses) ;}

However, it's returning the entire array on a single line. So obviously, I'm misinterpreting what this method does exactly.

I have two ideas, either I'm suppose to try to return each as an object, like getName().toString(arrayCourses) + getYear().toString(arrayCourses) + "\n",

Or, maybe I'm suppose to create a loop that adds a new line. Yet I think this defeats the purpose of having the toString method, and it still returns a '[' at the beginning of the output.

So, could anyone explain why this is happening and perhaps suggest a better approach?

like image 842
user180708 Avatar asked Feb 25 '26 07:02

user180708


1 Answers

In your example Arrays.toString(arrayCourses) you are calling the toString() method of the Arrays class, below is what Java Docs says about that method:

Returns a string representation of the contents of the specified array. The string representation consists of a list of the array's elements, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (a comma followed by a space). Elements are converted to strings as by String.valueOf(float). Returns "null" if a is null.

For the approach i would suggest what @dasblinkenlight adviced.

like image 123
Tarik Avatar answered Feb 26 '26 21:02

Tarik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!