Menu
Topics Index
...
`

Collections TreeSet


If you need explanation Read this topic

If you need Answer Take test on this topic

Collections TreeSet
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;    }
}

A. Name~Age~Pin
Noddy~15~2055
Wattson~40~945
Don~37~602
Murphy~25~1501
Dilbert~30~1500
B. Name~Age~Pin
Dilbert~30~1500
Murphy~25~1501
Don~37~602
Wattson~40~945
Noddy~15~2055
C. Name~Age~Pin
Noddy~15~15
Murphy~25~25
Dilbert~30~30
Don~37~37
Wattson~40~40
D. Name~Age~Pin
Noddy~15~2055
Murphy~25~1501
Dilbert~30~1500
Don~37~602
Wattson~40~945
E. Compilation Error or Runtime Error
Topic: Java Comparators

If you need explanation Read this topic

If you need Answer Take test on this topic

User comments below. All of them might not be correct.

Ans is B.

Posted by Gopinath Manchikanti    2014-06-17 12:59:18


ans is d..comparator implemented according to ascnd order of ages so 1st nobody wl com n so on...n adding 30 to age n 1500 to pin num

Posted by Uday Kumar    2014-06-17 13:04:05


ans d. objects r stored in ascending order .comparatr used to sorting operation of age.
while loop prints output age order 15,25,30,37,40.

Posted by Maheshwari Natarajan    2014-06-17 13:18:59


Congratulations Uday Kumar. You are this dose winner. We will send you the link using which you can claim your recharge.

Posted by Merit Campus    2014-06-18 04:12:42


© meritcampus 2019

All Rights Reserved.

Open In App