Home  Listings  By Name  By Subject  Email  www.tomswan.com  Help 

Java 2 Just Click! Solutions

Chapter 15 Listings

© 2001 by Tom Swan. All rights reserved. Updated: 6/4/01 12:20:54 PM

Return to Listings page
Switch to Solutions by name page
Switch to Solutions by subject page


Listing 15-1 List.txt Page 277

Return to top
001: // List interface methods not also in Collection
002: boolean addAll(int index, Collection c);
003: Object get(int index);
004: Object set(int index, Object element);
005: void add(int index, Object element);
006: Object remove(int index);
007: int indexOf(Object o);
008: int lastIndexOf(Object o);
009: ListIterator listIterator();
010: ListIterator listIterator(int index);
011: List subList(int fromIndex, int toIndex);
Return to top

Listing 15-2 ArrayList.txt Page 278

Return to top
001: // ArrayList methods
002: public ArrayList();
003: public ArrayList(int initialCapacity);
004: public ArrayList(Collection c);
005: public void trimToSize();
006: public void ensureCapacity(int minCapacity);
007: public Object clone();
Return to top

Listing 15-3 LinkedList.txt Page 279

Return to top
001: // LinkedList methods
002: public LinkedList();
003: public LinkedList(Collection c);
004: public Object getFirst();
005: public Object getLast();
006: public Object removeFirst();
007: public Object removeLast();
008: public void addFirst(Object o);
009: public void addLast(Object o);
Return to top

Listing 15-4 ArrayListDemo/Chart.java Page 281

Return to top
001: public class Chart implements Comparable {
002:  public int number;
003:  public String name;
004:  public long scale;
005:  public Chart(int number, String name, long scale) {
006:   this.number = number;
007:   this.name = name;
008:   this.scale = scale;
009:  }
010:  public int compareTo(Object o) {
011:   Chart other = (Chart)o;
012:   return name.compareTo(other.name);
013:  }
014:  public String toString() {
015:   return number + "  " + name + "  1:" + scale;
016:  }
017: }
Return to top

Listing 15-5 ArrayListDemo/ArrayListDemo.java Page 282

Return to top
001: import java.util.List;
002: import java.util.ArrayList;
003: import java.util.Collections;  // plural!
004: import Chart;
005: 
006: class ArrayListDemo {
007: 
008: // Display a List of objects
009:  public static void showContainer(List c) {
010:   for (int i = 0; i < c.size(); i++)
011:    System.out.println(c.get(i).toString());
012:  }
013: 
014:  public static void main(String args[]) {
015: // Construct the container
016:   ArrayList charts = new ArrayList();
017: 
018: // Insert some Data objects
019:   charts.add(new Chart(11013, "Morehead City Hrbr ", 12500));
020:   charts.add(new Chart(11552, "Neuse River        ", 40000));
021:   charts.add(new Chart(11428, "Dry Tortugas       ", 30000));
022:   charts.add(new Chart(11420, "Havana to Tampa Bay", 470940));
023:   charts.add(new Chart(25641, "Virgin Islands     ", 100000));
024:   charts.add(new Chart(26341, "Bermuda Islands    ", 50000));
025: 
026: // Sort and display container
027:   Collections.sort(charts);  
028:   showContainer(charts);
029:  }
030: }
Return to top

Listing 15-6 ComparatorDemo/Chart.java Page 285

