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?
 
gurpsbassiCommented:
yes but your method signature will be something like
compare(Fruit f1, Fruit f2)
0
 
ozoCommented:
'A' < 'B'
'B' < 'a'
'a' < 'b'
0
 
gudii9Author Commented:
How B <a
Please advise
0
Cloud Class® Course: Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

 
ozoCommented:
In ASCII, ISO/IEC 8859 or Unicode, 'B' == 66, 'a' == 97
0
 
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.