Why do we need to override toString( ) method.Please descibe in detail its behaviour in above detail.Also I seek your valuable opinions about:
1.When is the compareTo( ) method invoked?
2.How does the Collections.sort( ) function in above code i.e. how does it fuction.Can you suggest how do we make a code like that in java without using libraries.Plese reply soon!!!
[HENRY: added code tags]
[Rob: improved indentation]
I think you will have to work out what those methods do, which you can best do by finding the 3rd chapter of Joshua Bloch’s Effective Java™. You might find a reference to it is you search this forum; there will be links to the old edition because I posted them. Also look up the java.util.Comparator interface.
Welcome to CodeRanch!
Please UseCodeTags. It becomes difficult to read non-indented and non-formatted code.
Also, try to use meaningful names instead of t and t1 - say title and artist.
Now, coming to your questions:
Rachit Kumar Saxena wrote:Why do we need to override toString( ) method
You don't. toString method is used when you are printing the object directly. If you are not doing it, there's no need to override toString.
Rachit Kumar Saxena wrote:Please descibe in detail its behaviour in above detail
You can get it in javadoc of Object class.
Rachit Kumar Saxena wrote:1.When is the compareTo( ) method invoked?
Rachit Kumar Saxena wrote:2.How does the Collections.sort( ) function in above code i.e. how does it fuction
As said, it will call compareTo method, which will decide the logic behind smaller and larger object. E.g. currently, a song(again, why is it not 'Song' with capital S?) will be less than another song if first song's title is alphabetically less than other song's title.
Rachit Kumar Saxena wrote:Can you suggest how do we make a code like that in java without using libraries
Well, why do you want to do that? You are not using any third party libraries. Anyways, it can be done by comparing the song objects from the ArrayList to each other manually (i.e. you'll have to actually invoke the method) and the sorting also would have to be done manually (e.g. using algorithms like bubble sort etc.)
I hope this helps.
Campbell Ritchie wrote:Please go back to your post and add code tags, so we can actually read your code.
Okay, I added the code tags -- and I have to say that this is probably the most ugliest formatted code that I have even seen..... regardless, I guess it is still better than unformatted code.