Return to top
001: import java.util.Comparator;
002: 
003: public class Chart implements Comparable {
004: // Constants
005:  final static int BYNUMBER = 1;
006:  final static int BYNAME = 2;
007:  final static int BYSCALE = 3;
008: 
009:  public int number;
010:  public String name;
011:  public long scale;
012:  public Chart(int number, String name, long scale) {
013:   this.number = number;
014:   this.name = name;
015:   this.scale = scale;
016:  }
017:  public int compareTo(Object o) {
018:   Chart other = (Chart)o;
019:   return name.compareTo(other.name);
020:  }
021:  public String toString() {
022:   return number + "  " + name + "  1:" + scale;
023:  }
024: 
025: // Comparator "factory" methods
026:  public static final Comparator byNumber() {
027:   return new ChartComparator(BYNUMBER);
028:  }
029:  public static final Comparator byName() {
030:   return new ChartComparator(BYNAME);
031:  }
032:  public static final Comparator byScale() {
033:   return new ChartComparator(BYSCALE);
034:  }
035: 
036: // Private inner Comparator class
037:  private static class ChartComparator implements Comparator {
038: 
039:   private int compType;  // Type of comparison to perform
040: 
041:   // Constructor saves comparison type identifier
042:   ChartComparator(int compType) {
043:    this.compType = compType;  // BYNUMBER, BYNAME, or BYSCALE
044:   }
045: 
046:   // Implement the Comparator interface's method
047:   public int compare(Object o1, Object o2) {
048:    Chart c1 = (Chart)o1;  // Type cast objects to Charts
049:    Chart c2 = (Chart)o2;
050:    switch (compType) {
051:     case BYNUMBER:
052:      return (c1.number < c2.number ? -1 : 
053:       (c1.number == c2.number ? 0 : 1));
054:     case BYNAME:
055:      return c1.name.compareTo(c2.name);
056:     case BYSCALE:
057:      return (c1.scale < c2.scale ? -1 : 
058:       (c1.scale == c2.scale ? 0 : 1));
059:     default:
060:      return 0;  // Satisfy compiler; can't happen
061:    }
062:   }
063:  } // private inner class
064: } // Chart class
Return to top

Listing 15-7 ComparatorDemo/ComparatorDemo.java Page 287

Return to top
001: import java.util.List;
002: import java.util.ArrayList;
003: import java.util.Collections;  // plural!
004: import Chart;
005: 
006: class ComparatorDemo {
007: 
008: // Display a List of objects
009:  public static void showContainer(List c) {
010:   for (int i = 0; i < c.size(); i++)
011:    System.out.println(c.get(i).toString());
012:  }
013: 
014:  public static void main(String args[]) {
015: // Construct the container
016:   ArrayList charts = new ArrayList();
017: 
018: // Insert some Data objects
019:   charts.add(new Chart(11013, "Morehead City Hrbr ", 12500));
020:   charts.add(new Chart(11552, "Neuse River        ", 40000));
021:   charts.add(new Chart(11428, "Dry Tortugas       ", 30000));
022:   charts.add(new Chart(11420, "Havana to Tampa Bay", 470940));
023:   charts.add(new Chart(25641, "Virgin Islands     ", 100000));
024:   charts.add(new Chart(26341, "Bermuda Islands    ", 50000));
025: 
026: // Sort and display container three ways:
027:   Collections.sort(charts, Chart.byNumber());
028:   System.out.println("/nBy number:");  
029:   showContainer(charts);
030: 
031:   Collections.sort(charts, Chart.byName());
032:   System.out.println("/nBy name:");  
033:   showContainer(charts);
034: 
035:   Collections.sort(charts, Chart.byScale());
036:   System.out.println("/nBy scale:");  
037:   showContainer(charts);
038:  }
039: }
Return to top

Listing 15-8 Iterator.txt Page 288

Return to top
001: // Iterator interface methods
002: boolean hasNext();
003: Object next();
004: void remove();
Return to top

Listing 15-9 IteratorDemo/IteratorDemo.java Page 289

