-1
public class BioDiesel {
            public static void main(String args[]) {
                LinkedList<String> list = new LinkedList<String>();
                list.add("BbB1");
                list.add("bBb2");
                list.add("bbB3");
                list.add("BBb4");
                Collections.sort(list);
                for (String str : list) {
                    System.out.print(str + ":");
                }
            }
}

Code is running fine and displaying the result in a sorted order. Can someone explain how sorting is performed in case of above provided String elements?

How come the output is :

BBb4:BbB1:bBb2:bbB3:
Ravi.Kumar
  • 761
  • 2
  • 12
  • 34
  • Please try and improve your question. Sorry but it’s hard to understand what are you asking. Instead of pasting some code with a short cover note, try providing more exposition: what's the problem you're solving, what's your intended solution, what obstacles you're facing, etc. – Helgi Jul 14 '12 at 11:04

2 Answers2

1

Assuming that I understood your question correctly, this should work:

Collections.sort(list, String.CASE_INSENSITIVE_ORDER);

String.CASE_INSENSITIVE_ORDER is a comparator class that disregards the case when comparing strings.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

Let's start with the documentation for Collections.sort:

Sorts the specified list into ascending order, according to the natural ordering of its elements.

What's the natural ordering of a string? String can tell us:

The comparison is based on the Unicode value of each character in the strings.

And of course, the unicode value of b is higher than the unicode value of B.

If you want a case-insensitive sort, there's a form of sort that takes a Comparator, and String helpfully provides a pre-made CASE_INSENSITIVE_ORDER comparator.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875