Java Collections Sorting Hypothetical - java

I am currently a computer science major and am taking a course in advanced java programming. My question today is if you have two identical lists, lets call them list1 and list2, and you invoke Collections.sort(list1) and Collections.sort(list2), is it possible for these two lists to be different after invoking this? My textbook says that it is possible, while my professor says it isn't. Can someone please clarify this for me?

If we consider the obvious case such as sorting List<Integer>, then no it's not possible. If you're sorting two identical lists, they should be properly sorted of course.
However since Collections.sort() requires that the objects being sorted are Comparable, you can always implement Comparable poorly. For example you could have compareTo() return a random value (or the time of day, or anything not related to the object actually being sorted), and you wouldn't have any idea how they would be sorted.
Collections.sort() can notice if compareTo() is implemented wrong and will throw an exception saying Comparison method violates its general contract!. However it's not 100% guaranteed to notice this, so technically it is possible to have 2 identical collections sorted in different ways.
As equality is defined by Object.equals(), but comparison is defined by Comparable.compareTo() or Comparator.compare(), like the javadoc says:
It is strongly recommended (though not required) that natural
orderings be consistent with equals.
Otherwise it is possible that equal elements are sorted differently.

Related

Set interface and natural ordering [nonsensical interview test] [duplicate]

This question already has answers here:
To store unique element in a collection with natural order
(5 answers)
Closed 7 years ago.
By a chance it happened to me twice that I got the same Java question during a job interview Java test. For me it seems like a nonsense. It goes something like this:
Which of this collections would you use if you needed a collection with no
duplicates and with natural ordering?
java.util.List
java.util.Map
java.util.Set
java.util.Collection
The closest answer would be Set. But as far as I know these interfaces, with exception of List do not define any ordering in their contract but it is the matter of the implementing classes to have or not to have defined ordering.
Was I right in pointing out in the test that the question is wrong?
The first major clue is "no duplicates." A mathematical set contains only unique items, which means no duplicates, so you are correct here.
In terms of ordering, perhaps the interviewer was looking for you to expand upon your answer. Just as a "Set" extends a "Collection" (in Java), there are more specific types of "Sets" possible in Java. See: HashSet, TreeSet, LinkedHashSet. For example, TreeSet is inherited from SortedSet interface.
However, it is most definitely true that a Java set does not provide any ordering. Frankly, I think this is a poorly worded question and you were right to point out the lack in precision.
Yes, you're correct that none of the answers given matches the requirements. A correct answer might have been SortedSet or its subinterface NavigableSet.
A Set with natural ordering is a SortedSet (which extends Set so it is-a Set), and a concrete implementation of that interface is TreeSet (which implements SortedSet so it is-a Set).
The correct answer for that test is Set Let's remember that it's asking for an interface that could provide that; given the right implementation, the Set interface could provide it.
The Map interface doesn't make any guarantees around what order
things are stored, as that's implementation specific. However, if you
use the right implementation (that is, [TreeMap][1] as spelled out
by the docs), then you're guaranteed a natural ordering and no
duplicate entries. However, there's no requirement about
key-value pairs.
The Set interface also doesn't make any guarantees around what order
things are stored in, as that's implementation specific. But, like
TreeMap, [TreeSet][2] is a set that can be used to store things in a
natural order with no duplicates. Here's how it'd look.
Set<String> values = new TreeSet<>();
The List interface will definitely allow duplicates, which
instantly rules it out.
The Collection interface doesn't have anything directly implementing
it, but it is the patriarch of the entire collections hierarchy.
So, in theory, code like this is legal:
Collection<String> values = new TreeSet<>();
...but you'd lose information about what
kind of collection it actually was, so I'd discourage its
usage.

Why can't we use only comparable in every situation?

