Tuesday, December 23, 2014

Writing Comparators

Two ways of writing Comparators in a class:


    private Comparator ListNodeComparator = new Comparator()
    {
        public int compare(ListNode n1, ListNode n2)
        {
            if (n1 == null)
                return 1;
            if (n2 == null)
                return -1;
            return n1.val - n2.val;
        }
    };


    private class ListNodeComparator implements Comparator
    {
        public int compare(ListNode n1, ListNode n2)
        {
            if (n1 == null)
                return 1;
            if (n2 == null)
                return -1;
            return n1.val - n2.val;
        }
    }

No comments:

Post a Comment