treeset example

when i ran below code

import java.util.TreeSet;


public class All {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		TreeSet<String> names = new TreeSet<String>();
		names.add("aa");
		names.add("Bb");
		names.add("Ab");
		names.add("baa");
		
		System.out.println("size is"+names.size());
		for(String name:names)
			System.out.println(name);
		
		

	}

}

Open in new window


i got output as below

size is4
Ab
Bb
aa
baa


i wonder why aa came at 3rd. please advise
LVL 7
gudii9Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

ozoCommented:
'A' < 'B'
'B' < 'a'
'a' < 'b'
0
gudii9Author Commented:
How B <a
Please advise
0
ozoCommented:
In ASCII, ISO/IEC 8859 or Unicode, 'B' == 66, 'a' == 97
0
C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

mccarlIT Business Systems Analyst / Software DeveloperCommented:
In other words, all the Uppercase letter come before any of the Lowercase letters.

If you DON'T want this to happen, then you can construct your Treeset and pass it a specific Comparator instance that can perform a case INSENSITIVE comparison.
0
gudii9Author Commented:
If you DON'T want this to happen, then you can construct your Treeset and pass it a specific Comparator instance that can perform a case INSENSITIVE comparison.

Open in new window


how to do this. Please advise
0
gurpsbassiCommented:
Try something like:

public class All {

        /**
	 * @param args
	 */
	public static void main(String[] args) {
		TreeSet<String> names = new TreeSet<String>(new CaseInsensitiveComparator());
		names.add("aa");
		names.add("Bb");
		names.add("Ab");
		names.add("baa");
		
		System.out.println("size is"+names.size());
		for(String name:names)
			System.out.println(name);
	}
	
	static class CaseInsensitiveComparator implements Comparator<String>{
		
	  @Override
	  public int compare(String s1, String s2) {
            if(s1 == null && s2== null){
            	return 0;
            }else if (s1 == null){
            	return -1;
            }else if (s2 == null){
            	return 1;
            }
            return s1.toLowerCase().compareTo(s2.toLowerCase());
          }
	}
}

Open in new window

0
gudii9Author Commented:
import java.util.Comparator;
import java.util.TreeSet;

public class All {

        /**
	 * @param args
	 */
	public static void main(String[] args) {
		TreeSet<String> names = new TreeSet<String>(new CaseInsensitiveComparator());
		names.add("aa");
		names.add("Bb");
		names.add("Ab");
		names.add("baa");
		
		System.out.println("size is"+names.size());
		for(String name:names)
			System.out.println(name);
	}
	
	static class CaseInsensitiveComparator implements Comparator<String>{
		
	  @Override
	  public int compare(String s1, String s2) {
            if(s1 == null && s2== null){
            	return 0;
            }else if (s1 == null){
            	return -1;
            }else if (s2 == null){
            	return 1;
            }
            return s1.toLowerCase().compareTo(s2.toLowerCase());
          }
	}
}

Open in new window


above code produced below output

size is4
aa
Ab
baa
Bb


i wonder how compare method got called and what is s1 and s2.

please advise
0
gurpsbassiCommented:
Ok Lets go back to the beginning.
Java.lang.String implements the Comparable interface.

You are inserting String's into your TreeSet instance. If you look at the API documentation for java.util.TreeSet you will find that elements are ordered by their natural ordering. What this means is that the String class compareTo() method will be utilized to determine the order of the elements since String implements Comparable.

Now if you look at the API documentation for java.lang,String and you will find the compareTo() method states that it compares two String's lexicographically. What this means is that it will compare them based on the unicode value of each of the String's. This is clearly not what you want.


If you look at how I have initialized the TreeSet:
TreeSet<String> names = new TreeSet<String>(new CaseInsensitiveComparator());

I have passed it an instance of the CaseInsensitiveComparator class that I created. What this means is that it will no longer use the compareTo() method of the String class. Instead it will make use of this new custom comparator. If you look at the API documentation for java.util.TreeSet you will see the documentation states that the comparator passed into the constructor of the TreeSet takes precedence over the natural ordering of the elements.

The compare() method is called automatically by the Collection. You don't need to explicitly call it. The variables s1 and s2 are simply method arguments representing two Strings that can be compared. If your collection had objects of type Fruit, then I would signature this method as compare(Apple a1, Apple a2).
0
gudii9Author Commented:
if(s1 == null && s2== null){
                  return 0;
            }else if (s1 == null){
                  return -1;
            }else if (s2 == null){
                  return 1;
            }
            return s1.toLowerCase().compareTo(s2.toLowerCase());

above method body is same even if it is of type fruit right(of course a1 and a2 comes instead of s1 and s2)

Please advise
0
gurpsbassiCommented:
yes but your method signature will be something like
compare(Fruit f1, Fruit f2)
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java EE

From novice to tech pro — start learning today.