Hi All ,
There are 2 TreeMaps <Zinger,String>:
tp : it takes a Comparator in its constructor.
tm : it has a no-argument constructor.
Then both Trees are converted to their Collection view and then both collections are given Iterators .
Zinger implements Comparable , so has compareTo() which in turn is using Zinger’s getName for comparing two Zingers.
Similarly , for the TreeMap which takes Comparator , so Comparator is implemented via class Cataclysm
import java.util.*;
import java.util.Comparator;
class Zinger implements Comparable<Zinger>
{
int i;
static int c;
Zinger(int m)
{
double d=m*Math.random();
this.i=(int)d;
System.out.println(this.i+"is i of "+this.hashCode()+"currently c is :"+c);
c++;
}
int getRandom()
{
return i;
}
String getName()
{
return ("Zinger"+c);
}
public int compareTo(Zinger o2){
return (this.getName()).compareToIgnoreCase(o2.getName());
}
}
public class TreeMapz
{
public static void main(String args[])
{
TreeMap tm = new TreeMap<Zinger,String>();
Cataclysm cr= new Cataclysm();
TreeMap tp= new TreeMap<Zinger,String>(cr);
for (int i=0;i<9;i++)
{
Zinger z=new Zinger(i);
- tp.put(z,z.getName());
- System.out.println("innnnnsssssssssssssssss");
- tm.put(z,z.getName());
- System.out.println("ooooutssssssssssssssssss");
}
Collection cp =tp.values();
Collection cm =tm.values();
Iterator<Map.Entry<Zinger,String>> itp=cp.iterator();
Iterator itm=cm.iterator();
while(itp.hasNext())
{
System.out.println("this is "+itp.next());
//System.out.println(cm.next());
}
while(itm.hasNext())
{
System.out.println("this is widout comparator"+itm.next());
}
/*for(Map.Entry<Zinger,String> e: tp.entrySet())
{
System.out.println(e.getKey()+""+"is the key to zinger"+e.getKey().getName());
System.out.println(e.getValue()+""+"is value to zinger"+e.getKey().getName());
}*/
}
}
class Cataclysm implements Comparator<Zinger>
{
public int compare(Zinger o1, Zinger o2)
{
if (o1.getRandom()< o2.getRandom())
return 1;
else if(o1.getRandom()> o2.getRandom())
return -1;
else
return 0;
}
}
'm not able to understand why next() in the code is calling getName() of Zinger on executing the code .