Bear with me! A newbie is only trying to get a visual cue as to what is going on behind the scene.
Sorts the specified list into ascending order, according to the natural ordering of its elements. All elements in the list must implement the Comparable interface.
My sources of confusion:
1. The sort() method has not been overridden. So, at what point is the compareTo() method invoked?
2. On which element in the list is the compareTo() method invoked; that is (e1.name).compareTo(e2.name). How are e1 and e2 chosen from the list?
3. How does the sort() method iterate through the list in order to sort it?
1) The Collections class is a subclass of Object. Since Object does not have a 'sort' method, the 'sort' method of Collections can't be an override. The 'compareTo' is invoked any time the sort method wants to compare two elements of the list
2) As said: the compareTo method is invoked any time when two elements must be compared. So, if the elements e1 and e2 are involved, 'sort' invokes 'e1.compareTo(e2)' (and since a decent 'compareTo' method requires that 'e1.compareTo(e2)' is equal to 'e2.compareTo(e1), it doesn't matter if e1. or e2. is being used).
3) The API of 'Collections.sort' does not specify which particular sort algorithm is used. What elements and how many are involved in the sorting, is depending on that algorithm used.
Look at Wiki for some well-known sorting algorithms, and try to implement one of the simpler sort algorithms, using a List of, say, Integers or Strings (these implement the Comparable interface). See what elements you use, and when you invoke the 'compareTo' method.
posted 1 year ago
Thank you. I grab hold of this part of your reply
'sort' invokes 'e1.compareTo(e2)'
Did I hear somebody still saying Java is easy to learn?
Biniman Idugboe wrote:Did I hear somebody still saying Java is easy to learn?
Easy can be a relative term, which can be hard to define as it can change from person to person.
That being said, there are some things in Java which can be done rather quickly, like writing "Hello World" to the screen.
And then there are other things which can be rather difficult to learn like using some of the classes in the collections library.
Then there is also the fact that not everyone has the same level of experience when they start learning something new like Java and not everyone learns the same way.
The big thing here is, 'Do not give up'.
Learning something like Java can be a daunting task to undertake, and even if you do not end up using this skill you will still be the better for learning it.
Learning is the best way to keep your mind active and delay some of the illnesses associated with old age.
“The strongest of all warriors are these two — Time and Patience.” ― Leo Tolstoy, War and Peace
posted 1 year ago
I hear you, loud and clear!
All of the world's problems can be solved in a garden - Geoff Lawton. Tiny ad:
RavenDB is an Open Source NoSQL Database that’s fully transactional (ACID) across your database