This commit is contained in:
Bruce Eckel 2015-05-18 23:05:20 -07:00
parent 94eeca2359
commit 88dbdbbbcb
291 changed files with 1440 additions and 685 deletions

View File

@ -4,6 +4,7 @@
<property name="chapter" value="access"/> <property name="chapter" value="access"/>
<property name="excludedfiles" value=""/> <property name="excludedfiles" value=""/>
<import file="../Ant-Common.xml"/> <import file="../Ant-Common.xml"/>
<import file="../Ant-Clean.xml"/>
<target name="run" description="Compile and run" depends="build"> <target name="run" description="Compile and run" depends="build">
<jrun cls="Cake" /> <jrun cls="Cake" />

View File

@ -1,5 +1,5 @@
//: annotations/ExtractInterface.java //: annotations/ExtractInterface.java
// APT-based annotation processing. // javac-based annotation processing.
package annotations; package annotations;
import java.lang.annotation.*; import java.lang.annotation.*;

View File

@ -0,0 +1,68 @@
//: annotations/IfaceExtractorProcessor.java
// javac-based annotation processing.
package annotations;
import javax.annotation.processing.*;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.*;
import java.util.*;
import java.io.*;
@SupportedAnnotationTypes(
"annotations.ExtractInterface")
@SupportedSourceVersion(SourceVersion.RELEASE_8)
public class IfaceExtractorProcessor
extends AbstractProcessor {
private ArrayList<Element>
interfaceMethods = new ArrayList<>();
private ProcessingEnvironment processingEnv;
@Override public void
init(ProcessingEnvironment processingEnv) {
this.processingEnv = processingEnv;
}
@Override public boolean
process(Set<? extends TypeElement> annotations,
RoundEnvironment env) {
for(Element elem :
env.getElementsAnnotatedWith(ExtractInterface.class)) {
if(elem.getModifiers().contains(Modifier.PUBLIC) &&
!(elem.getModifiers().contains(Modifier.STATIC)))
interfaceMethods.add(elem);
if(interfaceMethods.size() > 0) {
for(Element el : interfaceMethods)
System.out.println(el.getKind() +
" : " + el.getModifiers() +
" : " + el.getSimpleName() +
" : " + el.asType());
try {
try(Writer writer =
processingEnv.getFiler()
.createSourceFile("Filename.txt")
.openWriter()) {
/* writer.write("package " +
typeDecl.getPackage().getQualifiedName() +";");
writer.write("public interface " +
annot.value() + " {");
for(MethodDeclaration m : interfaceMethods) {
writer.print(" public ");
writer.print(m.getReturnType() + " ");
writer.print(m.getSimpleName() + " (");
int i = 0;
for(ParameterDeclaration parm :
m.getParameters()) {
writer.print(parm.getType() + " " +
parm.getSimpleName());
if(++i < m.getParameters().size())
writer.print(", ");
}
writer.write(");");
}
*/ writer.write("}");
}
} catch(Exception e) {
throw new RuntimeException(e);
}
}
}
return false;
}
} ///:~

View File

@ -1,5 +1,5 @@
//: annotations/Multiplier.java //: annotations/Multiplier.java
// APT-based annotation processing. // javac-based annotation processing.
package annotations; package annotations;
@ExtractInterface("IMultiplier") @ExtractInterface("IMultiplier")

View File

@ -2,8 +2,9 @@
<project default="run"> <project default="run">
<property name="chapter" value="annotations"/> <property name="chapter" value="annotations"/>
<property name="excludedfiles" value="InterfaceExtractorProcessor.java InterfaceExtractorProcessorFactory.java database/TableCreationProcessorFactory.java"/> <property name="excludedfiles" value=""/>
<import file="../Ant-Common.xml"/> <import file="../Ant-Common.xml"/>
<import file="../Ant-Clean.xml"/>
<target name="run" description="Compile and run" depends="build"> <target name="run" description="Compile and run" depends="build">
<jrun cls="annotations.AtUnitComposition" dirpath="../annotations" /> <jrun cls="annotations.AtUnitComposition" dirpath="../annotations" />
@ -18,6 +19,7 @@
<jrun cls="annotations.StackLStringTest" dirpath="../annotations" /> <jrun cls="annotations.StackLStringTest" dirpath="../annotations" />
<jrun cls="UseCaseTracker" /> <jrun cls="UseCaseTracker" />
<jrun cls="annotations.database.TableCreator" dirpath="../annotations/database" arguments="annotations.database.Member" /> <jrun cls="annotations.database.TableCreator" dirpath="../annotations/database" arguments="annotations.database.Member" />
<jrun cls="annotations.simplest.SimpleTest" dirpath="../annotations/simplest" />
</target> </target>
</project> </project>

View File

@ -0,0 +1,17 @@
//: annotations/simplest/Simple.java
// A bare-bones annotation.
package annotations.simplest;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
@Retention(RetentionPolicy.SOURCE)
@Target({ElementType.TYPE, ElementType.METHOD,
ElementType.CONSTRUCTOR,
ElementType.ANNOTATION_TYPE,
ElementType.PACKAGE, ElementType.FIELD,
ElementType.LOCAL_VARIABLE})
public @interface Simple {
String value() default "-default-";
} ///:~

View File

@ -0,0 +1,28 @@
//: annotations/simplest/SimpleProcessor.java
// A bare-bones annotation processor.
package annotations.simplest;
import javax.annotation.processing.*;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.*;
import java.util.*;
@SupportedAnnotationTypes(
"annotations.simplest.Simple")
@SupportedSourceVersion(SourceVersion.RELEASE_8)
public class SimpleProcessor
extends AbstractProcessor {
@Override public boolean
process(Set<? extends TypeElement> annotations,
RoundEnvironment env) {
for(TypeElement t : annotations)
System.out.println(t);
for(Element el :
env.getElementsAnnotatedWith(Simple.class)){
System.out.println(el.getKind() +
" : " + el.getModifiers() +
" : " + el.getSimpleName() +
" : " + el.asType());
}
return false;
}
} ///:~

View File

@ -0,0 +1,21 @@
//: annotations/simplest/SimpleTest.java
// Test the "Simple" annotation
package annotations.simplest;
@Simple
public class SimpleTest {
@Simple
int i;
@Simple
public SimpleTest() {}
@Simple
public void foo() {
System.out.println("SimpleTest.foo()");
}
@Simple
public static void main(String[] args) {
@Simple
SimpleTest st = new SimpleTest();
st.foo();
}
} ///:~

View File

@ -4,6 +4,7 @@
<property name="chapter" value="arrays"/> <property name="chapter" value="arrays"/>
<property name="excludedfiles" value=""/> <property name="excludedfiles" value=""/>
<import file="../Ant-Common.xml"/> <import file="../Ant-Common.xml"/>
<import file="../Ant-Clean.xml"/>
<target name="run" description="Compile and run" depends="build"> <target name="run" description="Compile and run" depends="build">
<jrun cls="AlphabeticSearch" /> <jrun cls="AlphabeticSearch" />

View File

@ -1,6 +1,5 @@
//: assertions/Assert1.java //: assertions/Assert1.java
// Non-informative style of assert // Non-informative style of assert
// Compile with: javac -source 1.4 Assert1.java
// {JVMArgs: -ea} // Must run with -ea // {JVMArgs: -ea} // Must run with -ea
// {ThrowsException} // {ThrowsException}

View File

@ -1,6 +1,5 @@
//: assertions/LoaderAssertions.java //: assertions/LoaderAssertions.java
// Using the class loader to enable assertions // Using the class loader to enable assertions
// Compile with: javac -source 1.4 LoaderAssertions.java
// {ThrowsException} // {ThrowsException}
public class LoaderAssertions { public class LoaderAssertions {

View File

@ -1,9 +1,12 @@
//: assertions/Queue.java //: assertions/Queue.java
// Demonstration of Design by Contract (DBC) combined // Demonstration of Design by Contract (DBC) combined
// with white-box unit testing. // with white-box unit testing.
// {Depends: junit.jar} // (Install libraries from www.junit.org)
import junit.framework.*;
import java.util.*; import java.util.*;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
public class Queue { public class Queue {
private Object[] data; private Object[] data;
@ -86,11 +89,10 @@ public class Queue {
} }
// JUnit testing. // JUnit testing.
// As an inner class, this has access to privates: // As an inner class, this has access to privates:
public static class WhiteBoxTest extends TestCase { public static class WhiteBoxTest {
private Queue queue = new Queue(10); private Queue queue = new Queue(10);
private int i = 0; private int i = 0;
public WhiteBoxTest(String name) { public WhiteBoxTest() {
super(name);
while(i < 5) // Preload with some data while(i < 5) // Preload with some data
queue.put("" + i++); queue.put("" + i++);
} }
@ -106,7 +108,8 @@ public class Queue {
assertTrue(queue.empty()); assertTrue(queue.empty());
System.out.println(queue.dump()); System.out.println(queue.dump());
} }
public void testFull() { @Test
public void full() {
System.out.println("testFull"); System.out.println("testFull");
System.out.println(queue.dump()); System.out.println(queue.dump());
System.out.println(queue.get()); System.out.println(queue.get());
@ -123,7 +126,8 @@ public class Queue {
assertEquals(msg, "put() into full Queue"); assertEquals(msg, "put() into full Queue");
showFullness(); showFullness();
} }
public void testEmpty() { @Test
public void empty() {
System.out.println("testEmpty"); System.out.println("testEmpty");
while(!queue.empty()) while(!queue.empty())
System.out.println(queue.get()); System.out.println(queue.get());
@ -137,7 +141,8 @@ public class Queue {
assertEquals(msg, "get() from empty Queue"); assertEquals(msg, "get() from empty Queue");
showEmptiness(); showEmptiness();
} }
public void testNullPut() { @Test
public void nullPut() {
System.out.println("testNullPut"); System.out.println("testNullPut");
String msg = ""; String msg = "";
try { try {
@ -148,7 +153,8 @@ public class Queue {
} }
assertEquals(msg, "put() null item"); assertEquals(msg, "put() null item");
} }
public void testCircularity() { @Test
public void circularity() {
System.out.println("testCircularity"); System.out.println("testCircularity");
while(!queue.full()) while(!queue.full())
queue.put("" + i++); queue.put("" + i++);
@ -167,6 +173,7 @@ public class Queue {
} }
} }
public static void main(String[] args) { public static void main(String[] args) {
junit.textui.TestRunner.run(Queue.WhiteBoxTest.class); org.junit.runner.JUnitCore.runClasses(
Queue.WhiteBoxTest.class);
} }
} ///:~ } ///:~

View File

@ -4,6 +4,7 @@
<property name="chapter" value="assertions"/> <property name="chapter" value="assertions"/>
<property name="excludedfiles" value=""/> <property name="excludedfiles" value=""/>
<import file="../Ant-Common.xml"/> <import file="../Ant-Common.xml"/>
<import file="../Ant-Clean.xml"/>
<target name="run" description="Compile and run" depends="build"> <target name="run" description="Compile and run" depends="build">
<jrun cls="Assert1" failOnError='false' msg='* Exception was Expected *' /> <jrun cls="Assert1" failOnError='false' msg='* Exception was Expected *' />

View File

@ -61,7 +61,7 @@ public class ActiveObjectDemo {
} }
d1.shutdown(); d1.shutdown();
} }
} /* Output: (85% match) } /* Output: (85% Match)
All asynch calls made All asynch calls made
starting 0.0 + 0.0 starting 0.0 + 0.0
starting 0.2 + 0.2 starting 0.2 + 0.2

View File

@ -7,7 +7,7 @@ public class BasicThreads {
t.start(); t.start();
System.out.println("Waiting for LiftOff"); System.out.println("Waiting for LiftOff");
} }
} /* Output: (90% match) } /* Output: (90% Match)
Waiting for LiftOff Waiting for LiftOff
#0(9), #0(8), #0(7), #0(6), #0(5), #0(4), #0(3), #0(2), #0(1), #0(Liftoff!), #0(9), #0(8), #0(7), #0(6), #0(5), #0(4), #0(3), #0(2), #0(1), #0(Liftoff!),
*///:~ *///:~

View File

@ -41,7 +41,7 @@ public class CaptureUncaughtException {
new HandlerThreadFactory()); new HandlerThreadFactory());
exec.execute(new ExceptionThread2()); exec.execute(new ExceptionThread2());
} }
} /* Output: (90% match) } /* Output: (90% Match)
HandlerThreadFactory@de6ced creating new Thread HandlerThreadFactory@de6ced creating new Thread
created Thread[Thread-0,5,main] created Thread[Thread-0,5,main]
eh = MyUncaughtExceptionHandler@1fb8ee3 eh = MyUncaughtExceptionHandler@1fb8ee3

View File

@ -25,7 +25,7 @@ public class CloseResource {
print("Closing " + System.in.getClass().getName()); print("Closing " + System.in.getClass().getName());
System.in.close(); // Releases blocked thread System.in.close(); // Releases blocked thread
} }
} /* Output: (85% match) } /* Output: (85% Match)
Waiting for read(): Waiting for read():
Waiting for read(): Waiting for read():
Shutting down all threads Shutting down all threads

View File

@ -1,7 +1,7 @@
//: concurrency/ExchangerDemo.java //: concurrency/ExchangerDemo.java
import java.util.concurrent.*; import java.util.concurrent.*;
import java.util.*;
import net.mindview.util.*; import net.mindview.util.*;
import java.util.*;
class ExchangerProducer<T> implements Runnable { class ExchangerProducer<T> implements Runnable {
private Generator<T> generator; private Generator<T> generator;

View File

@ -34,7 +34,7 @@ class ExplicitPairManager2 extends PairManager {
} finally { } finally {
lock.unlock(); lock.unlock();
} }
store(temp); store(temp);
} }
} }

View File

@ -1,5 +1,6 @@
//: concurrency/HorseRace.java //: concurrency/HorseRace.java
// Using CyclicBarriers. // Using CyclicBarriers.
// {CheckOutputByHand}
import java.util.concurrent.*; import java.util.concurrent.*;
import java.util.*; import java.util.*;
import static net.mindview.util.Print.*; import static net.mindview.util.Print.*;

View File

@ -74,7 +74,7 @@ public class Interrupting {
print("Aborting with System.exit(0)"); print("Aborting with System.exit(0)");
System.exit(0); // ... since last 2 interrupts failed System.exit(0); // ... since last 2 interrupts failed
} }
} /* Output: (95% match) } /* Output: (95% Match)
Interrupting SleepBlocked Interrupting SleepBlocked
InterruptedException InterruptedException
Exiting SleepBlocked.run() Exiting SleepBlocked.run()

View File

@ -53,7 +53,7 @@ public class PipedIO {
TimeUnit.SECONDS.sleep(4); TimeUnit.SECONDS.sleep(4);
exec.shutdownNow(); exec.shutdownNow();
} }
} /* Output: (65% match) } /* Output: (65% Match)
Read: A, Read: B, Read: C, Read: D, Read: E, Read: F, Read: G, Read: H, Read: I, Read: J, Read: K, Read: L, Read: M, java.lang.InterruptedException: sleep interrupted Sender sleep interrupted Read: A, Read: B, Read: C, Read: D, Read: E, Read: F, Read: G, Read: H, Read: I, Read: J, Read: K, Read: L, Read: M, java.lang.InterruptedException: sleep interrupted Sender sleep interrupted
java.io.InterruptedIOException Receiver read exception java.io.InterruptedIOException Receiver read exception
*///:~ *///:~

View File

@ -24,7 +24,7 @@ public class SimpleDaemons implements Runnable {
print("All daemons started"); print("All daemons started");
TimeUnit.MILLISECONDS.sleep(175); TimeUnit.MILLISECONDS.sleep(175);
} }
} /* Output: (Sample) } /* Output: (First 11 Lines)
All daemons started All daemons started
Thread[Thread-0,5,main] SimpleDaemons@530daa Thread[Thread-0,5,main] SimpleDaemons@530daa
Thread[Thread-1,5,main] SimpleDaemons@a62fc3 Thread[Thread-1,5,main] SimpleDaemons@a62fc3

View File

@ -40,7 +40,7 @@ public class SimpleMicroBenchmark {
System.out.printf("Lock/synchronized = %1$.3f", System.out.printf("Lock/synchronized = %1$.3f",
(double)lockTime/(double)synchTime); (double)lockTime/(double)synchTime);
} }
} /* Output: (75% match) } /* Output: (75% Match)
synchronized: 244919117 synchronized: 244919117
Lock: 939098964 Lock: 939098964
Lock/synchronized = 3.834 Lock/synchronized = 3.834

View File

@ -36,7 +36,7 @@ public class SimplePriorities implements Runnable {
new SimplePriorities(Thread.MAX_PRIORITY)); new SimplePriorities(Thread.MAX_PRIORITY));
exec.shutdown(); exec.shutdown();
} }
} /* Output: (70% match) } /* Output: (First 10 Lines) (70% Match)
Thread[pool-1-thread-6,10,main]: 5 Thread[pool-1-thread-6,10,main]: 5
Thread[pool-1-thread-6,10,main]: 4 Thread[pool-1-thread-6,10,main]: 4
Thread[pool-1-thread-6,10,main]: 3 Thread[pool-1-thread-6,10,main]: 3

View File

@ -167,42 +167,42 @@ public class SynchronizationComparisons {
} }
Accumulator.exec.shutdown(); Accumulator.exec.shutdown();
} }
} /* Output: (Sample) using JDK6u10 } /* Output: (Sample)
Warmup Warmup
synch : 129868038 synch : 94513807
============================ ============================
Cycles : 50000 Cycles : 50000
synch : 126407922 synch : 94514234
Lock : 51207369 Lock : 24976352
Atomic : 141845223 Atomic : 98296651
synch/Lock : 2.47 synch/Lock : 3.78
synch/(Atomic-synch) : 8.19 synch/(Atomic-synch) : 24.99
============================ ============================
Cycles : 100000 Cycles : 100000
synch : 251174061 synch : 178531353
Lock : 105338114 Lock : 46007787
Atomic : 279503250 Atomic : 192372561
synch/Lock : 2.38 synch/Lock : 3.88
synch/(Atomic-synch) : 8.87 synch/(Atomic-synch) : 12.90
============================ ============================
Cycles : 200000 Cycles : 200000
synch : 508778006 synch : 377107591
Lock : 214398402 Lock : 91051260
Atomic : 574464795 Atomic : 394509274
synch/Lock : 2.37 synch/Lock : 4.14
synch/(Atomic-synch) : 7.75 synch/(Atomic-synch) : 21.67
============================ ============================
Cycles : 400000 Cycles : 400000
synch : 1027003521 synch : 722152518
Lock : 428342577 Lock : 184968090
Atomic : 1115667617 Atomic : 746950974
synch/Lock : 2.40 synch/Lock : 3.90
synch/(Atomic-synch) : 11.58 synch/(Atomic-synch) : 29.12
============================ ============================
Cycles : 800000 Cycles : 800000
synch : 2179255097 synch : 1478348925
Lock : 877216314 Lock : 416729956
Atomic : 2371504710 Atomic : 1559738238
synch/Lock : 2.48 synch/Lock : 3.55
synch/(Atomic-synch) : 11.34 synch/(Atomic-synch) : 18.16
*///:~ *///:~

View File

@ -4,6 +4,7 @@
<property name="chapter" value="concurrency"/> <property name="chapter" value="concurrency"/>
<property name="excludedfiles" value=""/> <property name="excludedfiles" value=""/>
<import file="../Ant-Common.xml"/> <import file="../Ant-Common.xml"/>
<import file="../Ant-Clean.xml"/>
<target name="run" description="Compile and run" depends="build"> <target name="run" description="Compile and run" depends="build">
<jrun cls="ActiveObjectDemo" /> <jrun cls="ActiveObjectDemo" />

View File

@ -73,7 +73,7 @@ public class WaxOMatic {
TimeUnit.SECONDS.sleep(5); // Run for a while... TimeUnit.SECONDS.sleep(5); // Run for a while...
exec.shutdownNow(); // Interrupt all tasks exec.shutdownNow(); // Interrupt all tasks
} }
} /* Output: (95% match) } /* Output: (95% Match)
Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Exiting via interrupt Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Exiting via interrupt
Ending Wax On task Ending Wax On task
Exiting via interrupt Exiting via interrupt

View File

@ -94,7 +94,7 @@ public class WaxOMatic2 {
TimeUnit.SECONDS.sleep(5); TimeUnit.SECONDS.sleep(5);
exec.shutdownNow(); exec.shutdownNow();
} }
} /* Output: (90% match) } /* Output: (90% Match)
Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Exiting via interrupt Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Wax Off! Wax On! Exiting via interrupt
Ending Wax Off task Ending Wax Off task
Exiting via interrupt Exiting via interrupt

View File

@ -44,7 +44,7 @@ public class Maps {
test(new ConcurrentHashMap<>()); test(new ConcurrentHashMap<>());
test(new WeakHashMap<>()); test(new WeakHashMap<>());
} }
} /* Output: } /* Output: (First 11 Lines)
HashMap HashMap
Size = 25, Keys: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17, 16, 19, 18, 21, 20, 23, 22, 24] Size = 25, Keys: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17, 16, 19, 18, 21, 20, 23, 22, 24]
Values: [A0, B0, C0, D0, E0, F0, G0, H0, I0, J0, K0, L0, M0, N0, O0, P0, R0, Q0, T0, S0, V0, U0, X0, W0, Y0] Values: [A0, B0, C0, D0, E0, F0, G0, H0, I0, J0, K0, L0, M0, N0, O0, P0, R0, Q0, T0, S0, V0, U0, X0, W0, Y0]

View File

@ -4,6 +4,7 @@
<property name="chapter" value="containers"/> <property name="chapter" value="containers"/>
<property name="excludedfiles" value=""/> <property name="excludedfiles" value=""/>
<import file="../Ant-Common.xml"/> <import file="../Ant-Common.xml"/>
<import file="../Ant-Clean.xml"/>
<target name="run" description="Compile and run" depends="build"> <target name="run" description="Compile and run" depends="build">
<jrun cls="AssociativeArray" /> <jrun cls="AssociativeArray" />

View File

@ -9,7 +9,7 @@ public class ListCharacters {
System.out.println("value: " + (int)c + System.out.println("value: " + (int)c +
" character: " + c); " character: " + c);
} }
} /* Output: } /* Output: (First 10 Lines)
value: 97 character: a value: 97 character: a
value: 98 character: b value: 98 character: b
value: 99 character: c value: 99 character: c

View File

@ -23,7 +23,7 @@ public class VowelsAndConsonants {
} }
} }
} }
} /* Output: } /* Output: (First 13 Lines)
y, 121: Sometimes a vowel y, 121: Sometimes a vowel
n, 110: consonant n, 110: consonant
z, 122: consonant z, 122: consonant

View File

@ -4,6 +4,7 @@
<property name="chapter" value="control"/> <property name="chapter" value="control"/>
<property name="excludedfiles" value=""/> <property name="excludedfiles" value=""/>
<import file="../Ant-Common.xml"/> <import file="../Ant-Common.xml"/>
<import file="../Ant-Clean.xml"/>
<target name="run" description="Compile and run" depends="build"> <target name="run" description="Compile and run" depends="build">
<jrun cls="BreakAndContinue" /> <jrun cls="BreakAndContinue" />

View File

@ -18,4 +18,13 @@ public class SimpleDebugging {
public static void main(String[] args) { public static void main(String[] args) {
foo1(); foo1();
} }
} ///:~ } /* Output:
In foo1
In foo2
In foo3
Exception in thread "main" java.lang.ArithmeticException: / by zero
at SimpleDebugging.foo3(SimpleDebugging.java:16)
at SimpleDebugging.foo2(SimpleDebugging.java:10)
at SimpleDebugging.foo1(SimpleDebugging.java:6)
at SimpleDebugging.main(SimpleDebugging.java:19)
*///:~

View File

@ -4,6 +4,7 @@
<property name="chapter" value="debugging"/> <property name="chapter" value="debugging"/>
<property name="excludedfiles" value=""/> <property name="excludedfiles" value=""/>
<import file="../Ant-Common.xml"/> <import file="../Ant-Common.xml"/>
<import file="../Ant-Clean.xml"/>
<target name="run" description="Compile and run" depends="build"> <target name="run" description="Compile and run" depends="build">
<jrun cls="SimpleDebugging" failOnError='false' msg='* Exception was Expected *' /> <jrun cls="SimpleDebugging" failOnError='false' msg='* Exception was Expected *' />

View File

@ -15,7 +15,7 @@ public enum Input {
public int amount() { // Disallow public int amount() { // Disallow
throw new RuntimeException("SHUT_DOWN.amount()"); throw new RuntimeException("SHUT_DOWN.amount()");
} }
}; };
int value; // In cents int value; // In cents
Input(int value) { this.value = value; } Input(int value) { this.value = value; }
Input() {} Input() {}

View File

@ -14,7 +14,7 @@ enum LikeClasses {
public class NotClasses { public class NotClasses {
// void f1(LikeClasses.WINKEN instance) {} // Nope // void f1(LikeClasses.WINKEN instance) {} // Nope
} /* Output: } /* Output: (First 7 Lines)
Compiled from "NotClasses.java" Compiled from "NotClasses.java"
abstract class LikeClasses extends java.lang.Enum{ abstract class LikeClasses extends java.lang.Enum{
public static final LikeClasses WINKEN; public static final LikeClasses WINKEN;

View File

@ -22,7 +22,7 @@ class Paper implements Item {
public Outcome eval(Rock r) { return LOSE; } public Outcome eval(Rock r) { return LOSE; }
@Override @Override
public String toString() { return "Paper"; } public String toString() { return "Paper"; }
} }
class Scissors implements Item { class Scissors implements Item {
@Override @Override
@ -48,7 +48,7 @@ class Rock implements Item {
public Outcome eval(Rock r) { return DRAW; } public Outcome eval(Rock r) { return DRAW; }
@Override @Override
public String toString() { return "Rock"; } public String toString() { return "Rock"; }
} }
public class RoShamBo1 { public class RoShamBo1 {
static final int SIZE = 20; static final int SIZE = 20;
@ -69,7 +69,7 @@ public class RoShamBo1 {
for(int i = 0; i < SIZE; i++) for(int i = 0; i < SIZE; i++)
match(newItem(), newItem()); match(newItem(), newItem());
} }
} /* Output: } /* Output:
Rock vs. Rock: DRAW Rock vs. Rock: DRAW
Paper vs. Rock: WIN Paper vs. Rock: WIN
Paper vs. Rock: WIN Paper vs. Rock: WIN

View File

@ -12,7 +12,7 @@ public enum RoShamBo2 implements Competitor<RoShamBo2> {
this.vPAPER = paper; this.vPAPER = paper;
this.vSCISSORS = scissors; this.vSCISSORS = scissors;
this.vROCK = rock; this.vROCK = rock;
} }
@Override @Override
public Outcome compete(RoShamBo2 it) { public Outcome compete(RoShamBo2 it) {
switch(it) { switch(it) {

View File

@ -14,7 +14,7 @@ enum RoShamBo5 implements Competitor<RoShamBo5> {
initRow(PAPER, DRAW, LOSE, WIN); initRow(PAPER, DRAW, LOSE, WIN);
initRow(SCISSORS, WIN, DRAW, LOSE); initRow(SCISSORS, WIN, DRAW, LOSE);
initRow(ROCK, LOSE, WIN, DRAW); initRow(ROCK, LOSE, WIN, DRAW);
} }
static void initRow(RoShamBo5 it, static void initRow(RoShamBo5 it,
Outcome vPAPER, Outcome vSCISSORS, Outcome vROCK) { Outcome vPAPER, Outcome vSCISSORS, Outcome vROCK) {
EnumMap<RoShamBo5,Outcome> row = EnumMap<RoShamBo5,Outcome> row =

View File

@ -3,7 +3,6 @@
// {Args: VendingMachineInput.txt} // {Args: VendingMachineInput.txt}
import java.util.*; import java.util.*;
import net.mindview.util.*; import net.mindview.util.*;
import static enumerated.Input.*;
import static net.mindview.util.Print.*; import static net.mindview.util.Print.*;
enum Category { enum Category {
@ -12,7 +11,7 @@ enum Category {
QUIT_TRANSACTION(ABORT_TRANSACTION), QUIT_TRANSACTION(ABORT_TRANSACTION),
SHUT_DOWN(STOP); SHUT_DOWN(STOP);
private Input[] values; private Input[] values;
Category(Input... types) { values = types; } Category(Input... types) { values = types; }
private static EnumMap<Input,Category> categories = private static EnumMap<Input,Category> categories =
new EnumMap<>(Input.class); new EnumMap<>(Input.class);
static { static {
@ -23,7 +22,7 @@ enum Category {
public static Category categorize(Input input) { public static Category categorize(Input input) {
return categories.get(input); return categories.get(input);
} }
} }
public class VendingMachine { public class VendingMachine {
private static State state = State.RESTING; private static State state = State.RESTING;
@ -44,7 +43,7 @@ public class VendingMachine {
default: default:
} }
} }
}, },
ADDING_MONEY { ADDING_MONEY {
@Override @Override
void next(Input input) { void next(Input input) {
@ -66,7 +65,7 @@ public class VendingMachine {
default: default:
} }
} }
}, },
DISPENSING(StateDuration.TRANSIENT) { DISPENSING(StateDuration.TRANSIENT) {
@Override @Override
void next() { void next() {
@ -84,7 +83,7 @@ public class VendingMachine {
} }
state = RESTING; state = RESTING;
} }
}, },
TERMINAL {@Override TERMINAL {@Override
void output() { print("Halted"); } }; void output() { print("Halted"); } };
private boolean isTransient = false; private boolean isTransient = false;
@ -99,7 +98,7 @@ public class VendingMachine {
"StateDuration.TRANSIENT states"); "StateDuration.TRANSIENT states");
} }
void output() { print(amount); } void output() { print(amount); }
} }
static void run(Generator<Input> gen) { static void run(Generator<Input> gen) {
while(state != State.TERMINAL) { while(state != State.TERMINAL) {
state.next(gen.next()); state.next(gen.next());
@ -114,7 +113,7 @@ public class VendingMachine {
gen = new FileInputGenerator(args[0]); gen = new FileInputGenerator(args[0]);
run(gen); run(gen);
} }
} }
// For a basic sanity check: // For a basic sanity check:
class RandomInputGenerator implements Generator<Input> { class RandomInputGenerator implements Generator<Input> {

View File

@ -4,6 +4,7 @@
<property name="chapter" value="enumerated"/> <property name="chapter" value="enumerated"/>
<property name="excludedfiles" value="VendingMachine.java"/> <property name="excludedfiles" value="VendingMachine.java"/>
<import file="../Ant-Common.xml"/> <import file="../Ant-Common.xml"/>
<import file="../Ant-Clean.xml"/>
<target name="run" description="Compile and run" depends="build"> <target name="run" description="Compile and run" depends="build">
<jrun cls="BigEnumSet" /> <jrun cls="BigEnumSet" />

View File

@ -26,7 +26,7 @@ public class LoggingExceptions {
System.err.println("Caught " + e); System.err.println("Caught " + e);
} }
} }
} /* Output: (85% match) } /* Output: (85% Match)
Aug 30, 2005 4:02:31 PM LoggingException <init> Aug 30, 2005 4:02:31 PM LoggingException <init>
SEVERE: LoggingException SEVERE: LoggingException
at LoggingExceptions.main(LoggingExceptions.java:19) at LoggingExceptions.main(LoggingExceptions.java:19)

View File

@ -18,7 +18,7 @@ public class LoggingExceptions2 {
logException(e); logException(e);
} }
} }
} /* Output: (90% match) } /* Output: (90% Match)
Aug 30, 2005 4:07:54 PM LoggingExceptions2 logException Aug 30, 2005 4:07:54 PM LoggingExceptions2 logException
SEVERE: java.lang.NullPointerException SEVERE: java.lang.NullPointerException
at LoggingExceptions2.main(LoggingExceptions2.java:16) at LoggingExceptions2.main(LoggingExceptions2.java:16)

View File

@ -4,6 +4,7 @@
<property name="chapter" value="exceptions"/> <property name="chapter" value="exceptions"/>
<property name="excludedfiles" value=""/> <property name="excludedfiles" value=""/>
<import file="../Ant-Common.xml"/> <import file="../Ant-Common.xml"/>
<import file="../Ant-Clean.xml"/>
<target name="run" description="Compile and run" depends="build"> <target name="run" description="Compile and run" depends="build">
<jrun cls="AlwaysFinally" /> <jrun cls="AlwaysFinally" />

View File

@ -17,7 +17,7 @@ public class Apply {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
} }
class Shape { class Shape {
public void rotate() { print(this + " rotate"); } public void rotate() { print(this + " rotate"); }
@ -39,7 +39,7 @@ class FilledList<T> extends ArrayList<T> {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
} }
class ApplyTest { class ApplyTest {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
@ -55,7 +55,7 @@ class ApplyTest {
Apply.apply(squares, Shape.class.getMethod("rotate")); Apply.apply(squares, Shape.class.getMethod("rotate"));
Apply.apply(squares, Apply.apply(squares,
Shape.class.getMethod("resize", int.class), 5); Shape.class.getMethod("resize", int.class), 5);
Apply.apply(new FilledList<>(Shape.class, 10), Apply.apply(new FilledList<>(Shape.class, 10),
Shape.class.getMethod("rotate")); Shape.class.getMethod("rotate"));
Apply.apply(new FilledList<>(Square.class, 10), Apply.apply(new FilledList<>(Square.class, 10),

View File

@ -13,7 +13,7 @@ class Customer {
public static Generator<Customer> generator() { public static Generator<Customer> generator() {
return () -> new Customer(); return () -> new Customer();
} }
} }
class Teller { class Teller {
private static long counter = 1; private static long counter = 1;
@ -24,7 +24,7 @@ class Teller {
// A single Generator object: // A single Generator object:
public static Generator<Teller> generator = public static Generator<Teller> generator =
() -> new Teller(); () -> new Teller();
} }
public class BankTeller { public class BankTeller {
public static void serve(Teller t, Customer c) { public static void serve(Teller t, Customer c) {
@ -38,7 +38,7 @@ public class BankTeller {
Generators.fill(tellers, Teller.generator, 4); Generators.fill(tellers, Teller.generator, 4);
for(Customer c : line) for(Customer c : line)
serve(tellers.get(rand.nextInt(tellers.size())), c); serve(tellers.get(rand.nextInt(tellers.size())), c);
} }
} /* Output: } /* Output:
Teller 3 serves Customer 1 Teller 3 serves Customer 1
Teller 2 serves Customer 2 Teller 2 serves Customer 2

View File

@ -14,7 +14,7 @@ class Dimension { public int x, y, z; }
// This won't work -- class must be first, then interfaces: // This won't work -- class must be first, then interfaces:
// class ColoredDimension<T extends HasColor & Dimension> { // class ColoredDimension<T extends HasColor & Dimension> {
// Multiple bounds: // Multiple bounds:
class ColoredDimension<T extends Dimension & HasColor> { class ColoredDimension<T extends Dimension & HasColor> {
T item; T item;
@ -26,7 +26,7 @@ class ColoredDimension<T extends Dimension & HasColor> {
int getZ() { return item.z; } int getZ() { return item.z; }
} }
interface Weight { int weight(); } interface Weight { int weight(); }
// As with inheritance, you can have only one // As with inheritance, you can have only one
// concrete class but multiple interfaces: // concrete class but multiple interfaces:
@ -47,7 +47,7 @@ extends Dimension implements HasColor, Weight {
public java.awt.Color getColor() { return null; } public java.awt.Color getColor() { return null; }
@Override @Override
public int weight() { return 0; } public int weight() { return 0; }
} }
public class BasicBounds { public class BasicBounds {
public static void main(String[] args) { public static void main(String[] args) {

View File

@ -7,7 +7,7 @@ public class CaptureConversion {
} }
static void f2(Holder<?> holder) { static void f2(Holder<?> holder) {
f1(holder); // Call with captured type f1(holder); // Call with captured type
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static void main(String[] args) { public static void main(String[] args) {
Holder raw = new Holder<>(1); Holder raw = new Holder<>(1);

View File

@ -7,7 +7,7 @@ public class CheckedList {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
static void oldStyleMethod(List probablyDogs) { static void oldStyleMethod(List probablyDogs) {
probablyDogs.add(new Cat()); probablyDogs.add(new Cat());
} }
public static void main(String[] args) { public static void main(String[] args) {
List<Dog> dogs1 = new ArrayList<>(); List<Dog> dogs1 = new ArrayList<>();
oldStyleMethod(dogs1); // Quietly accepts a Cat oldStyleMethod(dogs1); // Quietly accepts a Cat

View File

@ -9,7 +9,7 @@ public class ClassCasting {
new FileInputStream(args[0])); new FileInputStream(args[0]));
// Won't Compile: // Won't Compile:
// List<Widget> lw1 = // List<Widget> lw1 =
// List<Widget>.class.cast(in.readObject()); // List<>.class.cast(in.readObject());
List<Widget> lw2 = List.class.cast(in.readObject()); List<Widget> lw2 = List.class.cast(in.readObject());
} }
} ///:~ } ///:~

View File

@ -10,7 +10,7 @@ public class ClassTypeCapture<T> {
} }
public boolean f(Object arg) { public boolean f(Object arg) {
return kind.isInstance(arg); return kind.isInstance(arg);
} }
public static void main(String[] args) { public static void main(String[] args) {
ClassTypeCapture<Building> ctt1 = ClassTypeCapture<Building> ctt1 =
new ClassTypeCapture<>(Building.class); new ClassTypeCapture<>(Building.class);

View File

@ -14,7 +14,7 @@ class Creator extends GenericWithCreate<X> {
void f() { void f() {
System.out.println(element.getClass().getSimpleName()); System.out.println(element.getClass().getSimpleName());
} }
} }
public class CreatorGeneric { public class CreatorGeneric {
public static void main(String[] args) { public static void main(String[] args) {

View File

@ -15,7 +15,7 @@ class Robot implements Performs {
public void speak() { print("Click!"); } public void speak() { print("Click!"); }
public void sit() { print("Clank!"); } public void sit() { print("Clank!"); }
public void oilChange() {} public void oilChange() {}
} }
class Communicate { class Communicate {
public static <T extends Performs> public static <T extends Performs>

View File

@ -14,11 +14,11 @@ class MixinProxy implements InvocationHandler {
String methodName = method.getName(); String methodName = method.getName();
// The first interface in the map // The first interface in the map
// implements the method. // implements the method.
if (!delegatesByMethod.containsKey(methodName)) if(!delegatesByMethod.containsKey(methodName))
delegatesByMethod.put(methodName, pair.first); delegatesByMethod.put(methodName, pair.first);
} }
} }
} }
@Override @Override
public Object invoke(Object proxy, Method method, public Object invoke(Object proxy, Method method,
Object[] args) throws Throwable { Object[] args) throws Throwable {
@ -37,7 +37,7 @@ class MixinProxy implements InvocationHandler {
return Proxy.newProxyInstance( return Proxy.newProxyInstance(
cl, interfaces, new MixinProxy(pairs)); cl, interfaces, new MixinProxy(pairs));
} }
} }
public class DynamicProxyMixin { public class DynamicProxyMixin {
public static void main(String[] args) { public static void main(String[] args) {

View File

@ -13,7 +13,7 @@ class Derived2 extends GenericBase {} // No warning
// class Derived3 extends GenericBase<?> {} // class Derived3 extends GenericBase<?> {}
// Strange error: // Strange error:
// unexpected type found : ? // unexpected type found : ?
// required: class or interface without bounds // required: class or interface without bounds
public class ErasureAndInheritance { public class ErasureAndInheritance {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")

View File

@ -17,7 +17,7 @@ class IntegerFactory implements FactoryI<Integer> {
public Integer create() { public Integer create() {
return 0; return 0;
} }
} }
class Widget { class Widget {
public static class Factory implements FactoryI<Widget> { public static class Factory implements FactoryI<Widget> {

View File

@ -31,7 +31,7 @@ class Contract {
} }
class TitleTransfer extends Contract {} class TitleTransfer extends Contract {}
class FillTest { class FillTest {
public static void main(String[] args) { public static void main(String[] args) {
List<Contract> contracts = new ArrayList<>(); List<Contract> contracts = new ArrayList<>();

View File

@ -38,7 +38,7 @@ class AddableCollectionAdapter<T> implements Addable<T> {
@Override @Override
public void add(T item) { c.add(item); } public void add(T item) { c.add(item); }
} }
// A Helper to capture the type automatically: // A Helper to capture the type automatically:
class Adapter { class Adapter {
public static <T> public static <T>
@ -54,7 +54,7 @@ extends SimpleQueue<T> implements Addable<T> {
@Override @Override
public void add(T item) { super.add(item); } public void add(T item) { super.add(item); }
} }
class Fill2Test { class Fill2Test {
public static void main(String[] args) { public static void main(String[] args) {
// Adapt a Collection: // Adapt a Collection:

View File

@ -11,7 +11,7 @@ interface Collector<T> extends UnaryFunction<T,T> {
T result(); // Extract result of collecting parameter T result(); // Extract result of collecting parameter
} }
interface UnaryPredicate<T> { boolean test(T x); } interface UnaryPredicate<T> { boolean test(T x); }
public class Functional { public class Functional {
// Calls the Combiner object on each element to combine // Calls the Combiner object on each element to combine
// it with a running result, which is finally returned: // it with a running result, which is finally returned:

View File

@ -10,7 +10,7 @@ public class Generators {
for(int i = 0; i < n; i++) for(int i = 0; i < n; i++)
coll.add(gen.next()); coll.add(gen.next());
return coll; return coll;
} }
public static void main(String[] args) { public static void main(String[] args) {
Collection<Coffee> coffee = fill( Collection<Coffee> coffee = fill(
new ArrayList<>(), new CoffeeGenerator(), 4); new ArrayList<>(), new CoffeeGenerator(), 4);

View File

@ -11,7 +11,7 @@ public class GenericArray<T> {
} }
public T get(int index) { return array[index]; } public T get(int index) { return array[index]; }
// Method that exposes the underlying representation: // Method that exposes the underlying representation:
public T[] rep() { return array; } public T[] rep() { return array; }
public static void main(String[] args) { public static void main(String[] args) {
GenericArray<Integer> gai = new GenericArray<>(10); GenericArray<Integer> gai = new GenericArray<>(10);
// This causes a ClassCastException: // This causes a ClassCastException:

View File

@ -13,7 +13,7 @@ public class GenericArray2<T> {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public T[] rep() { public T[] rep() {
return (T[])array; // Warning: unchecked cast return (T[])array; // Warning: unchecked cast
} }
public static void main(String[] args) { public static void main(String[] args) {
GenericArray2<Integer> gai = GenericArray2<Integer> gai =
new GenericArray2<>(10); new GenericArray2<>(10);

View File

@ -12,7 +12,7 @@ public class GenericArrayWithTypeToken<T> {
} }
public T get(int index) { return array[index]; } public T get(int index) { return array[index]; }
// Expose the underlying representation: // Expose the underlying representation:
public T[] rep() { return array; } public T[] rep() { return array; }
public static void main(String[] args) { public static void main(String[] args) {
GenericArrayWithTypeToken<Integer> gai = GenericArrayWithTypeToken<Integer> gai =
new GenericArrayWithTypeToken<>( new GenericArrayWithTypeToken<>(

View File

@ -9,7 +9,7 @@ class FixedSizeStack<T> {
public void push(T item) { storage[index++] = item; } public void push(T item) { storage[index++] = item; }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public T pop() { return (T)storage[--index]; } public T pop() { return (T)storage[--index]; }
} }
public class GenericCast { public class GenericCast {
public static final int SIZE = 10; public static final int SIZE = 10;

View File

@ -17,7 +17,7 @@ public class GenericReading {
// established when the class is instantiated: // established when the class is instantiated:
static class Reader<T> { static class Reader<T> {
T readExact(List<T> list) { return list.get(0); } T readExact(List<T> list) { return list.get(0); }
} }
static void f2() { static void f2() {
Reader<Fruit> fruitReader = new Reader<>(); Reader<Fruit> fruitReader = new Reader<>();
Fruit f = fruitReader.readExact(fruit); Fruit f = fruitReader.readExact(fruit);
@ -35,7 +35,7 @@ public class GenericReading {
new CovariantReader<>(); new CovariantReader<>();
Fruit f = fruitReader.readCovariant(fruit); Fruit f = fruitReader.readCovariant(fruit);
Fruit a = fruitReader.readCovariant(apples); Fruit a = fruitReader.readCovariant(apples);
} }
public static void main(String[] args) { public static void main(String[] args) {
f1(); f2(); f3(); f1(); f2(); f3();
} }

View File

@ -14,7 +14,7 @@ public class GenericWriting {
static <T> void static <T> void
writeWithWildcard(List<? super T> list, T item) { writeWithWildcard(List<? super T> list, T item) {
list.add(item); list.add(item);
} }
static void f2() { static void f2() {
writeWithWildcard(apples, new Apple()); writeWithWildcard(apples, new Apple());
writeWithWildcard(fruit, new Apple()); writeWithWildcard(fruit, new Apple());

View File

@ -9,7 +9,7 @@ public class Holder<T> {
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
return value.equals(obj); return value.equals(obj);
} }
public static void main(String[] args) { public static void main(String[] args) {
Holder<Apple> Apple = new Holder<>(new Apple()); Holder<Apple> Apple = new Holder<>(new Apple());
Apple d = Apple.get(); Apple d = Apple.get();

View File

@ -13,7 +13,7 @@ class ClassAsFactory<T> {
} }
} }
class Employee {} class Employee {}
public class InstantiateGenericType { public class InstantiateGenericType {
public static void main(String[] args) { public static void main(String[] args) {

View File

@ -21,7 +21,7 @@ extends Fibonacci implements Iterable<Integer> {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
}; };
} }
public static void main(String[] args) { public static void main(String[] args) {
for(int i : new IterableFibonacci(18)) for(int i : new IterableFibonacci(18))
System.out.print(i + " "); System.out.print(i + " ");

View File

@ -17,7 +17,7 @@ class SmartDog {
public void speak() { print("Woof!"); } public void speak() { print("Woof!"); }
public void sit() { print("Sitting"); } public void sit() { print("Sitting"); }
public void reproduce() {} public void reproduce() {}
} }
class CommunicateReflectively { class CommunicateReflectively {
public static void perform(Object speaker) { public static void perform(Object speaker) {

View File

@ -15,7 +15,7 @@ public class LinkedStack<T> {
private Node<T> top = new Node<>(); // End sentinel private Node<T> top = new Node<>(); // End sentinel
public void push(T item) { public void push(T item) {
top = new Node<>(item, top); top = new Node<>(item, top);
} }
public T pop() { public T pop() {
T result = top.item; T result = top.item;
if(!top.end()) if(!top.end())

View File

@ -27,7 +27,7 @@ class Basic {
public: public:
void set(string val) { value = val; } void set(string val) { value = val; }
string get() { return value; } string get() { return value; }
}; };
int main() { int main() {
TimeStamped<SerialNumbered<Basic> > mixin1, mixin2; TimeStamped<SerialNumbered<Basic> > mixin1, mixin2;

View File

@ -4,5 +4,5 @@ import java.util.*;
public class NonCovariantGenerics { public class NonCovariantGenerics {
// Compile Error: incompatible types: // Compile Error: incompatible types:
List<Fruit> flist = new ArrayList<>(); List<Fruit> flist = new ArrayList<Apple>();
} ///:~ } ///:~

View File

@ -14,7 +14,7 @@ class B2 extends NotSelfBounded<A2> {}
class C2 extends NotSelfBounded<C2> { class C2 extends NotSelfBounded<C2> {
C2 setAndGet(C2 arg) { set(arg); return get(); } C2 setAndGet(C2 arg) { set(arg); return get(); }
} }
class D2 {} class D2 {}
// Now this is OK: // Now this is OK:

View File

@ -10,7 +10,7 @@ class DerivedSetter extends OrdinarySetter {
void set(Derived derived) { void set(Derived derived) {
System.out.println("DerivedSetter.set(Derived)"); System.out.println("DerivedSetter.set(Derived)");
} }
} }
public class OrdinaryArguments { public class OrdinaryArguments {
public static void main(String[] args) { public static void main(String[] args) {

View File

@ -10,7 +10,7 @@ class DerivedGS extends GenericSetter<Base> {
void set(Derived derived){ void set(Derived derived){
System.out.println("DerivedGS.set(Derived)"); System.out.println("DerivedGS.set(Derived)");
} }
} }
public class PlainGenericInheritance { public class PlainGenericInheritance {
public static void main(String[] args) { public static void main(String[] args) {

View File

@ -8,7 +8,7 @@ class FArray {
a[i] = gen.next(); a[i] = gen.next();
return a; return a;
} }
} }
public class PrimitiveGenericTest { public class PrimitiveGenericTest {
public static void main(String[] args) { public static void main(String[] args) {

View File

@ -14,7 +14,7 @@ class B extends SelfBounded<A> {} // Also OK
class C extends SelfBounded<C> { class C extends SelfBounded<C> {
C setAndGet(C arg) { set(arg); return get(); } C setAndGet(C arg) { set(arg); return get(); }
} }
class D {} class D {}
// Can't do this: // Can't do this:

View File

@ -35,7 +35,7 @@ class Shelf extends ArrayList<Product> {
public Shelf(int nProducts) { public Shelf(int nProducts) {
Generators.fill(this, Product.generator, nProducts); Generators.fill(this, Product.generator, nProducts);
} }
} }
class Aisle extends ArrayList<Shelf> { class Aisle extends ArrayList<Shelf> {
public Aisle(int nShelves, int nProducts) { public Aisle(int nShelves, int nProducts) {
@ -69,7 +69,7 @@ public class Store extends ArrayList<Aisle> {
public static void main(String[] args) { public static void main(String[] args) {
System.out.println(new Store(14, 5, 10)); System.out.println(new Store(14, 5, 10));
} }
} /* Output: } /* Output: (First 8 Lines)
258: Test, price: $400.99 258: Test, price: $400.99
861: Test, price: $160.99 861: Test, price: $160.99
868: Test, price: $417.99 868: Test, price: $417.99

View File

@ -13,7 +13,7 @@ extends ArrayList<Processor<T,E>> {
processor.process(resultCollector); processor.process(resultCollector);
return resultCollector; return resultCollector;
} }
} }
class Failure1 extends Exception {} class Failure1 extends Exception {}
@ -29,7 +29,7 @@ class Processor1 implements Processor<String,Failure1> {
if(count < 0) if(count < 0)
throw new Failure1(); throw new Failure1();
} }
} }
class Failure2 extends Exception {} class Failure2 extends Exception {}
@ -46,7 +46,7 @@ class Processor2 implements Processor<Integer,Failure2> {
if(count < 0) if(count < 0)
throw new Failure2(); throw new Failure2();
} }
} }
public class ThrowGenericException { public class ThrowGenericException {
public static void main(String[] args) { public static void main(String[] args) {

View File

@ -13,7 +13,7 @@ extends ArrayList<FourTuple<A,B,C,D>> {
for(FourTuple<Vehicle,Amphibian,String,Integer> i: tl) for(FourTuple<Vehicle,Amphibian,String,Integer> i: tl)
System.out.println(i); System.out.println(i);
} }
} /* Output: (75% match) } /* Output: (75% Match)
(Vehicle@11b86e7, Amphibian@35ce36, hi, 47) (Vehicle@11b86e7, Amphibian@35ce36, hi, 47)
(Vehicle@757aef, Amphibian@d9f9c3, hi, 47) (Vehicle@757aef, Amphibian@d9f9c3, hi, 47)
*///:~ *///:~

View File

@ -32,7 +32,7 @@ public class TupleTest {
System.out.println(h()); System.out.println(h());
System.out.println(k()); System.out.println(k());
} }
} /* Output: (80% match) } /* Output: (80% Match)
(hi, 47) (hi, 47)
(Amphibian@1f6a7b9, hi, 47) (Amphibian@1f6a7b9, hi, 47)
(Vehicle@35ce36, Amphibian@757aef, hi, 47) (Vehicle@35ce36, Amphibian@757aef, hi, 47)

View File

@ -27,7 +27,7 @@ public class TupleTest2 {
System.out.println(h()); System.out.println(h());
System.out.println(k()); System.out.println(k());
} }
} /* Output: (80% match) } /* Output: (80% Match)
(hi, 47) (hi, 47)
(hi, 47) (hi, 47)
(Amphibian@7d772e, hi, 47) (Amphibian@7d772e, hi, 47)

View File

@ -15,7 +15,7 @@ public class UnboundedWildcards1 {
list1 = list; list1 = list;
list2 = list; list2 = list;
list3 = list; list3 = list;
} }
static void assign3(List<? extends Object> list) { static void assign3(List<? extends Object> list) {
list1 = list; list1 = list;
list2 = list; list2 = list;

View File

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

View File

@ -17,12 +17,12 @@ public class WatercolorSets {
Set<Watercolors> subset = intersection(set1, set2); Set<Watercolors> subset = intersection(set1, set2);
print("intersection(set1, set2): " + subset); print("intersection(set1, set2): " + subset);
print("difference(set1, subset): " + print("difference(set1, subset): " +
difference(set1, subset)); difference(set1, subset));
print("difference(set2, subset): " + print("difference(set2, subset): " +
difference(set2, subset)); difference(set2, subset));
print("complement(set1, set2): " + print("complement(set1, set2): " +
complement(set1, set2)); complement(set1, set2));
} }
} /* Output: (Sample) } /* Output: (Sample)
set1: [BRILLIANT_RED, CRIMSON, MAGENTA, ROSE_MADDER, VIOLET, CERULEAN_BLUE_HUE, PHTHALO_BLUE, ULTRAMARINE, COBALT_BLUE_HUE, PERMANENT_GREEN, VIRIDIAN_HUE] set1: [BRILLIANT_RED, CRIMSON, MAGENTA, ROSE_MADDER, VIOLET, CERULEAN_BLUE_HUE, PHTHALO_BLUE, ULTRAMARINE, COBALT_BLUE_HUE, PERMANENT_GREEN, VIRIDIAN_HUE]
set2: [CERULEAN_BLUE_HUE, PHTHALO_BLUE, ULTRAMARINE, COBALT_BLUE_HUE, PERMANENT_GREEN, VIRIDIAN_HUE, SAP_GREEN, YELLOW_OCHRE, BURNT_SIENNA, RAW_UMBER, BURNT_UMBER] set2: [CERULEAN_BLUE_HUE, PHTHALO_BLUE, ULTRAMARINE, COBALT_BLUE_HUE, PERMANENT_GREEN, VIRIDIAN_HUE, SAP_GREEN, YELLOW_OCHRE, BURNT_SIENNA, RAW_UMBER, BURNT_UMBER]

View File

@ -14,7 +14,7 @@ public class Wildcards {
// OK, but type information is lost: // OK, but type information is lost:
Object obj = holder.get(); Object obj = holder.get();
} }
// Similar to rawArgs(), but errors instead of warnings: // Similar to rawArgs(), but errors instead of warnings:
static void unboundedArg(Holder<?> holder, Object arg) { static void unboundedArg(Holder<?> holder, Object arg) {
// holder.set(arg); // Error: // holder.set(arg); // Error:
@ -27,7 +27,7 @@ public class Wildcards {
// OK, but type information is lost: // OK, but type information is lost:
Object obj = holder.get(); Object obj = holder.get();
} }
static <T> T exact1(Holder<T> holder) { static <T> T exact1(Holder<T> holder) {
T t = holder.get(); T t = holder.get();
return t; return t;
@ -45,7 +45,7 @@ public class Wildcards {
// cannot be applied to (T) // cannot be applied to (T)
T t = holder.get(); T t = holder.get();
return t; return t;
} }
static <T> static <T>
void wildSupertype(Holder<? super T> holder, T arg) { void wildSupertype(Holder<? super T> holder, T arg) {
holder.set(arg); holder.set(arg);
@ -68,7 +68,7 @@ public class Wildcards {
rawArgs(qualified, lng); rawArgs(qualified, lng);
rawArgs(unbounded, lng); rawArgs(unbounded, lng);
rawArgs(bounded, lng); rawArgs(bounded, lng);
unboundedArg(raw, lng); unboundedArg(raw, lng);
unboundedArg(qualified, lng); unboundedArg(qualified, lng);
unboundedArg(unbounded, lng); unboundedArg(unbounded, lng);
@ -81,7 +81,7 @@ public class Wildcards {
Long r2 = exact1(qualified); Long r2 = exact1(qualified);
Object r3 = exact1(unbounded); // Must return Object Object r3 = exact1(unbounded); // Must return Object
Long r4 = exact1(bounded); Long r4 = exact1(bounded);
// Long r5 = exact2(raw, lng); // Warnings: // Long r5 = exact2(raw, lng); // Warnings:
// Unchecked conversion from Holder to Holder<Long> // Unchecked conversion from Holder to Holder<Long>
// Unchecked method invocation: exact2(Holder<T>,T) // Unchecked method invocation: exact2(Holder<T>,T)
@ -93,7 +93,7 @@ public class Wildcards {
// Long r8 = exact2(bounded, lng); // Error: // Long r8 = exact2(bounded, lng); // Error:
// exact2(Holder<T>,T) cannot be applied // exact2(Holder<T>,T) cannot be applied
// to (Holder<capture of ? extends Long>,Long) // to (Holder<capture of ? extends Long>,Long)
// Long r9 = wildSubtype(raw, lng); // Warnings: // Long r9 = wildSubtype(raw, lng); // Warnings:
// Unchecked conversion from Holder // Unchecked conversion from Holder
// to Holder<? extends Long> // to Holder<? extends Long>
@ -104,7 +104,7 @@ public class Wildcards {
// OK, but can only return Object: // OK, but can only return Object:
Object r11 = wildSubtype(unbounded, lng); Object r11 = wildSubtype(unbounded, lng);
Long r12 = wildSubtype(bounded, lng); Long r12 = wildSubtype(bounded, lng);
// wildSupertype(raw, lng); // Warnings: // wildSupertype(raw, lng); // Warnings:
// Unchecked conversion from Holder // Unchecked conversion from Holder
// to Holder<? super Long> // to Holder<? super Long>

View File

@ -4,6 +4,7 @@
<property name="chapter" value="generics"/> <property name="chapter" value="generics"/>
<property name="excludedfiles" value="Erased.java HijackedInterface.java Manipulation.java MultipleInterfaceVariants.java NonCovariantGenerics.java UseList.java"/> <property name="excludedfiles" value="Erased.java HijackedInterface.java Manipulation.java MultipleInterfaceVariants.java NonCovariantGenerics.java UseList.java"/>
<import file="../Ant-Common.xml"/> <import file="../Ant-Common.xml"/>
<import file="../Ant-Clean.xml"/>
<target name="run" description="Compile and run" depends="build"> <target name="run" description="Compile and run" depends="build">
<jrun cls="ApplyTest" /> <jrun cls="ApplyTest" />

View File

@ -12,7 +12,7 @@ implements Generator<Coffee>, Iterable<Coffee> {
public CoffeeGenerator() {} public CoffeeGenerator() {}
// For iteration: // For iteration:
private int size = 0; private int size = 0;
public CoffeeGenerator(int sz) { size = sz; } public CoffeeGenerator(int sz) { size = sz; }
@Override @Override
public Coffee next() { public Coffee next() {
try { try {
@ -37,7 +37,7 @@ implements Generator<Coffee>, Iterable<Coffee> {
public void remove() { // Not implemented public void remove() { // Not implemented
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
}; };
@Override @Override
public Iterator<Coffee> iterator() { public Iterator<Coffee> iterator() {
return new CoffeeIterator(); return new CoffeeIterator();

View File

@ -15,7 +15,7 @@ class Decorator extends Basic {
public void set(String val) { basic.set(val); } public void set(String val) { basic.set(val); }
@Override @Override
public String get() { return basic.get(); } public String get() { return basic.get(); }
} }
class TimeStamped extends Decorator { class TimeStamped extends Decorator {
private final long timeStamp; private final long timeStamp;
@ -31,7 +31,7 @@ class SerialNumbered extends Decorator {
private final long serialNumber = counter++; private final long serialNumber = counter++;
public SerialNumbered(Basic basic) { super(basic); } public SerialNumbered(Basic basic) { super(basic); }
public long getSerialNumber() { return serialNumber; } public long getSerialNumber() { return serialNumber; }
} }
public class Decoration { public class Decoration {
public static void main(String[] args) { public static void main(String[] args) {

View File

@ -2,7 +2,6 @@
// Using JCheckBoxes. // Using JCheckBoxes.
import javax.swing.*; import javax.swing.*;
import java.awt.*; import java.awt.*;
import java.awt.event.*;
import static net.mindview.util.SwingConsole.*; import static net.mindview.util.SwingConsole.*;
public class CheckBoxes extends JFrame { public class CheckBoxes extends JFrame {

View File

@ -2,7 +2,6 @@
// Using drop-down lists. // Using drop-down lists.
import javax.swing.*; import javax.swing.*;
import java.awt.*; import java.awt.*;
import java.awt.event.*;
import static net.mindview.util.SwingConsole.*; import static net.mindview.util.SwingConsole.*;
public class ComboBoxes extends JFrame { public class ComboBoxes extends JFrame {

View File

@ -2,7 +2,6 @@
// Creating and using Dialog Boxes. // Creating and using Dialog Boxes.
import javax.swing.*; import javax.swing.*;
import java.awt.*; import java.awt.*;
import java.awt.event.*;
import static net.mindview.util.SwingConsole.*; import static net.mindview.util.SwingConsole.*;
class MyDialog extends JDialog { class MyDialog extends JDialog {

View File

@ -2,7 +2,6 @@
// Icon behavior in JButtons. // Icon behavior in JButtons.
import javax.swing.*; import javax.swing.*;
import java.awt.*; import java.awt.*;
import java.awt.event.*;
import static net.mindview.util.SwingConsole.*; import static net.mindview.util.SwingConsole.*;
public class Faces extends JFrame { public class Faces extends JFrame {

View File

@ -2,7 +2,6 @@
// Putting HTML text on Swing components. // Putting HTML text on Swing components.
import javax.swing.*; import javax.swing.*;
import java.awt.*; import java.awt.*;
import java.awt.event.*;
import static net.mindview.util.SwingConsole.*; import static net.mindview.util.SwingConsole.*;
public class HTMLButton extends JFrame { public class HTMLButton extends JFrame {

View File

@ -2,7 +2,6 @@
// Using Callables for long-running tasks. // Using Callables for long-running tasks.
import javax.swing.*; import javax.swing.*;
import java.awt.*; import java.awt.*;
import java.awt.event.*;
import java.util.concurrent.*; import java.util.concurrent.*;
import net.mindview.util.*; import net.mindview.util.*;
import static net.mindview.util.SwingConsole.*; import static net.mindview.util.SwingConsole.*;

View File

@ -2,7 +2,6 @@
// Long-running tasks in threads. // Long-running tasks in threads.
import javax.swing.*; import javax.swing.*;
import java.awt.*; import java.awt.*;
import java.awt.event.*;
import java.util.concurrent.*; import java.util.concurrent.*;
import static net.mindview.util.SwingConsole.*; import static net.mindview.util.SwingConsole.*;

View File

@ -2,7 +2,6 @@
// A badly designed program. // A badly designed program.
import javax.swing.*; import javax.swing.*;
import java.awt.*; import java.awt.*;
import java.awt.event.*;
import java.util.concurrent.*; import java.util.concurrent.*;
import static net.mindview.util.SwingConsole.*; import static net.mindview.util.SwingConsole.*;

Some files were not shown because too many files have changed in this diff Show More