Menu
Question Index
...

What will be the output of the following program?

import java.util.*;
public class x {
    public static void main(String args[]) {
        TreeSet empAgeSet = new TreeSet(new EmployeeComparator_Age());
        int i = 0;
        int ageDiff[] = {0, -5, 7, 10, -15};
        int pinNumber[] = {0, 1, -898, -555, 555, 69};
        String[] empNames = {"Dilbert", "Murphy", "Don", "Wattson", "Noddy"};
        for (String empName : empNames) {
            empAgeSet.add(new Employee1(empName, 30 + ageDiff[i], 1500 + pinNumber[i]));
            i++;
        }
        Iterator empIterator = empAgeSet.iterator();
        System.out.print("Name~Age~Pin");
        while (empIterator.hasNext()) {    System.out.print("\n" + empIterator.next());    }
    }
}
class EmployeeComparator_Age implements Comparator {
    public int compare(Object emp1, Object emp2) {
        Employee1 e1 = (Employee1) emp1;
        Employee1 e2 = (Employee1) emp2;
        int ret = 1;
        if (e1.age == e2.age)    ret = 0;
        if (e1.age < e2.age)    ret = -1;
        return ret;
    }
}
class Employee1 {
    String name;
    int age;
    int pinNumber;
    public Employee1(String n, int a, int s) {
        name = n;
        age = a;
        pinNumber = s;
    }
    public String toString() {    return name + "~" + age + "~" + pinNumber;    }
}


Name~Age~Pin
Noddy~15~2055
Wattson~40~945
Don~37~602
Murphy~25~1501
Dilbert~30~1500
Name~Age~Pin
Dilbert~30~1500
Murphy~25~1501
Don~37~602
Wattson~40~945
Noddy~15~2055
Name~Age~Pin
Noddy~15~15
Murphy~25~25
Dilbert~30~30
Don~37~37
Wattson~40~40
Name~Age~Pin
Noddy~15~2055
Murphy~25~1501
Dilbert~30~1500
Don~37~602
Wattson~40~945
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