Win a copy of Emmy in the Key of Code this week in the General Computing 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Junilu Lacar
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Knute Snortum
  • Devaka Cooray
  • Tim Cooke
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Ron McLeod
  • Carey Brown
Bartenders:
  • Paweł Baczyński
  • Piet Souris
  • Vijitha Kumara

Doubt in collection Framework

 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • 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
  • 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
  • Quote
  • Report post to moderator
Thanks Tomasz Sochanski...
 
You can thank my dental hygienist for my untimely aliveness. So tiny:
Java file APIs (DOC, XLS, PDF, and many more)
https://products.aspose.com/total/java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!