使用してJavaの優先度つきキュープライオリティキュー

 

サンプルコード

パッケージcom.example.base.concurrent。

輸入はjava.util.Comparator。
輸入java.util.PriorityQueue。

パブリック クラスMyPriorityQueue { 

    公共 静的 ボイドメイン(文字列[]引数){ 
        FOO()。
    } 
    
    プライベート 静的 ボイドのfoo(){ 
        優先度つきキュー <ユーザー>キュー= generateQueue(NULL )。
        System.out.println( "****** ******順序なしでキューを読みます" );
        (ユーザーユーザー:キュー){ 
            System.out.printlnは(ユーザ)。
        } 
        // キュー= generateQueue()。
        System.out.println( "****** ******と読むオーダー・キュー" );
         しばらく(!Queue.isEmpty()){ 
            System.out.printlnは(queue.poll()); 
        } 
        
        // キュークラス同等のインタフェースを使用しないときに生成コンパレータ使用 
        > -キューgenerateQueue =((X、Y){
             int型 -デルタ= y.getAgeを(); x.getAge()
             を返す(0 -1 <デルタ? == 0デルタ:?1 ); 
        }); 
        のSystem.out.println( "****** ******コンパレータ順序で読み出しキュー" );
         ながら(!queue.isEmpty()){ 
            System.out.println(queue.poll());  
        }
    }

    / ** 
     * @param 比較する比較要素キューの優先順位コンパレータ
     * nullでない場合は、基本パリティコンパレータ、コンパレータの優先順位は
     、それがnullの場合*、要素compareToメソッド(継承は、Comparableインタフェースを必要とします)
     * @return 
     * / 
    プライベート 静的優先度つきキュー<ユーザー> generateQueue(コンパレータ<ユーザー> コンパレータ){ 
        優先度つきキュー <ユーザー>キュー= 新しい新しい優先度つきキュー<> コンパレータ)
         のためにint型、私は> 20であり、I 30 = i-- ){ 
            queue.add(新しい新しいユーザー(I、 "GC" + I)); 
        } 
        を返すキュー; 
    }
    
    プライベート 静的 クラスのユーザーは、実装同等<ユーザー> {
         プライベート int型の年齢を、
        プライベート文字列名; 
        
        パブリックユーザー(int型の年齢、文字列名){
             この .age = 年齢;
            この .nameの= 名前; 
        } 
        公共 INT getAge(){
             戻り年齢; 
        } 
        @Override 
        公共 のint のcompareTo(ユーザO){
             int型のデルタ= この .getAge() - o.getAge()。
            リターン・デルタ<0?-1:(デルタ== 0:1 )。
        } 
        @Override 
        パブリック文字列のtoString(){
             戻り "ユーザー[年齢=" +年齢+ "NAME =" +名+ "]" 
        } 
    } 
}

業績

******読み取りキュー順序無し****** 
ユーザ[年齢 = 21、名前= GC21] 
ユーザー[年齢 = 22、名前= gc22] 
ユーザー[年齢 = 25、名前= GC25] 
ユーザー[年齢 = 24、名前= gc24] 
ユーザー[年齢 = 23、名前= gc23] 
ユーザー[年齢 = 29、名前= gc29] 
ユーザー[年齢 = 26、名前= gc26] 
ユーザー[年齢 = 30、名前= gc30] 
ユーザー[年齢 = 27、名前= gc27] 
ユーザー[年齢 = 28、名前= gc28]
順序******読み取りキュー****** 
ユーザ[年齢 = 21、名前= GC21] 
ユーザー[年齢 = 22、名前=gc22] 
ユーザー[年齢 = 23、名前= gc23] 
ユーザー[年齢 = 24、名前= gc24] 
ユーザー[年齢 = 25、名前= GC25] 
ユーザー[年齢 = 26、名前= gc26] 
ユーザー[年齢 = 27、名前= gc27] 
ユーザー[年齢 = 28、名前= gc28] 
ユーザー[年齢 = 29、名前= gc29] 
ユーザー[年齢 = 30、名前= gc30]
 ****** order2と読みキュー****** 
ユーザー[年齢 = 30、名前= gc30] 
ユーザー[年齢 = 29、名前= gc29] 
ユーザー[年齢 = 28、名前= gc28] 
ユーザー[年齢 = 27、名前= gc27] 
ユーザー[年齢= 26、名前= gc26] 
ユーザー[年齢 = 25、名前= GC25] 
ユーザー[年齢 = 24、名前= gc24] 
ユーザー[年齢 = 23、名前= gc23] 
ユーザー[年齢 = 22、名前= gc22] 
ユーザー[年齢 = 21、名前= GC21]

 

おすすめ

転載: www.cnblogs.com/gc65/p/11183787.html