Win a copy of Fixing your Scrum this week in the Agile forum!
  • 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
  • Ron McLeod
  • Paul Clapham
  • Rob Spoor
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Junilu Lacar
  • Tim Cooke
Saloon Keepers:
  • Tim Holloway
  • Piet Souris
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
Bartenders:
  • Frits Walraven
  • Himai Minh

Doubt in collection Framework

 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
import java.util.Comparator;

import java.util.TreeSet;

class MyComp implements Comparator<String>{

@Override
public int compare(String o1, String o2) {
// TODO Auto-generated method stub
String aStr, bStr;
aStr= o1;
bStr=o2;
return bStr.compareTo(aStr);
}

}

public class TreeSetDemo {

public static void main(String[] args) {

TreeSet<String> ts = new TreeSet<String>(new MyComp());
ts.add("c");
ts.add("a");
ts.add("b");
ts.add("e");
ts.add("f");
ts.add("d");

for (String element : ts){
System.out.println(element+ " ");
//System.out.println();
}

}

}

Hello,

Can some explain how out is coming as
f
e
d
c
b
a

please explain this line: return bStr.compareTo(aStr);

A/C to my knowledge bStr.compareTo(aStr) returns 1,0,-1. So how output is returning as e d c b a ?
 
Ranch Hand
Posts: 47
Eclipse IDE Oracle Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
compare() is used by TreeSet to determine order of its elements.
You overrides String.compare() in your class. However inside your overriden compare(String a, String b) method you return b.compare(a) instead of a.compare(b), so natural lexicographic order (which is returned from String.compare()) is reversed.

EDIT: not compareTo() but compare() ;)
 
ersatish kumar
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Tomasz Sochanski...
 
Montana has cold dark nights. Perfect for the heat from incandescent light. Tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic