Search code examples
javacomparablecompareto

Yep, this puzzle is done


Have you ever came across such situation: In java, you need to compare two objects, which is usually done by overloading the 'compareTo' method in the interface of Comparable. Sometimes, this comparison should be too complex, we need to compare each item in the object to exactly know which one is larger. However, we may do not need to ensure that the comparable method return a right result every time. Let's say, we could get the correct comparisons in most cases(more than 95%), but we also may get wrong answers in rare time. Under this tolerance, maybe we could get a faster comparison method. Less accuracy, much faster running speed. This is an assignment from my mentor, so could anyone give me some instances? You could describe a complex comparison method you might meet before, and I would like to discover a new way to reduce the running time by lower the accurate rate. Thanks a lot.


Solution

  • You can do approximate comparisons, a simple one being a String comparison ignoring case, a more complex one being to compare the distance between Strings. This problem being that the cost of comparison in these solutions is much slower i.e. exact comparison is generally faster than an approximate comparison.

    The only example I can think of is comparing images. You could compare say the size and some random portions of the compressed image file. This should detect whether a file is different most of the time, but it would be faster than comparing the whole file.

    However, if this is homework, then your mentor should be providing the example. I would ask him/her to say when this technique is useful otherwise as I have already pointed out this is generally slower rather than faster than an exact comparison.