• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Sorting an Array List

 
Sarita KShetty
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ArrayList<String> st = new ArrayList<String>();
str.add("abc");
str.add("123");
str.add("xyz");
Collections.sort(st);
for(String x:str)
System.out.print(x + "");



What would be the output and could someone explain how is the contents of this array sorted?
 
Vijitha Kumara
Bartender
Posts: 3913
9
Chrome Fedora Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What would be the output


Why not try your self?

Collections.sort() sorts the specified List in to ascending order, based on the natural ordering of its elements (in this case String). Refer the API
 
Campbell Ritchie
Sheriff
Pie
Posts: 49367
62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to JavaRanch.
When Vijitha Kumara referred you to the API, that probably meant this bit, this bit and this bit.
 
Sarita KShetty
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The output is 123abcxyz i want to know as to why it is 123abcxyz ...i mean why is that the numbers come first
 
Henry Wong
author
Marshal
Pie
Posts: 21185
80
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i mean why is that the numbers come first


The ordering is based on unicode (and for the letters and numbers unicode is the same as ASCII). The numbers come first because the numbers come first on the ASCII table.

Henry
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic