Hi, I found many mock exam questions about collection asked if the collection is ordered or in natural ordered or sorted. What's the difference? Sorry English is my third language, I have some difficulties on understanding such details.
Sorted means there is a Comparator method based on which the elements are added into the collection. Ordered means the collection is maintained in the list in which the programmer adds the elements. HTH
Hi, When u add a few elements to a collection, and say, if the collection maintains the order in which u inserted (that is, while printing it back, u get the same order), it is 'ordered'. Ordered means that the elements are NOT stored in a random manner (that doesnt make sense to us). Sorting is also a form of ordering. Sorting means, ordering based on a 'natural order', that is, for numbers, the natural order is 1,2,3 etc. and for letters it is A,B,C... You can also specify what u exactly mean by a natural order, for your own classes.
Thanks<br />Karthik<br />SCJP 1.4, CCNA.<br /> <br />"Success is relative. More the success, more the relatives."
Originally posted by sun par: Sorted means there is a Comparator method...
Well, actually, Comparator is an interface, but Sunita is on the right track. Comparator defines the methods compare and equals. So, based on those methods, you can compare multiple objects of some type and determine how they should be sorted. For example, the class Integer, implements the Interface Comparable (which is very similar to Comparator) so you can compare two Integer objects to determine which one should come first in a list. If you've sorted objects this way, they are considered to be sorted. Note that, if a class does not have a compareTo method or something similar, there may be no way to sort a collection of instances of that class. There is really no way to know which one should come before another. Ordered, on the other hand, means that the objects are kept in the order that they were originally put there. So, for example, if you were adding things to a list, that list might keep the objects sorted (meaning that it will insert the new element wherever it belongs to keep the list sorted, as discussed above) or it might just put the object on the end, meaning that it retains the order that you put the elements in. Or, it is possible to make a container that puts elements in by some other criteria, making it neither sorted nor ordered. I hope that helps, Corey