Swati Pawar

Greenhorn
+ Follow
since Jul 06, 2009
Merit badge: grant badges
For More
Cows and Likes
Cows
Total received
0
In last 30 days
0
Total given
0
Likes
Total received
0
Received in last 30 days
0
Total given
0
Given in last 30 days
0
Forums and Threads
Scavenger Hunt
expand Ranch Hand Scavenger Hunt
expand Greenhorn Scavenger Hunt

Recent posts by Swati Pawar

As given in K&B book,

an element in a list can compare itself to another of its own type in only 1 way using its compareTo() method


But a Comparator is external to the element type you'r comparing- its a separate class . So you can make as many of these as you like!



So when using compareTo() method of Comparable interface, the class which calls Collections.sort(<List>) implements Comparable interface and write compareTo() method only once. Hence you can compare your objects only in 1 way.
But if you want to compare your objects by more than one way, then you should use compare() method of Comparator interface.

As given an example in K&B, to compare songs by only title, use compareTo() method.
But if you want to sort songs by its artist or by its title, to implement this, use compare() method.

I hope this clears all your confusion.
private double calcSpeed(double distance, double time) {
assert distance>=0.0; // Check if distance is grater than or equal to 0.0,
// then continue else throw assertionException
assert time >0.0 : "Time is not a positive value:" +time;
// If time > 0.0 then continue to the next line else throw
// assertionException. It will print "Time is not a positive value:" +
// time with the exception
double speed =distance/time;
assert speed >=0.0; // If speed is greater than or equal to 0.0 then return
// speed else will throw AssertionException
return speed;
}

Assertions are used for debugging the program. Its like if condition. If condition is true it will continue to execute code else will throw Exception.

Whatever I know about assertions, I am telling you from that. Please correct me if I am wrong.