incava.org

Difference algorithm for Java

This is an implementation of the longest common subsequences algorithm for Java, as two classes, its main method (Diff:diff()) returning a list of Difference objects, each of which describes an addition, deletion, or change between the two collections.

Example usage (modified from one of the unit tests):

    Object[] a = new Object[] {
        "a",
        "b",
        "c",
        "d",
        "e"
    };

    Object[] b = new Object[] {
        "a",
        "x",
        "y",
        "b",
        "c",
        "j",
        "e",
    };

    Difference[] expected = new Difference[] {
        new Difference(1, -1,  1,  2),
        new Difference(3,  3,  5,  5),
    };

    Diff diff = new Diff(a, b);
    List diffOut = diff.diff();

Diff supports comparison of objects that implement the Comparable interface, or for which a Comparator object has been passed to the Diff constructor. If the object does not implement the Comparator interface, its hash code will be used instead.

See the API for more.

This is the module used in the DiffJ application for comparison of code.

Many thanks go to Oliver Köll for finding and reporting a bug in the 1.0.4 version. Note that this has been fixed in 1.0.5.

Valid HTML 4.01!

Valid CSS!