public abstract class Animal
{
private int order;
protected String name;
public Animal(String n)
{
name=n;
}
public void SetOrder(int ord)
{
order=ord;
}
public int getOrder()
{
return order;
}
public boolean isOlderThan(Animal a)
{
return this.order<a.getOrder();
}
}
public class AnimalQueue
{
LinkedList<Dog> dogs=new LinkedList<Dog>();
LinkedList<Cat> cats=new LinkedList<Cat>();
private int order=0;//用作时截
public void enqueue(Animal a)
{
/*order 用作某种形式的时截,以便比较够或猫插入队列的先后顺序*/
a.SetOrder(order);
order++;
if( a instanceof Dog) dogs.addList((Dog) a);
else if (a instanceof Cat) cats.addLast((Cat) a);
}
public Animal dequeueAny()
{
/*查看狗和猫的队列的首部,弹出最旧的值
*/
if(dogs.size()==0)
{
return dequeueCats();
}
else if(cats.size()==0)
{
return dequeueDogs();
}
}
Dog dog=dogs.peek();
Cat cat=cats.peek();
if(dog.isOlderThan(cat))
{
return dequeueDogs();
}
else
{
return dequeueCats();
}
public Dog dequeueDogs()
{
return dogs.poll();
}
public Cat dequeCats()
{
return cats.poll();
}
}
public class Cat extends Animal
{
public Cat(String n)
{
super(n);
}
}
public class Dog extends Animal
{
public Dog(String n)
{
super(n);
}
}
版权声明:本文为博主原创文章,未经博主允许不得转载。