Home | About the author | Resume | << Hack any Java class using reflection attack | Drools - tutorial on writing DSL template >>
SMS Bundle - Mobile Marketing Solutions
SMS Bundle is an Australian-based service for sending marketing SMS and MMS

Brainteaser: Broken comparator

Question: The following program returns result "1", which indicates that first Integer value is greater than the second, why?
import java.util.*;

public class Example {

public static void main(String[] args) {
System.out.println("Result: " +
naturalOrder.compare(new Integer(90),
new Integer(90)));
}

private static Comparator<Integer> naturalOrder =
new Comparator<Integer>() {
public int compare(Integer first, Integer second) {
return first < second ? -1 : (first == second ? 0 :1);
}
};
}
Please note:
In this case, comparator for natural order on Integer is written for example only, and in practice there is no need to write it.

Looking forward for your answers dear readers

Resources:
Effective Java
Social Bookmarks :  Add this post to Slashdot    Add this post to Digg    Add this post to Reddit    Add this post to Delicious    Add this post to Stumble it    Add this post to Google    Add this post to Technorati    Add this post to Bloglines    Add this post to Facebook    Add this post to Furl    Add this post to Windows Live    Add this post to Yahoo!

Related Posts
Brainteaser Drools: Testing Objects
Brainteaser: Broken case of inheritance
Brainteaser: Overridable methods
Java and those frameworks
Brainteaser: ArrayList VS TreeSet
How to set SecurityManager and Java security policy programmatically
Hack any Java class using reflection attack
Singleton pattern and problem with double checked locking




If you like this post, then consider subscribing to the full feed RSS.



Re: Brainteaser: Broken comparator

equals

Re: Brainteaser: Broken comparator

Comparison between objects not values

Re: Brainteaser: Broken comparator

Integers compared by the instances

Re: Brainteaser: Broken comparator

in the comparison : first == second The object references are being compared. Since they point to different objects, they are not equal and hence the compare method returns 1.

Add a comment    Send a TrackBack