Menu
Question Index
...

What will be the output of the following program?

import java.util.*;
public class Person implements Comparator<Person>, Comparable<Person> {
    String name;
    int age;
    Person(String n, int a) {    name = n;    age = a;    }
    public String toString() {    return name + "~" + age;    }
    public static void main(String args[]) {
        List<Person> list = new ArrayList<Person>();
        Person jason = new Person("Jason", 22);
        list.add(jason);
        list.add(new Person(null, 21));
        list.add(new Person("Advin", 25));
        list.add(new Person("Advin", 30));
        list.add(new Person("Tom", 24));
        list.add(new Person(null, 23));
        Collections.sort(list);
        System.out.println(list);
    }
    public static int nullSafeStringComparator(final String one, final String two) {
        if (one == null ^ two == null)    return (one == null) ? -1 : 1;
        if (one == null && two == null)    return 0;
        return one.compareTo(two);
    }
    public int compareTo(final Person d) {
        int result = nullSafeStringComparator(name, d.name);
        if (result != 0)
            return result;
        return compare(d, this);
    }
    public int compare(Person d, Person d1) {    return d.age - d1.age;    }
}


[null~23, null~21, Advin~30, Advin~25, Jason~22, Tom~24]
[null~21, null~23, Advin~25, Advin~30, Jason~22, Tom~24]
[Advin~30, Advin~25, Jason~22, Tom~24, null~23, null~21]
[Advin~25, Advin~30, Jason~22, Tom~24, null~21, null~23]
Some other output
Compilation Error or Runtime Error

Doubts

Problems

Topic: Java Comparators

Read this topic
Take test on this topic

0
Wrong
Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App