Menu
Topics Index
...
`

Sort Alphabets


If you need explanation Read this topic

If you need Answer Take test on this topic

Sort Alphabets
What will be the output of the following program?
import java.util.*;
public class SortAlphabets {
    public static void main(String[] args) {
        Alphabets a = new Alphabets();
        a.add('c').add('z').add('A').add('k').add('i').add('C');
        Collections.sort(a.alphabets, a);
        System.out.println("\n"+a.alphabets);
    }
}
class Alphabets implements Comparator<Character> {
    List<Character> alphabets = new ArrayList<Character>();
        Alphabets add(Character c) {
        alphabets.add(c);
        return this;
    }
    public int compare(Character arg0, Character arg1) {
        int result = arg0.compareTo(arg1);
        System.out.print("" + arg0 + arg1 + result + " ");
        return 0;
    }
}

A. cz-23 zA57 cA34 zk15 ck-8 zi17 ki2 ci-6 zC55 kC40 iC38 cC32 AC-2 
[A, C, c, i, k, z]
B. cz-23 zA57 Ak-42 ki2 iC38 
[c, z, A, k, i, C]
C. cz-23 cA34 Ak-42 ck-8 zk15 Ai-40 ci-6 ki2 AC-2 cC32 
[z, k, i, c, C, A]
D. Some other output or Compilation Error
E. 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 D. Output is
zc23 Az-57 kA42 ik-2 Ci-38
[c, z, A, k, i, C]
First c and z are compared which results in 23 (the difference between their numeric values) and next A and z is compared and so on..

Posted by Nikhil Sulibhavi    2014-04-11 13:49:31


Ans is D...the elements in the list wont get sorted..1st tm arg0 wl get 'z'  n arg1 wl get 'c'..so compareTo wi Giv z-c--23 n zc23 wl printed..next tim A-z which wl giv -57 so zA-57 wl get printed so on...

OP: zc23 Az-57 kA42 ik-2 Ci-38
[c, z, A, k, i, C]

Posted by Uday Kumar    2014-04-11 14:03:06


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

Posted by Merit Campus    2014-04-14 04:20:27


© meritcampus 2019

All Rights Reserved.

Open In App