Search...
FAQs
Subscribe
Pie
FAQs
Recent topics
Flagged topics
Hot topics
Best topics
Search...
Search within Beginning Java
Search Coderanch
Advance search
Google search
Register / Login
Post Reply
Bookmark Topic
Watch Topic
New Topic
programming forums
Java
Mobile
Certification
Databases
Caching
Books
Engineering
Micro Controllers
OS
Languages
Paradigms
IDEs
Build Tools
Frameworks
Application Servers
Open Source
This Site
Careers
Other
Pie Elite
all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Campbell Ritchie
Jeanne Boyarsky
Ron McLeod
Paul Clapham
Liutauras Vilda
Sheriffs:
paul wheaton
Rob Spoor
Devaka Cooray
Saloon Keepers:
Stephan van Hulst
Tim Holloway
Carey Brown
Frits Walraven
Tim Moores
Bartenders:
Mikalai Zaikin
Forum:
Beginning Java
Using a Comparator in Collections
shivang sarawagi
Ranch Hand
Posts: 159
posted 12 years ago
Number of slices to send:
Optional 'thank-you' note:
Send
// Use a custom comparator. import java.util.*; // A reverse comparator for strings. class MyComp implements Comparator<String> { public int compare(String a, String b) { String aStr, bStr; aStr = a; bStr = b; // Reverse the comparison. return bStr.compareTo(aStr); } // No need to override equals. } class CompDemo { public static void main(String args[]) { // Create a tree set. TreeSet<String> ts = new TreeSet<String>(new MyComp()); // Add elements to the tree set. ts.add("C"); ts.add("A"); ts.add("B"); ts.add("E"); ts.add("F"); ts.add("D"); // Display the elements. for(String element : ts) System.out.print(element + " "); System.out.println(); } }
I have a doubt in this code, where is the compare method called in the CompDemo class ??
The output is F E D C B A.
John Jai
Rancher
Posts: 1776
posted 12 years ago
1
Number of slices to send:
Optional 'thank-you' note:
Send
From lines 19 through 24. Since you have specified a comparator, the compare() method is called when you add each element to the TreeSet.
Read ->
http://download.oracle.com/javase/6/docs/api/java/util/TreeSet.html#TreeSet(java.util.Comparator)
Campbell Ritchie
Marshal
Posts: 79153
377
posted 12 years ago
1
Number of slices to send:
Optional 'thank-you' note:
Send
By compareTo() I presume you mean compare()?
John Jai
Rancher
Posts: 1776
posted 12 years ago
Number of slices to send:
Optional 'thank-you' note:
Send
Thanks for correcting that Campbell... i have edited my initial reply..
reply
reply
Bookmark Topic
Watch Topic
New Topic
Boost this thread!
Similar Threads
Bubble Sort Set using Comparator
TreeMap and Sorting
Repositioning an object in a TreeSet?
Doubt in collection Framework
how comparator works
More...