Menu
Question Index
...

What will be the output of the following program?

import java.util.*;
class Dog implements Comparator<Dog>, Comparable<Dog> {
    String name;
    int age;
    Dog() {
    }
    Dog(String n, int a) {
        name = n;
        age = a;
    }
    public int compareTo(Dog d) {
        return (name).compareTo(d.name);
    }
    public int compare(Dog d, Dog d1) {
        return d.age - d1.age;
    }
}
public class Example {
    public static void main(String args[]) {
        List<Dog> list = new ArrayList<Dog>();
        list.add(new Dog("Shaggy", 3));
        list.add(new Dog("Lacy", 2));
        list.add(new Dog("Roger", 10));
        list.add(new Dog("Tommy", 4));
        list.add(new Dog("Tammy", 1));
        Collections.sort(list);
        for (Dog a : list)
            System.out.print(a.name + ", ");
        Collections.sort(list, new Dog());
        System.out.println(" ");
        for (Dog a : list)
            System.out.print(a.name + ":" + a.age + ", ");
    }
}


Lacy, Roger, Shaggy, Tammy, Tommy,  
Tammy:1, Lacy:2, Shaggy:3, Tommy:4, Roger:10,
Shaggy, Lacy, Roger, Tommy, Tammy,
Tammy:1, Lacy:2, Shaggy:3, Tommy:4, Roger:10,
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