import java.util.*;
class Mouse implements Comparable
{
private int i;
Mouse(int i){
this.i=i;
}
public String toString(){return "Mouse "+i;}
public int compareTo(Object o){
assert ((o!=null)&&(o instanceof Mouse));
return new Integer(i).compareTo(((Mouse)o).i);
}
}
public class TestQueue
{
public static void main(String[] args)
{
Queue <Mouse> queue=new PriorityQueue <Mouse> ();
for(int i=5;i> -1;i--)queue.add(new Mouse(i));
System.out.println(queue);
}
}
在我的及其打印的不是 Mouse 0,1,2,3,4,5,但我觉的应该是这样打印的啊
------解决方案--------------------
直接println(queue)得到的是String representation of the queue,是没有排序的。
如果你要看queue的序列,
1,用queue.poll()一个一个列出来看,
2,用Iterator来看,
就是0,1,2,3,4,5了。
------解决方案--------------------
import java.util.*;
class Mouse implements Comparable
{
private int i;
Mouse(int i){
this.i=i;
}
public String toString(){return "Mouse "+i;}
public int compareTo(Object o){
assert ((o!=null)&&(o instanceof Mouse));
return new Integer(i).compareTo(((Mouse)o).i);
}
}
public class TestQueue
{
public static void main(String[] args)
{
Queue <Mouse> queue=new PriorityQueue <Mouse> ();
for(int i=5;i> -1;i--)queue.add(new Mouse(i));
Iterator iter = queue.iterator();
while (iter.hasNext())
System.out.println(iter.next());
for(int i=5;i> -1;i--)
System.out.println(queue.poll());
}
}
------解决方案--------------------
D:\Testing> java TestQueue
Mouse 0
Mouse 2
Mouse 1
Mouse 5
Mouse 3
Mouse 4
Mouse 0
Mouse 1
Mouse 2
Mouse 3
Mouse 4
Mouse 5