Menu
Question Index
...

What will be the output of the following program?

import java.util.*;
public class ComparatorTest {
    public static void main(String arg[]) {
        List<Student> list = new ArrayList<Student>();
        list.add(new Student("Ram", 513));
        list.add(new Student("Sanath", 583));
        list.add(new Student("Amar", 504));
        list.add(new Student("Shiva", 506));
        list.add(new Student("Bobby", 589));
        Collections.sort(list, new Comparator<Student>() {
            public int compare(Student a1, Student a2) {
                return a1.rollno - a2.rollno;
            }
        });
        for (int i = 0; i < list.size(); i++) {
            Student a = list.get(i);
            System.out.println(a.name + " " + a.rollno);
        }
    }
}
class Student {
    String name;
    int rollno;
    public Student(String name, int rollno) {
        this.name = name;
        this.rollno = rollno;
    }
}


Amar 504
Shiva 506
Ram 513
Sanath 583
Bobby 589
Amar 504
Bobby 589
Ram 513
Sanath 583
Shiva 506
Bobby 589
Sanath 583
Shiva 506
Ram 513
Amar 504
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