Requirements:
1. Users can place instances of cat classes and dog classes into queues
2. The user can take out all the instances in the queue in the order in which they are placed
Ideas:
A class Petenterqueue is designed to record the timestamp of each element placed in the queue and, when taken out, to determine the elements taken out of the dog queue or cat queue by timestamp
The specific code is as follows:
Public classPet {PrivateString type; PublicPet (String type) { This. Type =type; } PublicString Getpettype () {return This. Type; }} Public classDogextendspet{ PublicDog () {Super("Dog") ; }} Public classCatextendspet{ PublicCat () {Super("Cat") ; }} Public classPetenterqueue {PrivatePet Pet; Private Longcount; PublicPetenterqueue (Pet Pet,Longcount) { This. Pet =Pet; This. Count =count; } PublicPet Getpet () {return This. Pet; } Public LongGetCount () {return This. Count; } PublicString Getenterpettype () {return This. Pet.getpettype (); }}Importjava.util.LinkedList;ImportJava.util.Queue; Public classDogcatqueue {PrivateQueue<petenterqueue>Dogq; PrivateQueue<petenterqueue>CATQ; Public Longcount; PublicDogcatqueue () { This. Dogq =NewLinkedlist<petenterqueue>() ; This. CATQ =NewLinkedlist<petenterqueue>() ; This. Count = 0 ; } Public voidAdd (Pet pet) {if(Pet.getpettype (). Equals ("Dog")) { This. Dogq.add (NewPetenterqueue (PET, This. count++)) ; } Else if(Pet.getpettype (). Equals ("Cat")) { This. Catq.add (NewPetenterqueue (PET, This. count++)) ; } Else Throw NewRuntimeException ("Err, not dog or cat") ; } PublicPet Pollall () {if(! This. Dogq.isempty () &&! This. Catq.isempty ()) { if( This. Dogq.peek (). GetCount () < This. Catq.peek (). GetCount ()) { return This. Dogq.poll (). Getpet (); } Else return This. Catq.poll (). Getpet (); } Else if(! This. Dogq.isempty ()) { return This. Polldog (); } Else if(! This. Catq.isempty ()) { return This. Pollcat (); } Else { Throw NewRuntimeException ("Err, Quque is empty") ; } } PublicDog Polldog () {if(! This. Isdogqueueempty ()) { return(DOG) This. Dogq.poll (). Getpet (); } Else Throw NewRuntimeException ("Dog queue is empty") ; } PublicCat Pollcat () {if(! This. Iscatqueueempty ()) { return(Cat) This. Catq.poll (). Getpet (); } Else Throw NewRuntimeException ("Cat queue is empty") ; } Public BooleanIsEmpty () {return This. Dogq.isempty () && This. Catq.isempty (); } Public BooleanIsdogqueueempty () {return This. Dogq.isempty (); } Public BooleanIscatqueueempty () {return This. Catq.isempty (); }}
Cat and Dog queue