I want to make a lexical sorted list of strings, so i went with the basic SortedSet
1) Set<String> words = new SortedSet<String>(){}
and realized that SortedSet is an abstract class, in which I will have to implement the comapartor method. So i went and searched on google and found out that treeSet is better and i can use its predefined comparator method.
2) SortedSet<String> words = new TreeSet<String>(){}
When went to java docs i realized that TreeSet extends AbstractSet rather than SortedSet. Question 1 - Can anyone explain how the 2nd line is still working(like i am not generalizing the Set which i would normally do instead i am using two totally different Classes with no Parent child relation). Question 2 - how to define comparator of SortedSet which will work as TreeSet. So here is the working code with TreeSet
SortedSet<String> words = new TreeSet<>();
Scanner scanner1 = new Scanner(System.in);
String s1 = scanner1.nextLine();
int a = scanner1.nextInt();
while(s1.length()>a){
words.add(s1.substring(0,a));
s1 = s1.substring(a);
}
Iterator itr = words.iterator();
while(itr!= null&&itr.hasNext()){
System.out.println(itr.next());
}
Normal Input
welcometojava
3
Expected Output
com
eto
jav
wel
Edit-1 For the answer of Question 2, i am expecting something like this
Set<String> words = new SortedSet<String>() {
@Override
public Comparator<? super String> comparator() {
return null;
}
......
I basically want to learn, how to make a basic comparator "like" in TreeSet while using SortedSet? I understand that if there is natural ordering i don't need to define a new comparator.