University of Toronto - Fall 2000
Department of Computer Science

Week 8 - Book class with Vector

Let's rewrite the Book class so that it uses a Vector. We'll add a constructor, so that the Vector can be initialized there. Because Vectors are objects, they have to be instantiated before you can use them.

import java.util.*;
class Book {
	private String title; 	   // Book title
	private Vector barCode;  // Book bar codes

	// ... omitting many other methods

	public Book (String t) {
		title = t;
		barCode = new Vector();
	}

	public void addBarCode (String code) {
		barCode.addElement(code);
	}

	// Print contents of this Book on one line.
	public String toString () {
		String result = "Title: " + title + " Codes:";
		for (int i = 0; i < barCode.size(); i++) {
			result += " " +(String)barCode.elementAt(i);
		}
		return result;
	}
}

public class Library {
	public static void main (String[] args) {
		Book b1 = new Book("Jurasic Park");
		b1.addBarCode("3423-0");
		System.out.println(b1);
		b1.addBarCode("3424-1");
		System.out.println(b1);
	}
}

Output

Title: Jurasic Park Codes: 3423-0
Title: Jurasic Park Codes: 3423-0 3424-1