Link to home
Start Free TrialLog in
Avatar of gudii9
gudii9Flag for United States of America

asked on

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
SOLUTION
Avatar of ozo
ozo
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of gudii9

ASKER

How B <a
Please advise
In ASCII, ISO/IEC 8859 or Unicode, 'B' == 66, 'a' == 97
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.
Avatar of gudii9

ASKER

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
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

Avatar of gudii9

ASKER

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
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).
Avatar of gudii9

ASKER

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
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial