All book examples resolved and incorporated

This commit is contained in:
Bruce Eckel 2015-04-29 13:56:17 -07:00
parent 7265b6aceb
commit ebd816f37e
18 changed files with 51 additions and 54 deletions

View File

@ -100,7 +100,7 @@ class TellerManager implements Runnable {
private Queue<Teller> tellersDoingOtherThings =
new LinkedList<Teller>();
private int adjustmentPeriod;
private static Random rand = new Random(47);
public TellerManager(ExecutorService e,
CustomerLine customers, int adjustmentPeriod) {
exec = e;
@ -201,4 +201,4 @@ Teller 0 interrupted
Teller 0 terminating
CustomerGenerator interrupted
CustomerGenerator terminating
*///:~
*///:~

View File

@ -1,4 +1,5 @@
//: concurrency/ExplicitCriticalSection.java
// {ThrowsException} on a multiprocessor machine
// Using explicit Lock objects to create critical sections.
package concurrency;
import java.util.concurrent.locks.*;
@ -6,7 +7,7 @@ import java.util.concurrent.locks.*;
// Synchronize the entire method:
class ExplicitPairManager1 extends PairManager {
private Lock lock = new ReentrantLock();
public synchronized void increment() {
public void increment() {
lock.lock();
try {
p.incrementX();
@ -31,7 +32,7 @@ class ExplicitPairManager2 extends PairManager {
} finally {
lock.unlock();
}
store(temp);
store(temp);
}
}
@ -42,7 +43,4 @@ public class ExplicitCriticalSection {
pman2 = new ExplicitPairManager2();
CriticalSection.testApproaches(pman1, pman2);
}
} /* Output: (Sample)
pm1: Pair: x: 15, y: 15 checkCounter = 174035
pm2: Pair: x: 16, y: 16 checkCounter = 2608588
*///:~
} ///:~

View File

@ -108,11 +108,10 @@ class PrioritizedTaskConsumer implements Runnable {
public class PriorityBlockingQueueDemo {
public static void main(String[] args) throws Exception {
Random rand = new Random(47);
ExecutorService exec = Executors.newCachedThreadPool();
PriorityBlockingQueue<Runnable> queue =
new PriorityBlockingQueue<Runnable>();
exec.execute(new PrioritizedTaskProducer(queue, exec));
exec.execute(new PrioritizedTaskConsumer(queue));
}
} /* (Execute to see output) *///:~
} /* (Execute to see output) *///:~

View File

@ -22,7 +22,8 @@ public class MapEntry<K,V> implements Map.Entry<K,V> {
}
public boolean equals(Object o) {
if(!(o instanceof MapEntry)) return false;
MapEntry me = (MapEntry)o;
@SuppressWarnings("unchecked")
MapEntry<K,V> me = (MapEntry<K,V>)o;
return
(key == null ?
me.getKey() == null : key.equals(me.getKey())) &&

View File

@ -1,8 +1,8 @@
//: generics/UseList.java
// {CompileTimeError} (Won't compile)
// {CompileTimeError} (Will not compile)
import java.util.*;
public class UseList<W,T> {
void f(List<T> v) {}
void f(List<W> v) {}
} ///:~
} ///:~

View File

@ -7,11 +7,9 @@
// www.javassist.org }
package net.mindview.atunit;
import javassist.*;
import javassist.expr.*;
import javassist.bytecode.*;
import javassist.bytecode.annotation.*;
import java.io.*;
import java.util.*;
import net.mindview.util.*;
import static net.mindview.util.Print.*;
@ -63,4 +61,4 @@ implements ProcessFiles.Strategy {
throw new RuntimeException(e);
}
}
} ///:~
} ///:~

View File

@ -3,7 +3,7 @@
package net.mindview.atunit;
import java.lang.annotation.*;
// Both fields and methods may be tagged as properties:
// Both fields and methods can be tagged as properties:
@Target({ElementType.FIELD, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface TestProperty {} ///:~
public @interface TestProperty {} ///:~

View File

@ -11,7 +11,7 @@ extends AbstractMap<Integer,String> {
.split(" ");
public CountingMapData(int size) {
if(size < 0) this.size = 0;
this.size = size;
else this.size = size;
}
private static class Entry
implements Map.Entry<Integer,String> {
@ -46,4 +46,4 @@ extends AbstractMap<Integer,String> {
}
} /* Output:
{0=A0, 1=B0, 2=C0, 3=D0, 4=E0, 5=F0, 6=G0, 7=H0, 8=I0, 9=J0, 10=K0, 11=L0, 12=M0, 13=N0, 14=O0, 15=P0, 16=Q0, 17=R0, 18=S0, 19=T0, 20=U0, 21=V0, 22=W0, 23=X0, 24=Y0, 25=Z0, 26=A1, 27=B1, 28=C1, 29=D1, 30=E1, 31=F1, 32=G1, 33=H1, 34=I1, 35=J1, 36=K1, 37=L1, 38=M1, 39=N1, 40=O1, 41=P1, 42=Q1, 43=R1, 44=S1, 45=T1, 46=U1, 47=V1, 48=W1, 49=X1, 50=Y1, 51=Z1, 52=A2, 53=B2, 54=C2, 55=D2, 56=E2, 57=F2, 58=G2, 59=H2}
*///:~
*///:~

View File

@ -1,6 +1,5 @@
//: net/mindview/util/Generated.java
package net.mindview.util;
import java.util.*;
public class Generated {
// Fill an existing array:
@ -15,4 +14,4 @@ public class Generated {
(T[])java.lang.reflect.Array.newInstance(type, size);
return new CollectionData<T>(gen, size).toArray(a);
}
} ///:~
} ///:~

View File

@ -17,9 +17,9 @@ public class Print {
public static void printnb(Object obj) {
System.out.print(obj);
}
// The new Java SE5 printf() (from C):
// The Java SE5 printf() (from C):
public static PrintStream
printf(String format, Object... args) {
return System.out.printf(format, args);
}
} ///:~
} ///:~

View File

@ -35,10 +35,10 @@ extends ArrayList<TaskItem<R,C>> {
// Leave completed tasks for results reporting:
if(!item.future.isDone()) {
results.add("Cancelling " + item.task);
item.future.cancel(true); // May interrupt
item.future.cancel(true); // Can interrupt
items.remove();
}
}
return results;
}
} ///:~
} ///:~

View File

@ -1,5 +1,5 @@
//: operators/PassObject.java
// Passing objects to methods may not be
// Passing objects to methods might not be
// what you're used to.
import static net.mindview.util.Print.*;
@ -21,4 +21,4 @@ public class PassObject {
} /* Output:
1: x.c: a
2: x.c: z
*///:~
*///:~

View File

@ -10,7 +10,7 @@ public class Receipt {
}
public void print(String name, int qty, double price) {
f.format("%-15.15s %5d %10.2f\n", name, qty, price);
total += price;
total += price * qty;
}
public void printTotal() {
f.format("%-15s %5s %10.2f\n", "Tax", "", total*0.06);
@ -32,7 +32,7 @@ Item Qty Price
Jack's Magic Be 4 4.25
Princess Peas 3 5.10
Three Bears Por 1 14.29
Tax 1.42
Tax 2.80
-----
Total 25.06
*///:~
Total 49.39
*///:~

View File

@ -1,5 +1,5 @@
//: strings/TestRegularExpression.java
// Allows you to easily try out regular expressions.
// Easily try out regular expressions.
// {Args: abcabcabcdefabc "abc+" "(abc)+" "(abc){2,}" }
import java.util.regex.*;
import static net.mindview.util.Print.*;
@ -36,4 +36,4 @@ Match "abcabcabc" at positions 0-8
Match "abc" at positions 12-14
Regular expression: "(abc){2,}"
Match "abcabcabc" at positions 0-8
*///:~
*///:~

View File

@ -1,5 +1,7 @@
#! py -3
"""
TODO: Make sure there's a newline at the end of the extracted files
Extract code examples from TIJ4 Refreshed. Extracts from plain text file
"""
from pathlib import Path

View File

@ -30,11 +30,11 @@ public class PetCount {
counter.count("Pug");
if(pet instanceof Cat)
counter.count("Cat");
if(pet instanceof Manx)
if(pet instanceof EgyptianMau)
counter.count("EgyptianMau");
if(pet instanceof Manx)
counter.count("Manx");
if(pet instanceof Manx)
if(pet instanceof Cymric)
counter.count("Cymric");
if(pet instanceof Rodent)
counter.count("Rodent");
@ -54,5 +54,5 @@ public class PetCount {
}
} /* Output:
Rat Manx Cymric Mutt Pug Cymric Pug Manx Cymric Rat EgyptianMau Hamster EgyptianMau Mutt Mutt Cymric Mouse Pug Mouse Cymric
{Pug=3, Cat=9, Hamster=1, Cymric=7, Mouse=2, Mutt=3, Rodent=5, Pet=20, Manx=7, EgyptianMau=7, Dog=6, Rat=2}
*///:~
{Rat=2, Cymric=5, Cat=9, Pet=20, Dog=6, Manx=7, EgyptianMau=2, Pug=3, Mouse=2, Rodent=5, Hamster=1, Mutt=3}
*///:~

View File

@ -1,4 +1,4 @@
//: xml/Person.java
//: xml/APerson.java
// Use the XOM library to write and read XML
// {Requires: nu.xom.Node; You must install
// the XOM library from http://www.xom.nu }
@ -6,13 +6,13 @@ import nu.xom.*;
import java.io.*;
import java.util.*;
public class Person {
public class APerson {
private String first, last;
public Person(String first, String last) {
public APerson(String first, String last) {
this.first = first;
this.last = last;
}
// Produce an XML Element from this Person object:
// Produce an XML Element from this APerson object:
public Element getXML() {
Element person = new Element("person");
Element firstName = new Element("first");
@ -23,8 +23,8 @@ public class Person {
person.appendChild(lastName);
return person;
}
// Constructor to restore a Person from an XML Element:
public Person(Element person) {
// Constructor to restore a APerson from an XML Element:
public APerson(Element person) {
first= person.getFirstChildElement("first").getValue();
last = person.getFirstChildElement("last").getValue();
}
@ -39,13 +39,13 @@ public class Person {
serializer.flush();
}
public static void main(String[] args) throws Exception {
List<Person> people = Arrays.asList(
new Person("Dr. Bunsen", "Honeydew"),
new Person("Gonzo", "The Great"),
new Person("Phillip J.", "Fry"));
List<APerson> people = Arrays.asList(
new APerson("Dr. Bunsen", "Honeydew"),
new APerson("Gonzo", "The Great"),
new APerson("Phillip J.", "Fry"));
System.out.println(people);
Element root = new Element("people");
for(Person p : people)
for(APerson p : people)
root.appendChild(p.getXML());
Document doc = new Document(root);
format(System.out, doc);
@ -69,4 +69,4 @@ public class Person {
<last>Fry</last>
</person>
</people>
*///:~
*///:~

View File

@ -1,18 +1,18 @@
//: xml/People.java
// {Requires: nu.xom.Node; You must install
// the XOM library from http://www.xom.nu }
// {RunFirst: Person}
// {RunFirst: APerson}
import nu.xom.*;
import java.io.File;
import java.util.*;
public class People extends ArrayList<Person> {
public class People extends ArrayList<APerson> {
public People(String fileName) throws Exception {
Document doc = new Builder().build(new File(fileName));
Elements elements =
doc.getRootElement().getChildElements();
for(int i = 0; i < elements.size(); i++)
add(new Person(elements.get(i)));
add(new APerson(elements.get(i)));
}
public static void main(String[] args) throws Exception {
People p = new People("People.xml");
@ -20,4 +20,4 @@ public class People extends ArrayList<Person> {
}
} /* Output:
[Dr. Bunsen Honeydew, Gonzo The Great, Phillip J. Fry]
*///:~
*///:~