Return to top
001: import java.util.Iterator;
002: import java.util.Collection;
003: import java.util.ArrayList;
004: import Chart;
005: 
006: class IteratorDemo {
007: 
008: // Display a Collection using an Iterator
009:  public static void showContainer(Collection c) {
010:   Chart achart;
011:   Iterator I = c.iterator();  // Get Iterator for Collection
012:   while (I.hasNext()) {       // Always call hasNext()
013:    achart = (Chart)I.next();  //  before calling next()
014:    System.out.println(achart.toString());
015:   }
016:  }
017: 
018:  public static void main(String args[]) {
019: // Construct the container
020:   ArrayList charts = new ArrayList();
021: 
022: // Insert some Data objects
023:   charts.add(new Chart(11013, "Morehead City Hrbr ", 12500));
024:   charts.add(new Chart(11552, "Neuse River        ", 40000));
025:   charts.add(new Chart(11428, "Dry Tortugas       ", 30000));
026:   charts.add(new Chart(11420, "Havana to Tampa Bay", 470940));
027:   charts.add(new Chart(25641, "Virgin Islands     ", 100000));
028:   charts.add(new Chart(26341, "Bermuda Islands    ", 50000));
029: 
030:   System.out.println("/nCharts shown by an Iterator object");
031:   showContainer(charts);
032: 
033:   // Erase first object
034:   Iterator I = charts.iterator();  // Get an Iterator object
035:   if (I.hasNext()) {               // Always call hasNext() and
036:    Chart c = (Chart)I.next();      //  next() before 
037:    I.remove();                     //  calling remove()
038:   }
039:   System.out.println("/nAfter removing first object");
040:   showContainer(charts);
041: 
042:   // Use Iterator to remove all objects
043:   I = charts.iterator();  // Get a fresh Iterator
044:   while (I.hasNext()) {
045:    I.next();    // Don't need to save returned object
046:    I.remove();  // Removes object last returned by next()
047:   }
048:   System.out.println("/nAfter removing all objects");
049:   System.out.println("Container size = " + charts.size());
050:  }
051: }
Return to top

Listing 15-10 LinkedListDemo/LinkedListDemo.java Page 292

Return to top
001: import java.util.List;
002: import java.util.LinkedList;
003: import java.util.ListIterator;
004: import java.util.Collections;
005: import Chart;
006: 
007: class LinkedListDemo {
008: 
009:  static final boolean FORWARD = true;
010:  static final boolean REVERSE = false;
011: 
012: // Display a LinkedList using a ListIterator
013: //  in forward or reverse order
014:  public static void showContainer(List c, boolean forward) {
015:   Chart achart;
016:   if (forward) {
017:    // Show in forward order
018:    ListIterator I = c.listIterator();
019:    while (I.hasNext()) {
020:     achart = (Chart)I.next();
021:     System.out.println(achart.toString());
022:    }
023:   } else {
024:    // Show in reverse order
025:    ListIterator I = c.listIterator(c.size());
026:    while (I.hasPrevious()) {
027:     achart = (Chart)I.previous();
028:     System.out.println(achart.toString());
029:    }
030:   }
031:  }
032: 
033:  public static void main(String args[]) {
034: // Construct the container
035:   LinkedList charts = new LinkedList();  // Can't specify size
036:   Chart achart;  // For accessing the container's objects
037: 
038: // Insert some Data objects
039:   charts.add(new Chart(11013, "Morehead City Hrbr ", 12500));
040:   charts.add(new Chart(11552, "Neuse River        ", 40000));
041:   charts.add(new Chart(11428, "Dry Tortugas       ", 30000));
042:   charts.add(new Chart(11420, "Havana to Tampa Bay", 470940));
043:   charts.add(new Chart(25641, "Virgin Islands     ", 100000));
044:   charts.add(new Chart(26341, "Bermuda Islands    ", 50000));
045: 
046:   // Sort the LinkedList container
047:   Collections.sort(charts);
048: 
049:   // Display head and tail objects
050:   System.out.println("/nHead object is:");
051:   achart = (Chart)charts.getFirst();
052:   System.out.println(achart.toString());
053:   System.out.println("/nTail object is:");
054:   achart = (Chart)charts.getLast();
055:   System.out.println(achart.toString());
056: 
057:   // Show list in forward and reverse order
058:   System.out.println("/nList in forward order");
059:   showContainer(charts, FORWARD);
060:   System.out.println("/nList in reverse order");
061:   showContainer(charts, REVERSE);
062:  }
063: }
Return to top

Listing 15-11 ListIterator.txt Page 294

Return to top
001: // Inherited Iterator methods
002: boolean hasNext();
003: Object next();
004: void remove();
005: // ListIterator interface methods
006: boolean hasPrevious();
007: Object previous();
008: int nextIndex();
009: int previousIndex();
010: void set(Object o);
011: void add(Object o);
Return to top

Listing 15-12 BinaryDemo/BinaryDemo.java Page 300

Return to top
001: import java.util.List;
002: import java.util.Comparator;
003: import java.util.ArrayList;
004: import java.util.Collections;
005: import Chart;
006: 
007: class BinaryDemo {
008: 
009:  // Display a List container's contents
010:  public static void showContainer(List c) {
011:   for (int i = 0; i < c.size(); i++)
012:    System.out.println(c.get(i).toString());
013:  }
014: 
015:  public static void main(String args[]) {
016: // Construct the container
017:   ArrayList charts = new ArrayList();
018: 
019: // Insert some Data objects
020:   charts.add(new Chart(11013, "Morehead City Hrbr ", 12500));
021:   charts.add(new Chart(11552, "Neuse River        ", 40000));
022:   charts.add(new Chart(11428, "Dry Tortugas       ", 30000));
023:   charts.add(new Chart(11420, "Havana to Tampa Bay", 470940));
024:   charts.add(new Chart(25641, "Virgin Islands     ", 100000));
025:   charts.add(new Chart(26341, "Bermuda Islands    ", 50000));
026: 
027: // Display all objects if none requested
028:   if (args.length == 0) {
029:    System.out.println("/nContainer contents:");
030:    showContainer(charts);
031:    System.out.println("/nEnter a chart number to find");
032:    System.out.println("ex. java BinaryDemo 11428");
033:   } else {
034: 
035: // Search container using Collections.binarySearch()
036:    try {
037: // Preparations for a binarySearch();
038:     int num = Integer.parseInt(args[0]); // Get chart number
039:     Comparator comp = Chart.byNumber();  // Create Comparator
040:     Chart key = new Chart(num, "", 0);   // Create search key 
041:     Collections.sort(charts, comp);      // Sort container
042: 
043: // Search the container for the key object
044:     int index = Collections.binarySearch(charts, key, comp);
045:     if (index < 0)
046:      System.out.println("Chart #" + args[0] + " not found");
047:     else
048:      System.out.println(charts.get(index)); // Show chart
049:    }
050:     catch (NumberFormatException e) {
051:     System.out.println("Error in argument " + e.getMessage());
052:    }
053:   }
054:  }
055: }
Return to top

Listing 15-13 StackDemo/Stack.java Page 303

Return to top
001: import java.util.Collection;
002: import java.util.LinkedList;
003: 
004: class StackEmptyException extends Exception {
005:  StackEmptyException(String s) { super(s); }
006: }
007: 
008: public class Stack extends LinkedList {
009: // Constructors
010:  public Stack() { super(); }
011:  public Stack(Collection c) { super(c); }
012: // Public methods
013:  public void push(Object o) {
014:   addLast(o);
015:  }
016:  public Object pop() throws StackEmptyException {
017:   if (size() == 0)
018:    throw new StackEmptyException("pop on empty stack");
019:   return removeLast();
020:  }
021:  public Object peek() throws StackEmptyException {
022:   if (size() == 0)
023:    throw new StackEmptyException("peek on empty stack");
024:   return getLast();
025:  }
026: // Unsupported methods (incomplete -- see text)
027:  public final Object removeFirst() {
028:   throw new UnsupportedOperationException();
029:  } 
030:  public final void addFirst(Object o) {
031:   throw new UnsupportedOperationException();
032:  } 
033: }
Return to top

Listing 15-14 StackDemo/StackDemo.java Page 306

Return to top
001: import Stack;
002:  
003: class StackDemo {
004:  public static void main(String args[]) {
005:   String s;
006:   try {
007:    Stack fruitStack = new Stack();
008:    fruitStack.push("Apples");
009:    fruitStack.push("Peaches");
010:    fruitStack.push("Pumpkin");
011: // Enable following to force an unchecked exception
012: //   fruitStack.removeFirst();
013: // Peek at top of stack 
014:    s = (String)fruitStack.peek();
015:    System.out.println("/nTop of stack = " + s);  
016: // Pop all objects from stack
017:    System.out.println("/nPopping all objects:");
018:    while (!fruitStack.isEmpty()) {
019:     s = (String)fruitStack.pop();
020:     System.out.println(s);
021:    }
022: // Enable following to force a checked exception
023: //   s = (String)fruitStack.pop();
024:   } catch (StackEmptyException e) {
025:    System.out.println("*** Error: " + e.getMessage());
026:   }
027:  }
028: }
Return to top