4.11 New Library and Book Code

     

Example 4-23 gives the code for the version of Book referenced in this chapter.

Example 4-23. The class Book
 Book.java public class  Book  {    private String title = "";    private String author = "";    Book(String title, String author) {       this.title = title;       this.author = author;    }    public String getTitle( ) { return title; }    public String getAuthor( ) { return author; } } 

The code for the final version of Library is given in Example 4-24. It uses a Hashtable to store the collection of Book s.

Example 4-24. The class Library
 Library.java import java.util.*; public class  Library  {    private Hashtable books;    Library( ) {       books = new Hashtable( );    }    public void addBook( Book book ) {       books.put( book.getTitle( ), book );    }    public Book getBook( String title ) {       return (Book)books.get( title );    }    public Book getBook( String title, String author ) {       return (Book)books.get( title );    }    public Vector getBooks( String author ) {       Vector auth_books = new Vector( );       for ( Enumeration e = books.elements( ); e.hasMoreElements( ); ) {          Book book = (Book)e.nextElement( );          if ( book.getAuthor( ).equals(author) )              auth_books.add( book );       }       return auth_books;       }    public void removeBook( String title ) throws Exception {       if ( books.remove( title ) == null )          throw new Exception("Book not found");    }    public int getNumBooks( ) {       return books.size( );    }    public void empty( ) {       books.clear( );    } } 



Unit Test Frameworks
Unit Test Frameworks
ISBN: 0596006896
EAN: 2147483647
Year: 2006
Pages: 146
Authors: Paul Hamill

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net