⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 auctionbid.java

📁 java 完全探索的随书源码
💻 JAVA
字号:
import java.util.*;import java.text.NumberFormat;public class AuctionBid implements Comparable {  // class holds the bidder's name and the amount bid  String bidder;  int amount;  public AuctionBid(String name, int bid) {    bidder = name;    amount = bid;  }  public String toString() {    // get a currency formatter to make the output look nice    NumberFormat formatter = NumberFormat.getCurrencyInstance();    return bidder + " bid " + formatter.format(amount);  }  // implement Comparable interface  public int compareTo( Object other ) {    // this method defines the natural ordering of    // the class to be based on ascending bid amount    AuctionBid otherBid = (AuctionBid)other;    if ( otherBid == null ) {      return 1;    }    if ( this.equals(otherBid) || (amount == otherBid.amount) ) {      return 0;    }    return ( otherBid.amount < amount ) ? 1 : -1;  }  // define a Comparator that instead sorts on the bidder's name  static class BidComparator implements Comparator, java.io.Serializable {    public int compare(Object o1, Object o2) {      AuctionBid firstBid = (AuctionBid)o1;      AuctionBid secondBid = (AuctionBid)o2;      if ( (firstBid == null) || (firstBid.bidder == null) ) {        return ((secondBid == null) || (secondBid.bidder == null)) ? 0 : -1;      }      if ( (secondBid == null) || (secondBid.bidder == null) ) {        return 1;      }      // String implements Comparable, so let it do the work      return firstBid.bidder.compareTo(secondBid.bidder);    }  }  public static void main( String args[] ) {    // fill a list with 5 bids    ArrayList bidList = new ArrayList();    for ( int i=0; i<5; i++ ) {      // generate a random number 0-100 for a bid amount      bidList.add( new AuctionBid("Bidder" + i, (int)(Math.random()*100)) );    }    // sort the bids in natural order and display them    Collections.sort( bidList );    System.out.println("Natural order sort by bid amount");    System.out.println( bidList );    // impose a different sort using a Comparator    Collections.sort( bidList, new BidComparator() );    System.out.println("Comparator sort by bidder name");    System.out.println( bidList );  }}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -