Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

iterating over Collection veiw of a Map

1058908Dec 6 2013 — edited Dec 7 2013

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

  1. tp.put(z,z.getName());
  2. System.out.println("innnnnsssssssssssssssss");
  3. tm.put(z,z.getName());
  4. 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 .

Comments

Processing
Locked Post
New comments cannot be posted to this locked post.

Post Details

Locked on Jan 4 2014
Added on Dec 6 2013
1 comment
467 views