Possible Duplicate of
When should a class be Comparable and/or Comparator?
I understand the difference that is given in this link.
And also in the book that i am referring it is given that we can not use comparable when we need to sort the objects on the basis of more than one fields.
My Question:
I just want an example where we could not possibly use comparable and have to go for comparator in order to compare and please also show that with comparable why can't we compare on two different fields of object.
If you find this question as duplicate please provide link,, i have searched many questions but none has the example that i wanted.
If a class implements Comparable, this defines what is usually considered the natural ordering of it elements. In some cases this is the only ordering that may make sense, in other cases it might be the most widely used ordering. If you look for example at numbers, there is probably only one (total) ordering that makes sense (except maybe for taking the reverse). As others already have pointed out, their are other objects that have other useful orderings. What makes the primary ordering (or if there is even one) depends on your application. If you manage persons with adresses in you application, phonebook sort order could be considered the natural order if this is the most widely used one and sorting by age could be a secondary. Slightly OT: Beware of cases where non equal objects are considered equal wrt to the ordering, this may yield problems with containers like OrderedList etc.
Comparing apples with each other will result in classes of equal apples, like red ones, green ones, old and fresh ones. That's OK as long as you only interested in a rather broad equality. But if you you are going to receive a paycheck you are very happy that you are identifiable within you equality class.
So compareto is good for sorting and clustering and equals/hashcode is got for identification.
Comparable is mostly used when there is a 'known' default sort order and the object or class that we are ordering is editable or owned by the developer making the change.
Comparator is suitable where the class or object being ordered is not owned by the developer making the change like a web service response. It is also preferred when the natural ordering doesn't fit the objective that needs to be accomplished.

use of equals() method in comparator interface?

equals() method is available to all java collection classes from the Object class. This method is also declared in Comparator interface, so what is the purpose of declaring this method in Comparator? in which case is it used and how?
what is the purpose of declaring this method in Comparator?
I think it's the designer's way of highlighting the fact that Comparator.equals() imposes some additional requirements on any classes that implement the interface:
Additionally, this method can return true only if the specified object is also a comparator and it imposes the same ordering as this comparator. Thus, comp1.equals(comp2) implies that sgn(comp1.compare(o1, o2))==sgn(comp2.compare(o1, o2)) for every object reference o1 and o2.
The method can be used to establish whether or not two distinct comparators impose the same order.
I think that the main reason is to make it clear that equals method is for testing the Comparator itself. This is obvious when you think about it, but can I imagine that some people might expect equals(Object) to (somehow) be semantically related to the compare(T, T) method.
It also allows the documentation of some common-sense guidelines for when two comparators could be viewed as equal.
Either way, the presence of the equals(Object) method in the interface is solely for documentation purposes.
From the javadoc
Note that it is always safe not to override Object.equals(Object).
However, overriding this method may, in some cases, improve
performance by allowing programs to determine that two distinct
comparators impose the same order.
The idea is simply to be able to allow you to not sort a collection that has already been sorted by another comparator if you realize that the end result will be the same.
Generally it had little use, but when sorting very large collections it is something you might want to look into.
-when the declaring Comparator is compared to another Object (argument)
It's just an over-ridden form of the Object's equals method to let you know if two objects are of same comparator type.
As per your question I think It is used to compare objects after converting in string.
Object class eqlas methods chek both Object are eqls or not And Competres method chek object data like Hello.eqlas("hello")

Insertion sort with strings

I'm curious how an insertion sort would be for strings. I know how to do with numbers.
Could someone show me an implementation?
No, it's not for homework.
Thanks.
The sorting algorithm is pretty much the same no matter what you're sorting. The only difference is that with Strings (or any type of Object) you need to use the compareTo method rather than simply if (a < b).
You should be able to adapt an insertion sort for numbers to Strings by using String.compareTo to determine whether Strings are 'less than' or 'greater than' each other.
Additionally, a quick google search turns up several implementations, like this one which uses the general Comparable interface (which String implements).

Java : Comparable vs Comparator [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
difference between compare() and compareTo()
Java: What is the difference between implementing Comparable and Comparator?
What are the keys differences between Comparable and Comparator.
and which is preferred over the other in what scenarios?
Thanks
Updated - GOOD LINK WITH EXAMPLE!!
http://www.digizol.com/2008/07/java-sorting-comparator-vs-comparable.html
When your class implements Comparable, the compareTo method of the class is defining the "natural" ordering of that object. That method is contractually obligated (though not demanded) to be in line with other methods on that object, such as a 0 should always be returned for objects when the .equals() comparisons return true.
A Comparator is its own definition of how to compare two objects, and can be used to compare objects in a way that might not align with the natural ordering.
For example, Strings are generally compared alphabetically. Thus the "a".compareTo("b") would use alphabetical comparisons. If you wanted to compare Strings on length, you would need to write a custom comparator.
In short, there isn't much difference. They are both ends to similar means. In general implement comparable for natural order, (natural order definition is obviously open to interpretation), and write a comparator for other sorting or comparison needs.
Comparator provides a way for you to provide custom comparison logic for types that you have no control over.
Comparable allows you to specify how objects that you are implementing get compared.
Obviously, if you don't have control over a class (or you want to provide multiple ways to compare objects that you do have control over) then use Comparator.
Otherwise you can use Comparable.

Categories