Menu
Topics Index
...
`

Compare Roll Number


If you need explanation Read this topic

If you need Answer Take test on this topic

Compare Roll Number
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;
    }
}

A. Amar 504
Shiva 506
Ram 513
Sanath 583
Bobby 589
B. Amar 504
Bobby 589
Ram 513
Sanath 583
Shiva 506
C. Bobby 589
Sanath 583
Shiva 506
Ram 513
Amar 504
D. 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.

Answer : B
the ArrayList is first created then the list is sorted thus we get a sortted arraylist as the o/p

Posted by Deepak Kumar Yadav    2014-08-25 12:38:19


ns is a list is sorted in ascnding order

Posted by Uday Kumar    2014-08-25 12:41:59


ans a.
sort based on rol num.
so output is sortd ascended ordr n printd

Posted by Maheshwari Natarajan    2014-08-25 12:42:28


a...arraylist is created n sortng is done on the basis of roll numbr

Posted by Asma Mujtaba Khan    2014-08-25 12:42:44


a

Posted by Rayapudi Ramya    2014-08-25 14:17:17


ans A userdefined comparator will sort the values in ascending manner of rollnumbers

Posted by Ashok Reddi    2014-08-25 15:46:27


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-08-26 04:50:39


© meritcampus 2019

All Rights Reserved.

Open In App