diff --git a/AddAndSubtractPaths.java b/AddAndSubtractPaths.java new file mode 100644 index 000000000..24e044c1a --- /dev/null +++ b/AddAndSubtractPaths.java @@ -0,0 +1,87 @@ +// files/AddAndSubtractPaths.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +import java.nio.file.*; +import java.io.IOException; + +public class AddAndSubtractPaths { + static Path base = Paths.get("..", "..", "..") + .toAbsolutePath() + .normalize(); + static void show(int id, Path result) { + if(result.isAbsolute()) + System.err.println("(" + id + ")[relativize] " + + base.relativize(result)); + else + System.err.println("(" + id + ") " + result); + try { + System.err.println("RealPath: " + + result.toRealPath()); + } catch(IOException e) { + System.err.println(e); + } + } + public static void main(String[] args) { + System.err.println(System.getProperty("os.name")); + System.err.println(base); + Path p = Paths.get("AddAndSubtractPaths.java") + .toAbsolutePath(); + show(1, p); + Path convoluted = p.getParent().getParent() + .resolve("strings") + .resolve("..") + .resolve(p.getParent().getFileName()); + show(2, convoluted); + show(3, convoluted.normalize()); + + Path p2 = Paths.get("..", ".."); + show(4, p2); + show(5, p2.normalize()); + show(6, p2.toAbsolutePath().normalize()); + + Path p3 = Paths.get(".").toAbsolutePath(); + Path p4 = p3.resolve(p2); + show(7, p4); + show(8, p4.normalize()); + + Path p5 = Paths.get("").toAbsolutePath(); + show(9, p5); + show(10, p5.resolveSibling("strings")); + show(11, Paths.get("nonexistent")); + } +} +/* Output: +Windows 10 +C:\Users\Bruce\Documents\GitHub +(1)r on- +java\ExtractedExamples\files\AddAndSubtractPaths.java +RealPath: C:\Users\Bruce\Documents\GitHub\on- +java\ExtractedExamples\files\AddAndSubtractPaths.java +(2)r on-java\ExtractedExamples\strings\..\files +RealPath: C:\Users\Bruce\Documents\GitHub\on- +java\ExtractedExamples\files +(3)r on-java\ExtractedExamples\files +RealPath: C:\Users\Bruce\Documents\GitHub\on- +java\ExtractedExamples\files +(4) ..\.. +RealPath: C:\Users\Bruce\Documents\GitHub\on-java +(5) ..\.. +RealPath: C:\Users\Bruce\Documents\GitHub\on-java +(6)r on-java +RealPath: C:\Users\Bruce\Documents\GitHub\on-java +(7)r on-java\ExtractedExamples\files\.\..\.. +RealPath: C:\Users\Bruce\Documents\GitHub\on-java +(8)r on-java +RealPath: C:\Users\Bruce\Documents\GitHub\on-java +(9)r on-java\ExtractedExamples\files +RealPath: C:\Users\Bruce\Documents\GitHub\on- +java\ExtractedExamples\files +(10)r on-java\ExtractedExamples\strings +RealPath: C:\Users\Bruce\Documents\GitHub\on- +java\ExtractedExamples\strings +(11) nonexistent +java.nio.file.NoSuchFileException: +C:\Users\Bruce\Documents\GitHub\on- +java\ExtractedExamples\files\nonexistent +*/ diff --git a/Directories.java b/Directories.java new file mode 100644 index 000000000..94ed9a3db --- /dev/null +++ b/Directories.java @@ -0,0 +1,94 @@ +// files/Directories.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +import java.util.*; +import java.nio.file.*; +//import onjava.RmDir; + +public class Directories { + static Path test = Paths.get("test"); + static String sep = + FileSystems.getDefault().getSeparator(); + static List parts = + Arrays.asList("foo", "bar", "baz", "bag"); + static Path makeVariant() { + Collections.rotate(parts, 1); + return Paths.get("test", String.join(sep, parts)); + } + static void refreshTestDir() throws Exception { + if(Files.exists(test)) + RmDir.rmdir(test); + if(!Files.exists(test)) + Files.createDirectory(test); + } + public static void + main(String[] args) throws Exception { + refreshTestDir(); + Files.createFile(test.resolve("Hello.txt")); + Path variant = makeVariant(); + // Throws exception (too many levels): + try { + Files.createDirectory(variant); + } catch(Exception e) { + System.err.println("Nope, that doesn't work."); + } + populateTestDir(); + Path tempdir = + Files.createTempDirectory(test, "DIR_"); + Files.createTempFile(tempdir, "pre", ".non"); + Files.newDirectoryStream(test) + .forEach(System.out::println); + System.err.println("*********"); + Files.walk(test).forEach(System.out::println); + } + static void populateTestDir() throws Exception { + for(int i = 0; i < parts.size(); i++) { + Path variant = makeVariant(); + if(!Files.exists(variant)) { + Files.createDirectories(variant); + Files.copy(Paths.get("Directories.java"), + variant.resolve("File.txt")); + Files.createTempFile(variant, null, null); + } + } + } +} +/* Output: +Nope, that doesn't work. +test\bag +test\bar +test\baz +test\DIR_5142667942049986036 +test\foo +test\Hello.txt +********* +test +test\bag +test\bag\foo +test\bag\foo\bar +test\bag\foo\bar\baz +test\bag\foo\bar\baz\8279660869874696036.tmp +test\bag\foo\bar\baz\File.txt +test\bar +test\bar\baz +test\bar\baz\bag +test\bar\baz\bag\foo +test\bar\baz\bag\foo\1274043134240426261.tmp +test\bar\baz\bag\foo\File.txt +test\baz +test\baz\bag +test\baz\bag\foo +test\baz\bag\foo\bar +test\baz\bag\foo\bar\6130572530014544105.tmp +test\baz\bag\foo\bar\File.txt +test\DIR_5142667942049986036 +test\DIR_5142667942049986036\pre7704286843227113253.non +test\foo +test\foo\bar +test\foo\bar\baz +test\foo\bar\baz\bag +test\foo\bar\baz\bag\5412864507741775436.tmp +test\foo\bar\baz\bag\File.txt +test\Hello.txt +*/ diff --git a/PartsOfPaths.java b/PartsOfPaths.java new file mode 100644 index 000000000..b272ebf89 --- /dev/null +++ b/PartsOfPaths.java @@ -0,0 +1,47 @@ +// files/PartsOfPaths.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +import java.nio.file.*; + +public class PartsOfPaths { + public static void main(String[] args) { + System.err.println(System.getProperty("os.name")); + Path p = Paths.get("PartsOfPaths.java").toAbsolutePath(); + System.err.println(p); + System.err.println(Files.exists(p)); + + for(int i = 0; i < p.getNameCount(); i++) + System.err.println("第" + i + "部分--"+p.getName(i)); + System.err.println("ends with '.java': " + + p.endsWith(".java")); + for(Path pp : p) { + System.err.print(pp + ": "); + System.err.print(p.startsWith(pp) + " : "); + System.err.println(p.endsWith(pp)); + } + System.err.println("Starts with " + p.getRoot() + + " " + p.startsWith(p.getRoot())); + } +} +/* Output: +Windows 10 +Users +Bruce +Documents +GitHub +on-java +ExtractedExamples +files +PartsOfPaths.java +ends with '.java': false +Users: false : false +Bruce: false : false +Documents: false : false +GitHub: false : false +on-java: false : false +ExtractedExamples: false : false +files: false : false +PartsOfPaths.java: false : true +Starts with C:\ true +*/ diff --git a/PathInfo.java b/PathInfo.java new file mode 100644 index 000000000..58089d9bc --- /dev/null +++ b/PathInfo.java @@ -0,0 +1,110 @@ +// files/PathInfo.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +import java.nio.file.*; +import java.net.URI; +import java.io.File; +import java.io.IOException; + +public class PathInfo { + static void show(String id, Object p) { + System.err.println(id + ": " + p); + } + static void info(Path p) { + show("toString", p); + show("Exists", Files.exists(p)); + show("RegularFile", Files.isRegularFile(p)); + show("Directory", Files.isDirectory(p)); + show("Absolute", p.isAbsolute()); + show("FileName", p.getFileName()); + show("Parent", p.getParent()); + show("Root", p.getRoot()); + System.err.println("******************"); + } + public static void main(String[] args) { + System.err.println(System.getProperty("os.name")); + + info(Paths.get( + "C:", "path", "to", "nowhere", "NoFile.txt")); + + Path p = Paths.get("PathInfo.java"); + info(p); + + Path ap = p.toAbsolutePath(); + info(ap); + + info(ap.getParent()); + + try { + info(p.toRealPath()); + } catch(IOException e) { + System.err.println(e); + } + + URI u = p.toUri(); + System.err.println("URI: " + u); + + Path puri = Paths.get(u); + System.err.println(Files.exists(puri)); + + File f = ap.toFile(); // Don't be fooled + } +} +/* Output: +Windows 10 +toString: C:\path\to\nowhere\NoFile.txt +Exists: false +RegularFile: false +Directory: false +Absolute: true +FileName: NoFile.txt +Parent: C:\path\to\nowhere +Root: C:\ +****************** +toString: PathInfo.java +Exists: true +RegularFile: true +Directory: false +Absolute: false +FileName: PathInfo.java +Parent: null +Root: null +****************** +toString: C:\Users\Bruce\Documents\GitHub\on- +java\ExtractedExamples\files\PathInfo.java +Exists: true +RegularFile: true +Directory: false +Absolute: true +FileName: PathInfo.java +Parent: C:\Users\Bruce\Documents\GitHub\on- +java\ExtractedExamples\files +Root: C:\ +****************** +toString: C:\Users\Bruce\Documents\GitHub\on- +java\ExtractedExamples\files +Exists: true +RegularFile: false +Directory: true +Absolute: true +FileName: files +Parent: C:\Users\Bruce\Documents\GitHub\on- +java\ExtractedExamples +Root: C:\ +****************** +toString: C:\Users\Bruce\Documents\GitHub\on- +java\ExtractedExamples\files\PathInfo.java +Exists: true +RegularFile: true +Directory: false +Absolute: true +FileName: PathInfo.java +Parent: C:\Users\Bruce\Documents\GitHub\on- +java\ExtractedExamples\files +Root: C:\ +****************** +URI: file:///C:/Users/Bruce/Documents/GitHub/on- +java/ExtractedExamples/files/PathInfo.java +true +*/ diff --git a/annotations/AtUnitExample1.java b/annotations/AtUnitExample1.java index 3b1f6fece..9c97dd632 100644 --- a/annotations/AtUnitExample1.java +++ b/annotations/AtUnitExample1.java @@ -13,7 +13,7 @@ public String methodOne() { return "This is methodOne"; } public int methodTwo() { - System.out.println("This is methodTwo"); + System.err.println("This is methodTwo"); return 2; } @Test diff --git a/annotations/AtUnitExample2.java b/annotations/AtUnitExample2.java index bf3f1d5cb..cc876ce1a 100644 --- a/annotations/AtUnitExample2.java +++ b/annotations/AtUnitExample2.java @@ -15,7 +15,7 @@ public String methodOne() { return "This is methodOne"; } public int methodTwo() { - System.out.println("This is methodTwo"); + System.err.println("This is methodTwo"); return 2; } @Test diff --git a/annotations/AtUnitExample3.java b/annotations/AtUnitExample3.java index 02092591b..a59ec2bf9 100644 --- a/annotations/AtUnitExample3.java +++ b/annotations/AtUnitExample3.java @@ -16,7 +16,7 @@ public String methodOne() { return "This is methodOne"; } public int methodTwo() { - System.out.println("This is methodTwo"); + System.err.println("This is methodTwo"); return 2; } @TestObjectCreate diff --git a/annotations/AtUnitExample4.java b/annotations/AtUnitExample4.java index 6b644b178..55cef1b8a 100644 --- a/annotations/AtUnitExample4.java +++ b/annotations/AtUnitExample4.java @@ -43,24 +43,24 @@ static AtUnitExample4 create() { } @Test boolean words() { - System.out.println("'" + getWord() + "'"); + System.err.println("'" + getWord() + "'"); return getWord().equals("are"); } @Test boolean scramble1() { // Use specific seed to get verifiable results: rand = new Random(47); - System.out.println("'" + getWord() + "'"); + System.err.println("'" + getWord() + "'"); String scrambled = scrambleWord(); - System.out.println(scrambled); + System.err.println(scrambled); return scrambled.equals("lAl"); } @Test boolean scramble2() { rand = new Random(74); - System.out.println("'" + getWord() + "'"); + System.err.println("'" + getWord() + "'"); String scrambled = scrambleWord(); - System.out.println(scrambled); + System.err.println(scrambled); return scrambled.equals("tsaeborornussu"); } } diff --git a/annotations/AtUnitExample5.java b/annotations/AtUnitExample5.java index d7cf95dfc..64f36cf70 100644 --- a/annotations/AtUnitExample5.java +++ b/annotations/AtUnitExample5.java @@ -32,7 +32,7 @@ static AtUnitExample5 create() { } @TestObjectCleanup static void cleanup(AtUnitExample5 tobj) { - System.out.println("Running cleanup"); + System.err.println("Running cleanup"); output.close(); } @Test diff --git a/annotations/DemoProcessFiles.java b/annotations/DemoProcessFiles.java index 6e2505373..703cf09ca 100644 --- a/annotations/DemoProcessFiles.java +++ b/annotations/DemoProcessFiles.java @@ -6,7 +6,7 @@ public class DemoProcessFiles { public static void main(String[] args) { - new ProcessFiles(file -> System.out.println(file), + new ProcessFiles(file -> System.err.println(file), "java").start(args); } } diff --git a/annotations/Testable.java b/annotations/Testable.java index bc48f4161..a63d06f10 100644 --- a/annotations/Testable.java +++ b/annotations/Testable.java @@ -7,7 +7,7 @@ public class Testable { public void execute() { - System.out.println("Executing.."); + System.err.println("Executing.."); } @Test void testExecute() { execute(); } diff --git a/annotations/UseCaseTracker.java b/annotations/UseCaseTracker.java index 5489b762b..bb6696eb5 100644 --- a/annotations/UseCaseTracker.java +++ b/annotations/UseCaseTracker.java @@ -12,13 +12,13 @@ public class UseCaseTracker { for(Method m : cl.getDeclaredMethods()) { UseCase uc = m.getAnnotation(UseCase.class); if(uc != null) { - System.out.println("Found Use Case " + + System.err.println("Found Use Case " + uc.id() + "\n " + uc.description()); useCases.remove(Integer.valueOf(uc.id())); } } useCases.forEach(i -> - System.out.println("Missing use case " + i)); + System.err.println("Missing use case " + i)); } public static void main(String[] args) { List useCases = IntStream.range(47, 51) diff --git a/annotations/database/TableCreator.java b/annotations/database/TableCreator.java index 53322fc72..86f25b65a 100644 --- a/annotations/database/TableCreator.java +++ b/annotations/database/TableCreator.java @@ -14,7 +14,7 @@ public class TableCreator { public static void main(String[] args) throws Exception { if(args.length < 1) { - System.out.println( + System.err.println( "arguments: annotated classes"); System.exit(0); } @@ -22,7 +22,7 @@ public class TableCreator { Class cl = Class.forName(className); DBTable dbTable = cl.getAnnotation(DBTable.class); if(dbTable == null) { - System.out.println( + System.err.println( "No DBTable annotations in class " + className); continue; @@ -67,7 +67,7 @@ public class TableCreator { // Remove trailing comma String tableCreate = createCommand.substring( 0, createCommand.length() - 1) + ");"; - System.out.println("Table Creation SQL for " + + System.err.println("Table Creation SQL for " + className + " is:\n" + tableCreate); } } diff --git a/annotations/ifx/IfaceExtractorProcessor.java b/annotations/ifx/IfaceExtractorProcessor.java index d17156f88..eca077b01 100644 --- a/annotations/ifx/IfaceExtractorProcessor.java +++ b/annotations/ifx/IfaceExtractorProcessor.java @@ -73,7 +73,7 @@ public boolean process( signature += method.getSimpleName(); signature += createArgList( method.getParameters()); - System.out.println(signature); + System.err.println(signature); writer.write(signature + ";\n"); } writer.write("}"); diff --git a/annotations/ifx/Multiplier.java b/annotations/ifx/Multiplier.java index b5b99a1b8..7e5501e70 100644 --- a/annotations/ifx/Multiplier.java +++ b/annotations/ifx/Multiplier.java @@ -25,7 +25,7 @@ public double timesTen(double arg) { } public static void main(String[] args) { Multiplier m = new Multiplier(); - System.out.println( + System.err.println( "11 * 16 = " + m.multiply(11, 16)); } } diff --git a/annotations/simplest/SimpleProcessor.java b/annotations/simplest/SimpleProcessor.java index a85d8987a..589c97444 100644 --- a/annotations/simplest/SimpleProcessor.java +++ b/annotations/simplest/SimpleProcessor.java @@ -19,29 +19,29 @@ public boolean process( Set annotations, RoundEnvironment env) { for(TypeElement t : annotations) - System.out.println(t); + System.err.println(t); for(Element el : env.getElementsAnnotatedWith(Simple.class)) display(el); return false; } private void display(Element el) { - System.out.println("==== " + el + " ===="); - System.out.println(el.getKind() + + System.err.println("==== " + el + " ===="); + System.err.println(el.getKind() + " : " + el.getModifiers() + " : " + el.getSimpleName() + " : " + el.asType()); if(el.getKind().equals(ElementKind.CLASS)) { TypeElement te = (TypeElement)el; - System.out.println(te.getQualifiedName()); - System.out.println(te.getSuperclass()); - System.out.println(te.getEnclosedElements()); + System.err.println(te.getQualifiedName()); + System.err.println(te.getSuperclass()); + System.err.println(te.getEnclosedElements()); } if(el.getKind().equals(ElementKind.METHOD)) { ExecutableElement ex = (ExecutableElement)el; - System.out.print(ex.getReturnType() + " "); - System.out.print(ex.getSimpleName() + "("); - System.out.println(ex.getParameters() + ")"); + System.err.print(ex.getReturnType() + " "); + System.err.print(ex.getSimpleName() + "("); + System.err.println(ex.getParameters() + ")"); } } } diff --git a/annotations/simplest/SimpleTest.java b/annotations/simplest/SimpleTest.java index 689d12fdc..aac040ae9 100644 --- a/annotations/simplest/SimpleTest.java +++ b/annotations/simplest/SimpleTest.java @@ -14,11 +14,11 @@ public class SimpleTest { public SimpleTest() {} @Simple public void foo() { - System.out.println("SimpleTest.foo()"); + System.err.println("SimpleTest.foo()"); } @Simple public void bar(String s, int i, float f) { - System.out.println("SimpleTest.bar()"); + System.err.println("SimpleTest.bar()"); } @Simple public static void main(String[] args) { diff --git a/arrays/AlphabeticSearch.java b/arrays/AlphabeticSearch.java index 70adc8ff5..7366c52c9 100644 --- a/arrays/AlphabeticSearch.java +++ b/arrays/AlphabeticSearch.java @@ -14,7 +14,7 @@ public static void main(String[] args) { show(sa); int index = Arrays.binarySearch(sa, sa[10], String.CASE_INSENSITIVE_ORDER); - System.out.println( + System.err.println( "Index: "+ index + "\n"+ sa[index]); } } diff --git a/arrays/ArrayCopying.java b/arrays/ArrayCopying.java index c68c2a0d6..cd944bfde 100644 --- a/arrays/ArrayCopying.java +++ b/arrays/ArrayCopying.java @@ -64,7 +64,7 @@ public static void main(String[] args) { Sub[] d3 = Arrays.copyOf( b2, b2.length, Sub[].class); // [6] } catch(Exception e) { - System.out.println(e); + System.err.println(e); } } } diff --git a/arrays/ArrayOptions.java b/arrays/ArrayOptions.java index bb6cbfbb6..c1c2f29d7 100644 --- a/arrays/ArrayOptions.java +++ b/arrays/ArrayOptions.java @@ -33,12 +33,12 @@ public static void main(String[] args) { }; // (Trailing comma is optional) - System.out.println("a.length = " + a.length); - System.out.println("b.length = " + b.length); - System.out.println("c.length = " + c.length); - System.out.println("d.length = " + d.length); + System.err.println("a.length = " + a.length); + System.err.println("b.length = " + b.length); + System.err.println("c.length = " + c.length); + System.err.println("d.length = " + d.length); a = d; - System.out.println("a.length = " + a.length); + System.err.println("a.length = " + a.length); // Arrays of primitives: int[] e; // Null reference @@ -53,14 +53,14 @@ public static void main(String[] args) { int[] h = { 11, 47, 93 }; // Compile error: variable e not initialized: - //- System.out.println("e.length = " + e.length); - System.out.println("f.length = " + f.length); - System.out.println("g.length = " + g.length); - System.out.println("h.length = " + h.length); + //- System.err.println("e.length = " + e.length); + System.err.println("f.length = " + f.length); + System.err.println("g.length = " + g.length); + System.err.println("h.length = " + h.length); e = h; - System.out.println("e.length = " + e.length); + System.err.println("e.length = " + e.length); e = new int[]{ 1, 2 }; - System.out.println("e.length = " + e.length); + System.err.println("e.length = " + e.length); } } /* Output: diff --git a/arrays/ArraySearching.java b/arrays/ArraySearching.java index fb4085e9b..b8a9f7803 100644 --- a/arrays/ArraySearching.java +++ b/arrays/ArraySearching.java @@ -17,7 +17,7 @@ public static void main(String[] args) { int r = rand.getAsInt(); int location = Arrays.binarySearch(a, r); if(location >= 0) { - System.out.println( + System.err.println( "Location of " + r + " is " + location + ", a[" + location + "] is " + a[location]); break; // Out of while loop diff --git a/arrays/AssemblingMultidimensionalArrays.java b/arrays/AssemblingMultidimensionalArrays.java index e79302b30..790aa98cb 100644 --- a/arrays/AssemblingMultidimensionalArrays.java +++ b/arrays/AssemblingMultidimensionalArrays.java @@ -14,7 +14,7 @@ public static void main(String[] args) { for(int j = 0; j < a[i].length; j++) a[i][j] = i * j; // Autoboxing } - System.out.println(Arrays.deepToString(a)); + System.err.println(Arrays.deepToString(a)); } } /* Output: diff --git a/arrays/AutoboxingArrays.java b/arrays/AutoboxingArrays.java index 25b3a0e88..ffb370ea6 100644 --- a/arrays/AutoboxingArrays.java +++ b/arrays/AutoboxingArrays.java @@ -12,7 +12,7 @@ public static void main(String[] args) { { 51, 52, 53, 54, 55, 56, 57, 58, 59, 60 }, { 71, 72, 73, 74, 75, 76, 77, 78, 79, 80 }, }; - System.out.println(Arrays.deepToString(a)); + System.err.println(Arrays.deepToString(a)); } } /* Output: diff --git a/arrays/CollectionComparison.java b/arrays/CollectionComparison.java index fc703c0a1..42e28c7ef 100644 --- a/arrays/CollectionComparison.java +++ b/arrays/CollectionComparison.java @@ -22,22 +22,22 @@ public static void main(String[] args) { for(int i = 0; i < 5; i++) spheres[i] = new BerylliumSphere(); show(spheres); - System.out.println(spheres[4]); + System.err.println(spheres[4]); List sphereList = Suppliers.create( ArrayList::new, BerylliumSphere::new, 5); - System.out.println(sphereList); - System.out.println(sphereList.get(4)); + System.err.println(sphereList); + System.err.println(sphereList.get(4)); int[] integers = { 0, 1, 2, 3, 4, 5 }; show(integers); - System.out.println(integers[4]); + System.err.println(integers[4]); List intList = new ArrayList<>( Arrays.asList(0, 1, 2, 3, 4, 5)); intList.add(97); - System.out.println(intList); - System.out.println(intList.get(4)); + System.err.println(intList); + System.err.println(intList.get(4)); } } /* Output: diff --git a/arrays/ComparingArrays.java b/arrays/ComparingArrays.java index 9ddad69d0..b8674747c 100644 --- a/arrays/ComparingArrays.java +++ b/arrays/ComparingArrays.java @@ -19,31 +19,31 @@ public static void main(String[] args) { int[] a1 = new int[SZ], a2 = new int[SZ]; Arrays.setAll(a1, new Count.Integer()::get); Arrays.setAll(a2, new Count.Integer()::get); - System.out.println( + System.err.println( "a1 == a2: " + Arrays.equals(a1, a2)); a2[3] = 11; - System.out.println( + System.err.println( "a1 == a2: " + Arrays.equals(a1, a2)); Integer[] a1w = new Integer[SZ], a2w = new Integer[SZ]; Arrays.setAll(a1w, new Count.Integer()::get); Arrays.setAll(a2w, new Count.Integer()::get); - System.out.println( + System.err.println( "a1w == a2w: " + Arrays.equals(a1w, a2w)); a2w[3] = 11; - System.out.println( + System.err.println( "a1w == a2w: " + Arrays.equals(a1w, a2w)); String[][] md1 = twoDArray(), md2 = twoDArray(); - System.out.println(Arrays.deepToString(md1)); - System.out.println("deepEquals(md1, md2): " + + System.err.println(Arrays.deepToString(md1)); + System.err.println("deepEquals(md1, md2): " + Arrays.deepEquals(md1, md2)); - System.out.println( + System.err.println( "md1 == md2: " + Arrays.equals(md1, md2)); md1[4][1] = "#$#$#$#"; - System.out.println(Arrays.deepToString(md1)); - System.out.println("deepEquals(md1, md2): " + + System.err.println(Arrays.deepToString(md1)); + System.err.println("deepEquals(md1, md2): " + Arrays.deepEquals(md1, md2)); } } diff --git a/arrays/MultiDimWrapperArray.java b/arrays/MultiDimWrapperArray.java index 1185d0f93..690bddf67 100644 --- a/arrays/MultiDimWrapperArray.java +++ b/arrays/MultiDimWrapperArray.java @@ -21,11 +21,11 @@ public static void main(String[] args) { { "Jumped", "Over" }, { "The", "Lazy", "Brown", "Dog", "&", "friend" }, }; - System.out.println( + System.err.println( "a1: " + Arrays.deepToString(a1)); - System.out.println( + System.err.println( "a2: " + Arrays.deepToString(a2)); - System.out.println( + System.err.println( "a3: " + Arrays.deepToString(a3)); } } diff --git a/arrays/MultidimensionalObjectArrays.java b/arrays/MultidimensionalObjectArrays.java index 998e7c991..fe84bf785 100644 --- a/arrays/MultidimensionalObjectArrays.java +++ b/arrays/MultidimensionalObjectArrays.java @@ -15,7 +15,7 @@ public static void main(String[] args) { new BerylliumSphere(), new BerylliumSphere(), new BerylliumSphere(), new BerylliumSphere() }, }; - System.out.println(Arrays.deepToString(spheres)); + System.err.println(Arrays.deepToString(spheres)); } } /* Output: diff --git a/arrays/MultidimensionalPrimitiveArray.java b/arrays/MultidimensionalPrimitiveArray.java index 8ed5884f9..1750eb94b 100644 --- a/arrays/MultidimensionalPrimitiveArray.java +++ b/arrays/MultidimensionalPrimitiveArray.java @@ -10,7 +10,7 @@ public static void main(String[] args) { { 1, 2, 3, }, { 4, 5, 6, }, }; - System.out.println(Arrays.deepToString(a)); + System.err.println(Arrays.deepToString(a)); } } /* Output: diff --git a/arrays/ParallelPrefix1.java b/arrays/ParallelPrefix1.java index e180d019a..7f9d74ae5 100644 --- a/arrays/ParallelPrefix1.java +++ b/arrays/ParallelPrefix1.java @@ -10,11 +10,11 @@ public class ParallelPrefix1 { public static void main(String[] args) { int[] nums = new Count.Pint().array(10); show(nums); - System.out.println(Arrays.stream(nums) + System.err.println(Arrays.stream(nums) .reduce(Integer::sum).getAsInt()); Arrays.parallelPrefix(nums, Integer::sum); show(nums); - System.out.println(Arrays.stream( + System.err.println(Arrays.stream( new Count.Pint().array(6)) .reduce(Integer::sum).getAsInt()); } diff --git a/arrays/ParallelPrefix3.java b/arrays/ParallelPrefix3.java index ed2751dca..e42b8a286 100644 --- a/arrays/ParallelPrefix3.java +++ b/arrays/ParallelPrefix3.java @@ -11,9 +11,9 @@ public static void main(String[] args) { long[] nums = new long[SIZE]; Arrays.setAll(nums, n -> n); Arrays.parallelPrefix(nums, Long::sum); - System.out.println("First 20: " + nums[19]); - System.out.println("First 200: " + nums[199]); - System.out.println("All: " + nums[nums.length-1]); + System.err.println("First 20: " + nums[19]); + System.err.println("First 200: " + nums[199]); + System.err.println("All: " + nums[nums.length-1]); } } /* Output: diff --git a/arrays/RaggedArray.java b/arrays/RaggedArray.java index bd7d625bb..c9fc9c406 100644 --- a/arrays/RaggedArray.java +++ b/arrays/RaggedArray.java @@ -17,7 +17,7 @@ public static void main(String[] args) { Arrays.setAll(a[i][j], n -> val++); // [1] } } - System.out.println(Arrays.deepToString(a)); + System.err.println(Arrays.deepToString(a)); } } /* Output: diff --git a/arrays/TestCount.java b/arrays/TestCount.java index a77e00f76..ab4439363 100644 --- a/arrays/TestCount.java +++ b/arrays/TestCount.java @@ -11,7 +11,7 @@ public class TestCount { static final int SZ = 5; public static void main(String[] args) { - System.out.println("Boolean"); + System.err.println("Boolean"); Boolean[] a1 = new Boolean[SZ]; Arrays.setAll(a1, new Count.Boolean()::get); show(a1); @@ -24,7 +24,7 @@ public static void main(String[] args) { new Count.Pboolean().array(SZ + 3); show(a1b); - System.out.println("Byte"); + System.err.println("Byte"); Byte[] a2 = new Byte[SZ]; Arrays.setAll(a2, new Count.Byte()::get); show(a2); @@ -36,7 +36,7 @@ public static void main(String[] args) { byte[] a2b = new Count.Pbyte().array(SZ + 3); show(a2b); - System.out.println("Character"); + System.err.println("Character"); Character[] a3 = new Character[SZ]; Arrays.setAll(a3, new Count.Character()::get); show(a3); @@ -48,7 +48,7 @@ public static void main(String[] args) { char[] a3b = new Count.Pchar().array(SZ + 3); show(a3b); - System.out.println("Short"); + System.err.println("Short"); Short[] a4 = new Short[SZ]; Arrays.setAll(a4, new Count.Short()::get); show(a4); @@ -60,7 +60,7 @@ public static void main(String[] args) { short[] a4b = new Count.Pshort().array(SZ + 3); show(a4b); - System.out.println("Integer"); + System.err.println("Integer"); int[] a5 = new int[SZ]; Arrays.setAll(a5, new Count.Integer()::get); show(a5); @@ -76,7 +76,7 @@ public static void main(String[] args) { a5 = new Count.Pint().array(SZ + 3); show(a5); - System.out.println("Long"); + System.err.println("Long"); long[] a6 = new long[SZ]; Arrays.setAll(a6, new Count.Long()::get); show(a6); @@ -91,7 +91,7 @@ public static void main(String[] args) { a6 = new Count.Plong().array(SZ + 3); show(a6); - System.out.println("Float"); + System.err.println("Float"); Float[] a7 = new Float[SZ]; Arrays.setAll(a7, new Count.Float()::get); show(a7); @@ -103,7 +103,7 @@ public static void main(String[] args) { float[] a7b = new Count.Pfloat().array(SZ + 3); show(a7b); - System.out.println("Double"); + System.err.println("Double"); double[] a8 = new double[SZ]; Arrays.setAll(a8, new Count.Double()::get); show(a8); diff --git a/arrays/TestRand.java b/arrays/TestRand.java index 17e0718f3..8d8ce7d2d 100644 --- a/arrays/TestRand.java +++ b/arrays/TestRand.java @@ -11,7 +11,7 @@ public class TestRand { static final int SZ = 5; public static void main(String[] args) { - System.out.println("Boolean"); + System.err.println("Boolean"); Boolean[] a1 = new Boolean[SZ]; Arrays.setAll(a1, new Rand.Boolean()::get); show(a1); @@ -24,7 +24,7 @@ public static void main(String[] args) { new Rand.Pboolean().array(SZ + 3); show(a1b); - System.out.println("Byte"); + System.err.println("Byte"); Byte[] a2 = new Byte[SZ]; Arrays.setAll(a2, new Rand.Byte()::get); show(a2); @@ -36,7 +36,7 @@ public static void main(String[] args) { byte[] a2b = new Rand.Pbyte().array(SZ + 3); show(a2b); - System.out.println("Character"); + System.err.println("Character"); Character[] a3 = new Character[SZ]; Arrays.setAll(a3, new Rand.Character()::get); show(a3); @@ -48,7 +48,7 @@ public static void main(String[] args) { char[] a3b = new Rand.Pchar().array(SZ + 3); show(a3b); - System.out.println("Short"); + System.err.println("Short"); Short[] a4 = new Short[SZ]; Arrays.setAll(a4, new Rand.Short()::get); show(a4); @@ -60,7 +60,7 @@ public static void main(String[] args) { short[] a4b = new Rand.Pshort().array(SZ + 3); show(a4b); - System.out.println("Integer"); + System.err.println("Integer"); int[] a5 = new int[SZ]; Arrays.setAll(a5, new Rand.Integer()::get); show(a5); @@ -76,7 +76,7 @@ public static void main(String[] args) { a5 = new Rand.Pint().array(SZ + 3); show(a5); - System.out.println("Long"); + System.err.println("Long"); long[] a6 = new long[SZ]; Arrays.setAll(a6, new Rand.Long()::get); show(a6); @@ -91,7 +91,7 @@ public static void main(String[] args) { a6 = new Rand.Plong().array(SZ + 3); show(a6); - System.out.println("Float"); + System.err.println("Float"); Float[] a7 = new Float[SZ]; Arrays.setAll(a7, new Rand.Float()::get); show(a7); @@ -103,7 +103,7 @@ public static void main(String[] args) { float[] a7b = new Rand.Pfloat().array(SZ + 3); show(a7b); - System.out.println("Double"); + System.err.println("Double"); double[] a8 = new double[SZ]; Arrays.setAll(a8, new Rand.Double()::get); show(a8); @@ -119,7 +119,7 @@ public static void main(String[] args) { a8 = new Rand.Pdouble().array(SZ + 3); show(a8); - System.out.println("String"); + System.err.println("String"); String[] s = new String[SZ - 1]; Arrays.setAll(s, new Rand.String()::get); show(s); diff --git a/arrays/ThreeDWithNew.java b/arrays/ThreeDWithNew.java index 7aaef0694..046fc606d 100644 --- a/arrays/ThreeDWithNew.java +++ b/arrays/ThreeDWithNew.java @@ -8,7 +8,7 @@ public class ThreeDWithNew { public static void main(String[] args) { // 3-D array with fixed length: int[][][] a = new int[2][2][4]; - System.out.println(Arrays.deepToString(a)); + System.err.println(Arrays.deepToString(a)); } } /* Output: diff --git a/collections/AdapterMethodIdiom.java b/collections/AdapterMethodIdiom.java index a97abb411..9e161d09b 100644 --- a/collections/AdapterMethodIdiom.java +++ b/collections/AdapterMethodIdiom.java @@ -35,11 +35,11 @@ public static void main(String[] args) { Arrays.asList("To be or not to be".split(" "))); // Grabs the ordinary iterator via iterator(): for(String s : ral) - System.out.print(s + " "); - System.out.println(); + System.err.print(s + " "); + System.err.println(); // Hand it the Iterable of your choice for(String s : ral.reversed()) - System.out.print(s + " "); + System.err.print(s + " "); } } /* Output: diff --git a/collections/ApplesAndOrangesWithGenerics.java b/collections/ApplesAndOrangesWithGenerics.java index c251672ce..2112f7ee2 100644 --- a/collections/ApplesAndOrangesWithGenerics.java +++ b/collections/ApplesAndOrangesWithGenerics.java @@ -12,7 +12,7 @@ public static void main(String[] args) { // Compile-time error: // apples.add(new Orange()); for(Apple apple : apples) { - System.out.println(apple.id()); + System.err.println(apple.id()); } } } diff --git a/collections/ArrayIsNotIterable.java b/collections/ArrayIsNotIterable.java index d496feb16..d28a20d69 100644 --- a/collections/ArrayIsNotIterable.java +++ b/collections/ArrayIsNotIterable.java @@ -7,7 +7,7 @@ public class ArrayIsNotIterable { static void test(Iterable ib) { for(T t : ib) - System.out.print(t + " "); + System.err.print(t + " "); } public static void main(String[] args) { test(Arrays.asList(1, 2, 3)); diff --git a/collections/CollectionSequence.java b/collections/CollectionSequence.java index 6a12ed69f..814e6f2c6 100644 --- a/collections/CollectionSequence.java +++ b/collections/CollectionSequence.java @@ -2,7 +2,7 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -import typeinfo.pets.*; +import pets.*; import java.util.*; public class CollectionSequence @@ -31,7 +31,88 @@ public static void main(String[] args) { InterfaceVsIterator.display(c); InterfaceVsIterator.display(c.iterator()); } + +} + +class Test1 implements Collection { + + @Override + public int size() { + return 0; + } + + @Override + public boolean isEmpty() { + return false; + } + + @Override + public boolean contains(Object o) { + return false; + } + + @Override + public Iterator iterator() { + return null; + } + + @Override + public Object[] toArray() { + return new Object[0]; + } + + @Override + public T[] toArray(T[] a) { + return null; + } + + @Override + public boolean add(Pet pet) { + return false; + } + + @Override + public boolean remove(Object o) { + return false; + } + + @Override + public boolean containsAll(Collection c) { + return false; + } + + @Override + public boolean addAll(Collection c) { + return false; + } + + @Override + public boolean removeAll(Collection c) { + return false; + } + + @Override + public boolean retainAll(Collection c) { + return false; + } + + @Override + public void clear() { + + } + + @Override + public boolean equals(Object o) { + return false; + } + + @Override + public int hashCode() { + return 0; + } } + + /* Output: 0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug 7:Manx diff --git a/collections/CrossCollectionIteration.java b/collections/CrossCollectionIteration.java index 99769fe24..c0040ce10 100644 --- a/collections/CrossCollectionIteration.java +++ b/collections/CrossCollectionIteration.java @@ -2,16 +2,16 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -import typeinfo.pets.*; +import pets.*; import java.util.*; public class CrossCollectionIteration { public static void display(Iterator it) { while(it.hasNext()) { Pet p = it.next(); - System.out.print(p.id() + ":" + p + " "); + System.err.print(p.id() + ":" + p + " "); } - System.out.println(); + System.err.println(); } public static void main(String[] args) { List pets = Pets.list(8); @@ -33,4 +33,7 @@ public static void main(String[] args) { 7:Manx 5:Cymric 2:Cymric 7:Manx 1:Manx 3:Mutt 6:Pug 4:Pug 0:Rat + +self-note: Iterator 的真正威力:能够将遍历序列的操作与该序列的底层结构分离。 + 出于这个原因,我们有时会说:迭代器统一了对集合的访问方式。 */ diff --git a/collections/CrossCollectionIteration2.java b/collections/CrossCollectionIteration2.java index c7da143ff..b184dcbc1 100644 --- a/collections/CrossCollectionIteration2.java +++ b/collections/CrossCollectionIteration2.java @@ -10,9 +10,9 @@ public static void display(Iterable ip) { Iterator it = ip.iterator(); while(it.hasNext()) { Pet p = it.next(); - System.out.print(p.id() + ":" + p + " "); + System.err.print(p.id() + ":" + p + " "); } - System.out.println(); + System.err.println(); } public static void main(String[] args) { List pets = Pets.list(8); diff --git a/collections/EnvironmentVariables.java b/collections/EnvironmentVariables.java index af89e5a28..48deda6bc 100644 --- a/collections/EnvironmentVariables.java +++ b/collections/EnvironmentVariables.java @@ -8,7 +8,7 @@ public class EnvironmentVariables { public static void main(String[] args) { for(Map.Entry entry: System.getenv().entrySet()) { - System.out.println(entry.getKey() + ": " + + System.err.println(entry.getKey() + ": " + entry.getValue()); } } diff --git a/collections/ForInCollections.java b/collections/ForInCollections.java index a8ddd7923..b69912dae 100644 --- a/collections/ForInCollections.java +++ b/collections/ForInCollections.java @@ -11,7 +11,7 @@ public static void main(String[] args) { Collections.addAll(cs, "Take the long way home".split(" ")); for(String s : cs) - System.out.print("'" + s + "' "); + System.err.print("'" + s + "' "); } } /* Output: diff --git a/collections/GenericsAndUpcasting.java b/collections/GenericsAndUpcasting.java index ed8d3f557..93b50b714 100644 --- a/collections/GenericsAndUpcasting.java +++ b/collections/GenericsAndUpcasting.java @@ -17,7 +17,7 @@ public static void main(String[] args) { apples.add(new Fuji()); apples.add(new Braeburn()); for(Apple apple : apples) - System.out.println(apple); + System.err.println(apple); } } /* Output: diff --git a/collections/InterfaceVsIterator.java b/collections/InterfaceVsIterator.java index b5a8663d8..b7a459cbe 100644 --- a/collections/InterfaceVsIterator.java +++ b/collections/InterfaceVsIterator.java @@ -2,21 +2,21 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -import typeinfo.pets.*; +import pets.*; import java.util.*; public class InterfaceVsIterator { public static void display(Iterator it) { while(it.hasNext()) { Pet p = it.next(); - System.out.print(p.id() + ":" + p + " "); + System.err.print(p.id() + ":" + p + " "); } - System.out.println(); + System.err.println(); } public static void display(Collection pets) { for(Pet p : pets) - System.out.print(p.id() + ":" + p + " "); - System.out.println(); + System.err.print(p.id() + ":" + p + " "); + System.err.println(); } public static void main(String[] args) { List petList = Pets.list(8); @@ -30,8 +30,8 @@ public static void main(String[] args) { display(petSet); display(petList.iterator()); display(petSet.iterator()); - System.out.println(petMap); - System.out.println(petMap.keySet()); + System.err.println(petMap); + System.err.println(petMap.keySet()); display(petMap.values()); display(petMap.values().iterator()); } diff --git a/collections/IterableClass.java b/collections/IterableClass.java index 260edc7d4..3ca4bc19c 100644 --- a/collections/IterableClass.java +++ b/collections/IterableClass.java @@ -27,7 +27,7 @@ public void remove() { // Not implemented } public static void main(String[] args) { for(String s : new IterableClass()) - System.out.print(s + " "); + System.err.print(s + " "); } } /* Output: diff --git a/collections/LinkedListFeatures.java b/collections/LinkedListFeatures.java index 3c10ff4ea..e2882ab7d 100644 --- a/collections/LinkedListFeatures.java +++ b/collections/LinkedListFeatures.java @@ -2,38 +2,55 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -import typeinfo.pets.*; +import pets.*; import java.util.*; public class LinkedListFeatures { public static void main(String[] args) { LinkedList pets = new LinkedList<>(Pets.list(5)); - System.out.println(pets); - // Identical: - System.out.println( + System.err.println(pets); + +/*-----------------------------------------------------------------------------------------------------------------------------------*/ + + // Identical: self-note: getFirst() 和 element() 是相同的,它们都返回列表的头部(第一个元素)而并不删除它, + // 如果 List 为空,则抛出 NoSuchElementException 异常。 + System.err.println( "pets.getFirst(): " + pets.getFirst()); - System.out.println( + System.err.println( "pets.element(): " + pets.element()); - // Only differs in empty-list behavior: - System.out.println("pets.peek(): " + pets.peek()); - // Identical; remove and return the first element: - System.out.println( + // Only differs in empty-list behavior: peek() 方法与这两个方法只是稍有差异,它在列表为空时返回 null 。 + System.err.println("pets.peek(): " + pets.peek()); + +/*-----------------------------------------------------------------------------------------------------------------------------------*/ + + // Identical; remove and return the first element: 如果 List 为空,则抛出 NoSuchElementException 异常。 + System.err.println( "pets.remove(): " + pets.remove()); - System.out.println( + System.err.println( "pets.removeFirst(): " + pets.removeFirst()); - // Only differs in empty-list behavior: - System.out.println("pets.poll(): " + pets.poll()); - System.out.println(pets); + // Only differs in empty-list behavior: 它在列表为空时返回 null 。 + System.err.println("pets.poll(): " + pets.poll()); + System.err.println(pets); + +/*-----------------------------------------------------------------------------------------------------------------------------------*/ + + /*在列表的开头插入一个元素。*/ pets.addFirst(new Rat()); - System.out.println("After addFirst(): " + pets); + System.err.println("After addFirst(): " + pets); + + + /*offer() 与 add() 和 addLast() 相同。 它们都在列表的尾部(末尾)添加一个元素。*/ pets.offer(Pets.get()); - System.out.println("After offer(): " + pets); + System.err.println("After offer(): " + pets); pets.add(Pets.get()); - System.out.println("After add(): " + pets); + System.err.println("After add(): " + pets); pets.addLast(new Hamster()); - System.out.println("After addLast(): " + pets); - System.out.println( + System.err.println("After addLast(): " + pets); + + + /*删除并返回列表的最后一个元素。*/ + System.err.println( "pets.removeLast(): " + pets.removeLast()); } } diff --git a/collections/ListFeatures.java b/collections/ListFeatures.java index b4ee16ab4..a6c9266b2 100644 --- a/collections/ListFeatures.java +++ b/collections/ListFeatures.java @@ -2,64 +2,65 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -import typeinfo.pets.*; +import pets.*; import java.util.*; public class ListFeatures { public static void main(String[] args) { Random rand = new Random(47); List pets = Pets.list(7); - System.out.println("1: " + pets); + System.err.println("1: " + pets); Hamster h = new Hamster(); pets.add(h); // Automatically resizes - System.out.println("2: " + pets); - System.out.println("3: " + pets.contains(h)); + System.err.println("2: " + pets); + System.err.println("3: " + pets.contains(h)); pets.remove(h); // Remove by object Pet p = pets.get(2); - System.out.println( + System.err.println( "4: " + p + " " + pets.indexOf(p)); Pet cymric = new Cymric(); - System.out.println("5: " + pets.indexOf(cymric)); - System.out.println("6: " + pets.remove(cymric)); + System.err.println("5: " + pets.indexOf(cymric)); + System.err.println("6: " + pets.remove(cymric)); // Must be the exact object: - System.out.println("7: " + pets.remove(p)); - System.out.println("8: " + pets); + System.err.println("7: " + pets.remove(p)); + System.err.println("8: " + pets); pets.add(3, new Mouse()); // Insert at an index - System.out.println("9: " + pets); + System.err.println("9: " + pets); List sub = pets.subList(1, 4); - System.out.println("subList: " + sub); - System.out.println("10: " + pets.containsAll(sub)); + System.err.println("subList: " + sub); + System.err.println("10: " + pets.containsAll(sub)); Collections.sort(sub); // In-place sort - System.out.println("sorted subList: " + sub); + System.err.println("sorted subList: " + sub); // Order is not important in containsAll(): - System.out.println("11: " + pets.containsAll(sub)); + System.err.println("11: " + pets.containsAll(sub)); Collections.shuffle(sub, rand); // Mix it up - System.out.println("shuffled subList: " + sub); - System.out.println("12: " + pets.containsAll(sub)); + System.err.println("shuffled subList: " + sub); + System.err.println("12: " + pets.containsAll(sub)); List copy = new ArrayList<>(pets); sub = Arrays.asList(pets.get(1), pets.get(4)); - System.out.println("sub: " + sub); + System.err.println("sub: " + sub); copy.retainAll(sub); - System.out.println("13: " + copy); + System.err.println("13: " + copy); copy = new ArrayList<>(pets); // Get a fresh copy - copy.remove(2); // Remove by index - System.out.println("14: " + copy); + copy.remove(6); // Remove by index + System.err.println("14: " + copy); + System.err.println("current sub--->"+sub); copy.removeAll(sub); // Only removes exact objects - System.out.println("15: " + copy); + System.err.println("15: " + copy); copy.set(1, new Mouse()); // Replace an element - System.out.println("16: " + copy); + System.err.println("16: " + copy); copy.addAll(2, sub); // Insert a list in the middle - System.out.println("17: " + copy); - System.out.println("18: " + pets.isEmpty()); + System.err.println("17: " + copy); + System.err.println("18: " + pets.isEmpty()); pets.clear(); // Remove all elements - System.out.println("19: " + pets); - System.out.println("20: " + pets.isEmpty()); + System.err.println("19: " + pets); + System.err.println("20: " + pets.isEmpty()); pets.addAll(Pets.list(4)); - System.out.println("21: " + pets); + System.err.println("21: " + pets); Object[] o = pets.toArray(); - System.out.println("22: " + o[3]); + System.err.println("22: " + o[3]); Pet[] pa = pets.toArray(new Pet[0]); - System.out.println("23: " + pa[3].id()); + System.err.println("23: " + pa[3].id()); } } /* Output: @@ -90,4 +91,16 @@ public static void main(String[] args) { 21: [Manx, Cymric, Rat, EgyptianMau] 22: EgyptianMau 23: 14 + +self-note: +需求 list的方法 说明 备注 + +交集 listA.retainAll(listB) 依赖equals listA内容变为listA和listB都存在的对象 listB不变 + + +差集 listA.removeAll(listB) 依赖equals listA中存在的listB的内容去重 listB不变 + + +并集 listA.removeAll(listB) + listA.addAll(listB) 为了去重,listA先取差集,然后追加全部的listB listB不变 */ diff --git a/collections/ListIteration.java b/collections/ListIteration.java index 95d2786cc..2e45d0af7 100644 --- a/collections/ListIteration.java +++ b/collections/ListIteration.java @@ -2,7 +2,7 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -import typeinfo.pets.*; +import pets.*; import java.util.*; public class ListIteration { @@ -10,21 +10,22 @@ public static void main(String[] args) { List pets = Pets.list(8); ListIterator it = pets.listIterator(); while(it.hasNext()) - System.out.print(it.next() + + System.err.print(it.next() + ", " + it.nextIndex() + ", " + it.previousIndex() + "; "); - System.out.println(); + System.err.println(); // Backwards: while(it.hasPrevious()) - System.out.print(it.previous().id() + " "); - System.out.println(); - System.out.println(pets); + System.err.print(it.previous().id() + " "); + System.err.println(); + System.err.println("TOTAL_1:"+pets); it = pets.listIterator(3); while(it.hasNext()) { - it.next(); - it.set(Pets.get()); +// ; + System.err.println(it.next() ); + it.set(Pets.get());//self-note: 使用 set() 方法可以替换它访问过的最近一个元素。 } - System.out.println(pets); + System.err.println("TOTAL_2:"+pets); } } /* Output: @@ -32,6 +33,5 @@ public static void main(String[] args) { 5, 4; Cymric, 6, 5; Pug, 7, 6; Manx, 8, 7; 7 6 5 4 3 2 1 0 [Rat, Manx, Cymric, Mutt, Pug, Cymric, Pug, Manx] -[Rat, Manx, Cymric, Cymric, Rat, EgyptianMau, Hamster, -EgyptianMau] +[Rat, Manx, Cymric, Cymric, Rat, EgyptianMau, Hamster, EgyptianMau] */ diff --git a/collections/MapOfList.java b/collections/MapOfList.java index 3a985dd9f..fd98ccaad 100644 --- a/collections/MapOfList.java +++ b/collections/MapOfList.java @@ -4,7 +4,7 @@ // Visit http://OnJava8.com for more book information. // {java collections.MapOfList} package collections; -import typeinfo.pets.*; +import pets.*; import java.util.*; public class MapOfList { @@ -30,12 +30,12 @@ public class MapOfList { Arrays.asList(new Rat("Freckly"))); } public static void main(String[] args) { - System.out.println("People: " + petPeople.keySet()); - System.out.println("Pets: " + petPeople.values()); + System.err.println("People: " + petPeople.keySet()); + System.err.println("Pets: " + petPeople.values()); for(Person person : petPeople.keySet()) { - System.out.println(person + " has:"); + System.err.println(person + " has:"); for(Pet pet : petPeople.get(person)) - System.out.println(" " + pet); + System.err.println(" " + pet); } } } diff --git a/collections/ModifyingArraysAsList.java b/collections/ModifyingArraysAsList.java index fea3da423..76a6f3e84 100644 --- a/collections/ModifyingArraysAsList.java +++ b/collections/ModifyingArraysAsList.java @@ -8,18 +8,17 @@ public class ModifyingArraysAsList { public static void main(String[] args) { Random rand = new Random(47); Integer[] ia = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; - List list1 = - new ArrayList<>(Arrays.asList(ia)); - System.out.println("Before shuffling: " + list1); + List list1 = new ArrayList<>(Arrays.asList(ia)); + System.err.println("Before shuffling: " + list1); Collections.shuffle(list1, rand); - System.out.println("After shuffling: " + list1); - System.out.println("array: " + Arrays.toString(ia)); + System.err.println("After shuffling: " + list1); + System.err.println("array: " + Arrays.toString(ia)); List list2 = Arrays.asList(ia); - System.out.println("Before shuffling: " + list2); + System.err.println("Before shuffling: " + list2); Collections.shuffle(list2, rand); - System.out.println("After shuffling: " + list2); - System.out.println("array: " + Arrays.toString(ia)); + System.err.println("After shuffling: " + list2); + System.err.println("array: " + Arrays.toString(ia)); } } /* Output: diff --git a/collections/MultiIterableClass.java b/collections/MultiIterableClass.java index 1d7376e5f..f2c6c82fc 100644 --- a/collections/MultiIterableClass.java +++ b/collections/MultiIterableClass.java @@ -37,13 +37,13 @@ public Iterator iterator() { public static void main(String[] args) { MultiIterableClass mic = new MultiIterableClass(); for(String s : mic.reversed()) - System.out.print(s + " "); - System.out.println(); + System.err.print(s + " "); + System.err.println(); for(String s : mic.randomized()) - System.out.print(s + " "); - System.out.println(); + System.err.print(s + " "); + System.err.println(); for(String s : mic) - System.out.print(s + " "); + System.err.print(s + " "); } } /* Output: diff --git a/collections/NonCollectionSequence.java b/collections/NonCollectionSequence.java index ed1ae6f63..f9fbcde8c 100644 --- a/collections/NonCollectionSequence.java +++ b/collections/NonCollectionSequence.java @@ -2,7 +2,7 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -import typeinfo.pets.*; +import pets.*; import java.util.*; class PetSequence { diff --git a/collections/PetMap.java b/collections/PetMap.java index 18d02ef0b..a5a073f7f 100644 --- a/collections/PetMap.java +++ b/collections/PetMap.java @@ -2,7 +2,7 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -import typeinfo.pets.*; +import pets.*; import java.util.*; public class PetMap { @@ -11,11 +11,11 @@ public static void main(String[] args) { petMap.put("My Cat", new Cat("Molly")); petMap.put("My Dog", new Dog("Ginger")); petMap.put("My Hamster", new Hamster("Bosco")); - System.out.println(petMap); + System.err.println(petMap); Pet dog = petMap.get("My Dog"); - System.out.println(dog); - System.out.println(petMap.containsKey("My Dog")); - System.out.println(petMap.containsValue(dog)); + System.err.println(dog); + System.err.println(petMap.containsKey("My Dog")); + System.err.println(petMap.containsValue(dog)); } } /* Output: diff --git a/collections/PrintingCollections.java b/collections/PrintingCollections.java index c5746fc3e..0f7a97b1e 100644 --- a/collections/PrintingCollections.java +++ b/collections/PrintingCollections.java @@ -22,14 +22,14 @@ static Map fill(Map map) { return map; } public static void main(String[] args) { - System.out.println(fill(new ArrayList<>())); - System.out.println(fill(new LinkedList<>())); - System.out.println(fill(new HashSet<>())); - System.out.println(fill(new TreeSet<>())); - System.out.println(fill(new LinkedHashSet<>())); - System.out.println(fill(new HashMap<>())); - System.out.println(fill(new TreeMap<>())); - System.out.println(fill(new LinkedHashMap<>())); + System.err.println(fill(new ArrayList<>())); + System.err.println(fill(new LinkedList<>())); + System.err.println(fill(new HashSet<>())); + System.err.println(fill(new TreeSet<>())); + System.err.println(fill(new LinkedHashSet<>())); + System.err.println(fill(new HashMap<>())); + System.err.println(fill(new TreeMap<>())); + System.err.println(fill(new LinkedHashMap<>())); } } /* Output: diff --git a/collections/PriorityQueueDemo.java b/collections/PriorityQueueDemo.java index 4f71ab0e8..2b1b09fc4 100644 --- a/collections/PriorityQueueDemo.java +++ b/collections/PriorityQueueDemo.java @@ -6,39 +6,34 @@ public class PriorityQueueDemo { public static void main(String[] args) { - PriorityQueue priorityQueue = - new PriorityQueue<>(); + PriorityQueue priorityQueue = new PriorityQueue<>(); Random rand = new Random(47); for(int i = 0; i < 10; i++) priorityQueue.offer(rand.nextInt(i + 10)); - QueueDemo.printQ(priorityQueue); + System.err.println("一"); QueueDemo.printQ(priorityQueue); - List ints = Arrays.asList(25, 22, 20, - 18, 14, 9, 3, 1, 1, 2, 3, 9, 14, 18, 21, 23, 25); + List ints = Arrays.asList(25, 22, 20, 18, 14, 9, 3, 1, 1, 2, 3, 9, 14, 18, 21, 23, 25); priorityQueue = new PriorityQueue<>(ints); - QueueDemo.printQ(priorityQueue); - priorityQueue = new PriorityQueue<>( - ints.size(), Collections.reverseOrder()); + System.err.println("二");QueueDemo.printQ(priorityQueue); + + priorityQueue = new PriorityQueue<>(ints.size(), Collections.reverseOrder()); priorityQueue.addAll(ints); - QueueDemo.printQ(priorityQueue); + System.err.println("三");QueueDemo.printQ(priorityQueue); String fact = "EDUCATION SHOULD ESCHEW OBFUSCATION"; - List strings = - Arrays.asList(fact.split("")); - PriorityQueue stringPQ = - new PriorityQueue<>(strings); - QueueDemo.printQ(stringPQ); - stringPQ = new PriorityQueue<>( - strings.size(), Collections.reverseOrder()); + List strings = Arrays.asList(fact.split("")); + PriorityQueue stringPQ = new PriorityQueue<>(strings); + System.err.println("四");QueueDemo.printQ(stringPQ); + + stringPQ = new PriorityQueue<>(strings.size(), Collections.reverseOrder()); stringPQ.addAll(strings); - QueueDemo.printQ(stringPQ); + System.err.println("五");QueueDemo.printQ(stringPQ); Set charSet = new HashSet<>(); for(char c : fact.toCharArray()) charSet.add(c); // Autoboxing - PriorityQueue characterPQ = - new PriorityQueue<>(charSet); - QueueDemo.printQ(characterPQ); + PriorityQueue characterPQ = new PriorityQueue<>(charSet); + System.err.println("六"); QueueDemo.printQ(characterPQ); } } /* Output: diff --git a/collections/QueueDemo.java b/collections/QueueDemo.java index f807e89a9..088c31da0 100644 --- a/collections/QueueDemo.java +++ b/collections/QueueDemo.java @@ -8,8 +8,8 @@ public class QueueDemo { public static void printQ(Queue queue) { while(queue.peek() != null) - System.out.print(queue.remove() + " "); - System.out.println(); + System.err.print(queue.remove() + " "); + System.err.println(); } public static void main(String[] args) { Queue queue = new LinkedList<>(); @@ -21,6 +21,8 @@ public static void main(String[] args) { for(char c : "Brontosaurus".toCharArray()) qc.offer(c); printQ(qc); + + } } /* Output: diff --git a/collections/SetOfInteger.java b/collections/SetOfInteger.java index 78157d5cd..fc4ac8147 100644 --- a/collections/SetOfInteger.java +++ b/collections/SetOfInteger.java @@ -8,9 +8,15 @@ public class SetOfInteger { public static void main(String[] args) { Random rand = new Random(47); Set intset = new HashSet<>(); - for(int i = 0; i < 10000; i++) + int i = 0; + for(; i < 10000; i++) { intset.add(rand.nextInt(30)); - System.out.println(intset); + if (intset.size()==30) { + break; + } + } + System.err.println("i="+i); + System.err.println(intset); } } /* Output: diff --git a/collections/SetOfString.java b/collections/SetOfString.java index 01d9455e6..a8fea07c1 100644 --- a/collections/SetOfString.java +++ b/collections/SetOfString.java @@ -17,7 +17,7 @@ public static void main(String[] args) { colors.add("Blue"); colors.add("Purple"); } - System.out.println(colors); + System.err.println(colors); } } /* Output: diff --git a/collections/SetOperations.java b/collections/SetOperations.java index f716f9651..7eb7ef65e 100644 --- a/collections/SetOperations.java +++ b/collections/SetOperations.java @@ -10,22 +10,31 @@ public static void main(String[] args) { Collections.addAll(set1, "A B C D E F G H I J K L".split(" ")); set1.add("M"); - System.out.println("H: " + set1.contains("H")); - System.out.println("N: " + set1.contains("N")); + System.err.println("H: " + set1.contains("H")); + System.err.println("N: " + set1.contains("N")); Set set2 = new HashSet<>(); + Collections.addAll(set2, "H I J K L".split(" ")); - System.out.println( + System.err.println("set1: " + set1); + System.err.println("set2: " + set2); + + System.err.println( "set2 in set1: " + set1.containsAll(set2)); set1.remove("H"); - System.out.println("set1: " + set1); - System.out.println( + System.err.println("------after remove 'H'---------------------"); + System.err.println("set1: " + set1); + System.err.println( "set2 in set1: " + set1.containsAll(set2)); + System.err.println(); + set1.removeAll(set2); - System.out.println( + System.err.println( "set2 removed from set1: " + set1); + Collections.addAll(set1, "X Y Z".split(" ")); - System.out.println( + System.err.println( "'X Y Z' added to set1: " + set1); + } } /* Output: @@ -35,6 +44,5 @@ public static void main(String[] args) { set1: [A, B, C, D, E, F, G, I, J, K, L, M] set2 in set1: false set2 removed from set1: [A, B, C, D, E, F, G, M] -'X Y Z' added to set1: [A, B, C, D, E, F, G, M, X, Y, -Z] +'X Y Z' added to set1: [A, B, C, D, E, F, G, M, X, Y, Z] */ diff --git a/collections/SimpleCollection.java b/collections/SimpleCollection.java index 8915e2591..cc6852e17 100644 --- a/collections/SimpleCollection.java +++ b/collections/SimpleCollection.java @@ -10,7 +10,7 @@ public static void main(String[] args) { for(int i = 0; i < 10; i++) c.add(i); // Autoboxing for(Integer i : c) - System.out.print(i + ", "); + System.err.print(i + ", "); } } /* Output: diff --git a/collections/SimpleIteration.java b/collections/SimpleIteration.java index a65a2a714..dd08e56a2 100644 --- a/collections/SimpleIteration.java +++ b/collections/SimpleIteration.java @@ -2,7 +2,7 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -import typeinfo.pets.*; +import pets.*; import java.util.*; public class SimpleIteration { @@ -11,20 +11,20 @@ public static void main(String[] args) { Iterator it = pets.iterator(); while(it.hasNext()) { Pet p = it.next(); - System.out.print(p.id() + ":" + p + " "); + System.err.print(p.id() + ":" + p + " "); } - System.out.println(); + System.err.println(); // A simpler approach, when possible: for(Pet p : pets) - System.out.print(p.id() + ":" + p + " "); - System.out.println(); + System.err.print(p.id() + ":" + p + " "); + System.err.println(); // An Iterator can also remove elements: it = pets.iterator(); for(int i = 0; i < 6; i++) { it.next(); it.remove(); } - System.out.println(pets); + System.err.println(pets); } } /* Output: diff --git a/collections/SortedSetOfString.java b/collections/SortedSetOfString.java index a043b7911..c1103b3ae 100644 --- a/collections/SortedSetOfString.java +++ b/collections/SortedSetOfString.java @@ -17,7 +17,7 @@ public static void main(String[] args) { colors.add("Blue"); colors.add("Purple"); } - System.out.println(colors); + System.err.println(colors); } } /* Output: diff --git a/collections/StackCollision.java b/collections/StackCollision.java index 67ee4d907..c32eba39d 100644 --- a/collections/StackCollision.java +++ b/collections/StackCollision.java @@ -9,14 +9,14 @@ public static void main(String[] args) { for(String s : "My dog has fleas".split(" ")) stack.push(s); while(!stack.isEmpty()) - System.out.print(stack.pop() + " "); - System.out.println(); + System.err.print(stack.pop() + " "); + System.err.println(); java.util.Stack stack2 = new java.util.Stack<>(); for(String s : "My dog has fleas".split(" ")) stack2.push(s); while(!stack2.empty()) - System.out.print(stack2.pop() + " "); + System.err.print(stack2.pop() + " "); } } /* Output: diff --git a/collections/StackTest.java b/collections/StackTest.java index dc1663cc4..9954eb534 100644 --- a/collections/StackTest.java +++ b/collections/StackTest.java @@ -10,7 +10,7 @@ public static void main(String[] args) { for(String s : "My dog has fleas".split(" ")) stack.push(s); while(!stack.isEmpty()) - System.out.print(stack.pop() + " "); + System.err.print(stack.pop() + " "); } } /* Output: diff --git a/collections/StackTest2.java b/collections/StackTest2.java index 2464d7a9c..7291ef6fc 100644 --- a/collections/StackTest2.java +++ b/collections/StackTest2.java @@ -2,17 +2,24 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -import onjava.*; +import onjava.Stack; public class StackTest2 { public static void main(String[] args) { - Stack stack = new Stack<>(); +// onjava.Stack stack = new onjava.Stack<>();//fun1 完整指定包名 import onjava.*; + Stack stack = new Stack<>(); //fun2 完整指定包名 import onjava.Stack; + + for(String s : "My dog has fleas".split(" ")) stack.push(s); while(!stack.isEmpty()) - System.out.print(stack.pop() + " "); + System.err.print(stack.pop() + " "); } } /* Output: fleas has dog My + +self-note: +如果想在自己的代码中使用这个 Stack 类,当在创建其实例时,就需要完整指定包名,或者更改这个类的名称; +否则,就有可能会与 java.util 包中的 Stack 发生冲突。 */ diff --git a/collections/Statistics.java b/collections/Statistics.java index f888db585..065d61306 100644 --- a/collections/Statistics.java +++ b/collections/Statistics.java @@ -15,7 +15,7 @@ public static void main(String[] args) { Integer freq = m.get(r); // [1] m.put(r, freq == null ? 1 : freq + 1); } - System.out.println(m); + System.err.println(m); } } /* Output: diff --git a/collections/UniqueWords.java b/collections/UniqueWords.java index c6c3681d4..407c3229b 100644 --- a/collections/UniqueWords.java +++ b/collections/UniqueWords.java @@ -15,7 +15,7 @@ public class UniqueWords { for(String word : line.split("\\W+")) if(word.trim().length() > 0) words.add(word); - System.out.println(words); + System.err.println(words); } } /* Output: diff --git a/collections/UniqueWordsAlphabetic.java b/collections/UniqueWordsAlphabetic.java index 66a7fecfa..a5fab06ea 100644 --- a/collections/UniqueWordsAlphabetic.java +++ b/collections/UniqueWordsAlphabetic.java @@ -17,7 +17,7 @@ public class UniqueWordsAlphabetic { for(String word : line.split("\\W+")) if(word.trim().length() > 0) words.add(word); - System.out.println(words); + System.err.println(words); } } /* Output: diff --git a/collections/onjava/Stack.java b/collections/onjava/Stack.java new file mode 100644 index 000000000..d7663f653 --- /dev/null +++ b/collections/onjava/Stack.java @@ -0,0 +1,21 @@ +package onjava;// onjava/Stack.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// A Stack class built with an ArrayDeque +//package onjava; + +import java.util.ArrayDeque; +import java.util.Deque; + +public class Stack { + private Deque storage = new ArrayDeque<>(); + public void push(T v) { storage.push(v); } + public T peek() { return storage.peek(); } + public T pop() { return storage.pop(); } + public boolean isEmpty() { return storage.isEmpty(); } + @Override + public String toString() { + return storage.toString(); + } +} diff --git a/collections/pets/Cat.java b/collections/pets/Cat.java new file mode 100644 index 000000000..386eb78e9 --- /dev/null +++ b/collections/pets/Cat.java @@ -0,0 +1,10 @@ +// typeinfo/pets/Cat.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +package pets; + +public class Cat extends Pet { + public Cat(String name) { super(name); } + public Cat() { super(); } +} diff --git a/collections/pets/Cymric.java b/collections/pets/Cymric.java new file mode 100644 index 000000000..d5259f18d --- /dev/null +++ b/collections/pets/Cymric.java @@ -0,0 +1,10 @@ +// typeinfo/pets/Cymric.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +package pets; + +public class Cymric extends Manx { + public Cymric(String name) { super(name); } + public Cymric() { super(); } +} diff --git a/collections/pets/Dog.java b/collections/pets/Dog.java new file mode 100644 index 000000000..4c5ddbbcd --- /dev/null +++ b/collections/pets/Dog.java @@ -0,0 +1,10 @@ +// typeinfo/pets/Dog.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +package pets; + +public class Dog extends Pet { + public Dog(String name) { super(name); } + public Dog() { super(); } +} diff --git a/collections/pets/EgyptianMau.java b/collections/pets/EgyptianMau.java new file mode 100644 index 000000000..d68bfeffc --- /dev/null +++ b/collections/pets/EgyptianMau.java @@ -0,0 +1,10 @@ +// typeinfo/pets/EgyptianMau.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +package pets; + +public class EgyptianMau extends Cat { + public EgyptianMau(String name) { super(name); } + public EgyptianMau() { super(); } +} diff --git a/collections/pets/ForNameCreator.java b/collections/pets/ForNameCreator.java new file mode 100644 index 000000000..54a879b08 --- /dev/null +++ b/collections/pets/ForNameCreator.java @@ -0,0 +1,39 @@ +// typeinfo/pets/ForNameCreator.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +package pets; + +import java.util.ArrayList; +import java.util.List; + +public class ForNameCreator extends PetCreator { + private static List> types = + new ArrayList<>(); + // Types you want randomly created: + private static String[] typeNames = { + "typeinfo.pets.Mutt", + "typeinfo.pets.Pug", + "typeinfo.pets.EgyptianMau", + "typeinfo.pets.Manx", + "typeinfo.pets.Cymric", + "typeinfo.pets.Rat", + "typeinfo.pets.Mouse", + "typeinfo.pets.Hamster" + }; + @SuppressWarnings("unchecked") + private static void loader() { + try { + for(String name : typeNames) + types.add( + (Class)Class.forName(name)); + } catch(ClassNotFoundException e) { + throw new RuntimeException(e); + } + } + static { loader(); } + @Override + public List> types() { + return types; + } +} diff --git a/collections/pets/Hamster.java b/collections/pets/Hamster.java new file mode 100644 index 000000000..fc2d08f67 --- /dev/null +++ b/collections/pets/Hamster.java @@ -0,0 +1,10 @@ +// typeinfo/pets/Hamster.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +package pets; + +public class Hamster extends Rodent { + public Hamster(String name) { super(name); } + public Hamster() { super(); } +} diff --git a/collections/pets/Individual.java b/collections/pets/Individual.java new file mode 100644 index 000000000..71e1cf017 --- /dev/null +++ b/collections/pets/Individual.java @@ -0,0 +1,47 @@ +// typeinfo/pets/Individual.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +package pets; + +import java.util.Objects; + +public class +Individual implements Comparable { + private static long counter = 0; + private final long id = counter++; + private String name; + public Individual(String name) { this.name = name; } + // 'name' is optional: + public Individual() {} + @Override + public String toString() { + return getClass().getSimpleName() + + (name == null ? "" : " " + name); + } + public long id() { return id; } + @Override + public boolean equals(Object o) { + return o instanceof Individual && + Objects.equals(id, ((Individual)o).id); + } + @Override + public int hashCode() { + return Objects.hash(name, id); + } + @Override + public int compareTo(Individual arg) { + // Compare by class name first: + String first = getClass().getSimpleName(); + String argFirst = arg.getClass().getSimpleName(); + int firstCompare = first.compareTo(argFirst); + if(firstCompare != 0) + return firstCompare; + if(name != null && arg.name != null) { + int secondCompare = name.compareTo(arg.name); + if(secondCompare != 0) + return secondCompare; + } + return (arg.id < id ? -1 : (arg.id == id ? 0 : 1)); + } +} diff --git a/collections/pets/LiteralPetCreator.java b/collections/pets/LiteralPetCreator.java new file mode 100644 index 000000000..30e27c2c5 --- /dev/null +++ b/collections/pets/LiteralPetCreator.java @@ -0,0 +1,42 @@ +// typeinfo/pets/LiteralPetCreator.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// Using class literals +// {java typeinfo.pets.LiteralPetCreator} +package pets; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +public class LiteralPetCreator extends PetCreator { + // No try block needed. + @SuppressWarnings("unchecked") + public static + final List> ALL_TYPES = + Collections.unmodifiableList(Arrays.asList( + Pet.class, Dog.class, Cat.class, Rodent.class, + Mutt.class, Pug.class, EgyptianMau.class, + Manx.class, Cymric.class, Rat.class, + Mouse.class, Hamster.class)); + // Types for random creation: + private static final + List> TYPES = + ALL_TYPES.subList(ALL_TYPES.indexOf(Mutt.class), + ALL_TYPES.size()); + @Override + public List> types() { + return TYPES; + } + public static void main(String[] args) { + System.err.println(TYPES); + } +} +/* Output: +[class typeinfo.pets.Mutt, class typeinfo.pets.Pug, +class typeinfo.pets.EgyptianMau, class +typeinfo.pets.Manx, class typeinfo.pets.Cymric, class +typeinfo.pets.Rat, class typeinfo.pets.Mouse, class +typeinfo.pets.Hamster] +*/ diff --git a/collections/pets/Manx.java b/collections/pets/Manx.java new file mode 100644 index 000000000..d1c273d28 --- /dev/null +++ b/collections/pets/Manx.java @@ -0,0 +1,10 @@ +// typeinfo/pets/Manx.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +package pets; + +public class Manx extends Cat { + public Manx(String name) { super(name); } + public Manx() { super(); } +} diff --git a/collections/pets/Mouse.java b/collections/pets/Mouse.java new file mode 100644 index 000000000..6a85070d4 --- /dev/null +++ b/collections/pets/Mouse.java @@ -0,0 +1,10 @@ +// typeinfo/pets/Mouse.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +package pets; + +public class Mouse extends Rodent { + public Mouse(String name) { super(name); } + public Mouse() { super(); } +} diff --git a/collections/pets/Mutt.java b/collections/pets/Mutt.java new file mode 100644 index 000000000..d48d93760 --- /dev/null +++ b/collections/pets/Mutt.java @@ -0,0 +1,10 @@ +// typeinfo/pets/Mutt.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +package pets; + +public class Mutt extends Dog { + public Mutt(String name) { super(name); } + public Mutt() { super(); } +} diff --git a/collections/pets/Person.java b/collections/pets/Person.java new file mode 100644 index 000000000..f16624c69 --- /dev/null +++ b/collections/pets/Person.java @@ -0,0 +1,9 @@ +// typeinfo/pets/Person.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +package pets; + +public class Person extends Individual { + public Person(String name) { super(name); } +} diff --git a/collections/pets/Pet.java b/collections/pets/Pet.java new file mode 100644 index 000000000..f56288ded --- /dev/null +++ b/collections/pets/Pet.java @@ -0,0 +1,10 @@ +// typeinfo/pets/Pet.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +package pets; + +public class Pet extends Individual { + public Pet(String name) { super(name); } + public Pet() { super(); } +} diff --git a/collections/pets/PetCreator.java b/collections/pets/PetCreator.java new file mode 100644 index 000000000..911d62d12 --- /dev/null +++ b/collections/pets/PetCreator.java @@ -0,0 +1,30 @@ +// typeinfo/pets/PetCreator.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// Creates random sequences of Pets +package pets; + +import java.lang.reflect.InvocationTargetException; +import java.util.List; +import java.util.Random; +import java.util.function.Supplier; + +public abstract +class PetCreator implements Supplier { + private Random rand = new Random(47); + // The List of the different types of Pet to create: + public abstract List> types(); + public Pet get() { // Create one random Pet + int n = rand.nextInt(types().size()); + try { + return types().get(n) + .getConstructor().newInstance(); + } catch(InstantiationException | + NoSuchMethodException | + InvocationTargetException | + IllegalAccessException e) { + throw new RuntimeException(e); + } + } +} diff --git a/collections/pets/Pets.java b/collections/pets/Pets.java new file mode 100644 index 000000000..d88fba670 --- /dev/null +++ b/collections/pets/Pets.java @@ -0,0 +1,33 @@ +// typeinfo/pets/Pets.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// Facade to produce a default PetCreator +package pets; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.stream.Stream; + +public class Pets { + public static final PetCreator CREATOR = + new LiteralPetCreator(); + public static Pet get() { + return CREATOR.get(); + } + public static Pet[] array(int size) { + Pet[] result = new Pet[size]; + for(int i = 0; i < size; i++) + result[i] = CREATOR.get(); + return result; + } + public static List list(int size) { + List result = new ArrayList<>(); + Collections.addAll(result, array(size)); + return result; + } + public static Stream stream() { + return Stream.generate(CREATOR); + } +} diff --git a/collections/pets/Pug.java b/collections/pets/Pug.java new file mode 100644 index 000000000..cdd7c6620 --- /dev/null +++ b/collections/pets/Pug.java @@ -0,0 +1,10 @@ +// typeinfo/pets/Pug.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +package pets; + +public class Pug extends Dog { + public Pug(String name) { super(name); } + public Pug() { super(); } +} diff --git a/collections/pets/Rat.java b/collections/pets/Rat.java new file mode 100644 index 000000000..d46d3f8b7 --- /dev/null +++ b/collections/pets/Rat.java @@ -0,0 +1,10 @@ +// typeinfo/pets/Rat.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +package pets; + +public class Rat extends Rodent { + public Rat(String name) { super(name); } + public Rat() { super(); } +} diff --git a/collections/pets/Rodent.java b/collections/pets/Rodent.java new file mode 100644 index 000000000..fb0cfa9f2 --- /dev/null +++ b/collections/pets/Rodent.java @@ -0,0 +1,10 @@ +// typeinfo/pets/Rodent.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +package pets; + +public class Rodent extends Pet { + public Rodent(String name) { super(name); } + public Rodent() { super(); } +} diff --git a/collectiontopics/AssociativeArray.java b/collectiontopics/AssociativeArray.java index e7488489c..5b8458eb7 100644 --- a/collectiontopics/AssociativeArray.java +++ b/collectiontopics/AssociativeArray.java @@ -46,10 +46,10 @@ public static void main(String[] args) { try { map.put("extra", "object"); // Past the end } catch(ArrayIndexOutOfBoundsException e) { - System.out.println("Too many objects!"); + System.err.println("Too many objects!"); } - System.out.println(map); - System.out.println(map.get("ocean")); + System.err.println(map); + System.err.println(map.get("ocean")); } } /* Output: diff --git a/collectiontopics/Bits.java b/collectiontopics/Bits.java index 16afb3617..69ba5440b 100644 --- a/collectiontopics/Bits.java +++ b/collectiontopics/Bits.java @@ -7,11 +7,11 @@ public class Bits { public static void printBitSet(BitSet b) { - System.out.println("bits: " + b); + System.err.println("bits: " + b); StringBuilder bbits = new StringBuilder(); for(int j = 0; j < b.size() ; j++) bbits.append(b.get(j) ? "1" : "0"); - System.out.println("bit pattern: " + bbits); + System.err.println("bit pattern: " + bbits); } public static void main(String[] args) { Random rand = new Random(47); @@ -23,7 +23,7 @@ public static void main(String[] args) { bb.set(i); else bb.clear(i); - System.out.println("byte value: " + bt); + System.err.println("byte value: " + bt); printBitSet(bb); short st = (short)rand.nextInt(); @@ -33,7 +33,7 @@ public static void main(String[] args) { bs.set(i); else bs.clear(i); - System.out.println("short value: " + st); + System.err.println("short value: " + st); printBitSet(bs); int it = rand.nextInt(); @@ -43,20 +43,20 @@ public static void main(String[] args) { bi.set(i); else bi.clear(i); - System.out.println("int value: " + it); + System.err.println("int value: " + it); printBitSet(bi); // Test bitsets >= 64 bits: BitSet b127 = new BitSet(); b127.set(127); - System.out.println("set bit 127: " + b127); + System.err.println("set bit 127: " + b127); BitSet b255 = new BitSet(65); b255.set(255); - System.out.println("set bit 255: " + b255); + System.err.println("set bit 255: " + b255); BitSet b1023 = new BitSet(512); b1023.set(1023); b1023.set(1024); - System.out.println("set bit 1023: " + b1023); + System.err.println("set bit 1023: " + b1023); } } /* Output: diff --git a/collectiontopics/CanonicalMapping.java b/collectiontopics/CanonicalMapping.java index c02f9132a..ff85b0027 100644 --- a/collectiontopics/CanonicalMapping.java +++ b/collectiontopics/CanonicalMapping.java @@ -22,7 +22,7 @@ public boolean equals(Object r) { @SuppressWarnings("deprecation") @Override protected void finalize() { - System.out.println("Finalizing " + + System.err.println("Finalizing " + getClass().getSimpleName() + " " + ident); } } diff --git a/collectiontopics/CollectionMethods.java b/collectiontopics/CollectionMethods.java index e32e5982a..b009b79db 100644 --- a/collectiontopics/CollectionMethods.java +++ b/collectiontopics/CollectionMethods.java @@ -21,9 +21,9 @@ public static void main(String[] args) { // Find max and min elements; this means // different things depending on the way // the Comparable interface is implemented: - System.out.println( + System.err.println( "Collections.max(c) = " + Collections.max(c)); - System.out.println( + System.err.println( "Collections.min(c) = " + Collections.min(c)); border(); // Add a Collection to another Collection @@ -45,10 +45,10 @@ public static void main(String[] args) { border(); // Is an element in this Collection? String val = LIST.get(3); - System.out.println( + System.err.println( "c.contains(" + val + ") = " + c.contains(val)); // Is a Collection in this Collection? - System.out.println( + System.err.println( "c.containsAll(c2) = " + c.containsAll(c2)); Collection c3 = ((List)c).subList(3, 5); @@ -59,7 +59,7 @@ public static void main(String[] args) { // Throw away all the elements // in c2 that also appear in c3: c2.removeAll(c3); - System.out.println( + System.err.println( "c2.isEmpty() = " + c2.isEmpty()); border(); // Functional operation: @@ -69,7 +69,7 @@ public static void main(String[] args) { // Stream operation: c.stream().forEach(System.out::println); c.clear(); // Remove all elements - System.out.println("after c.clear():" + c); + System.err.println("after c.clear():" + c); } } /* Output: diff --git a/collectiontopics/Enumerations.java b/collectiontopics/Enumerations.java index 22b83e52a..36bd8d523 100644 --- a/collectiontopics/Enumerations.java +++ b/collectiontopics/Enumerations.java @@ -12,7 +12,7 @@ public static void main(String[] args) { new Vector<>(Countries.names(10)); Enumeration e = v.elements(); while(e.hasMoreElements()) - System.out.print(e.nextElement() + ", "); + System.err.print(e.nextElement() + ", "); // Produce an Enumeration from a Collection: e = Collections.enumeration(new ArrayList<>()); } diff --git a/collectiontopics/FailFast.java b/collectiontopics/FailFast.java index 0b0ce253f..871061432 100644 --- a/collectiontopics/FailFast.java +++ b/collectiontopics/FailFast.java @@ -13,7 +13,7 @@ public static void main(String[] args) { try { String s = it.next(); } catch(ConcurrentModificationException e) { - System.out.println(e); + System.err.println(e); } } } diff --git a/collectiontopics/FillMapTest.java b/collectiontopics/FillMapTest.java index 5cfd612bc..9a9d04275 100644 --- a/collectiontopics/FillMapTest.java +++ b/collectiontopics/FillMapTest.java @@ -11,15 +11,15 @@ public class FillMapTest { public static void main(String[] args) { Map mcs = FillMap.basic( new Rand.String(4), new Count.Integer(), 7); - System.out.println(mcs); + System.err.println(mcs); HashMap hashm = FillMap.create(new Rand.String(4), new Count.Integer(), HashMap::new, 7); - System.out.println(hashm); + System.err.println(hashm); LinkedHashMap linkm = FillMap.create(new Rand.String(4), new Count.Integer(), LinkedHashMap::new, 7); - System.out.println(linkm); + System.err.println(linkm); } } /* Output: diff --git a/collectiontopics/FillingLists.java b/collectiontopics/FillingLists.java index 32bdb8ef0..f68ea0398 100644 --- a/collectiontopics/FillingLists.java +++ b/collectiontopics/FillingLists.java @@ -19,10 +19,10 @@ public static void main(String[] args) { List list = new ArrayList<>( Collections.nCopies(4, new StringAddress("Hello"))); - System.out.println(list); + System.err.println(list); Collections.fill(list, new StringAddress("World!")); - System.out.println(list); + System.err.println(list); } } /* Output: diff --git a/collectiontopics/LinkedHashMapDemo.java b/collectiontopics/LinkedHashMapDemo.java index d0b933932..a9b7c15b0 100644 --- a/collectiontopics/LinkedHashMapDemo.java +++ b/collectiontopics/LinkedHashMapDemo.java @@ -10,17 +10,17 @@ public class LinkedHashMapDemo { public static void main(String[] args) { LinkedHashMap linkedMap = new LinkedHashMap<>(new CountMap(9)); - System.out.println(linkedMap); + System.err.println(linkedMap); // Least-recently-used order: linkedMap = new LinkedHashMap<>(16, 0.75f, true); linkedMap.putAll(new CountMap(9)); - System.out.println(linkedMap); + System.err.println(linkedMap); for(int i = 0; i < 6; i++) linkedMap.get(i); - System.out.println(linkedMap); + System.err.println(linkedMap); linkedMap.get(0); - System.out.println(linkedMap); + System.err.println(linkedMap); } } /* Output: diff --git a/collectiontopics/ListOps.java b/collectiontopics/ListOps.java index 824ffba98..e11c2169f 100644 --- a/collectiontopics/ListOps.java +++ b/collectiontopics/ListOps.java @@ -67,48 +67,48 @@ public static void iterManipulation(List a) { it.set("47"); } public static void testVisual(List a) { - System.out.println(a); + System.err.println(a); List b = LIST; - System.out.println("b = " + b); + System.err.println("b = " + b); a.addAll(b); a.addAll(b); - System.out.println(a); + System.err.println(a); // Insert, remove, and replace elements // using a ListIterator: ListIterator x = a.listIterator(a.size()/2); x.add("one"); - System.out.println(a); - System.out.println(x.next()); + System.err.println(a); + System.err.println(x.next()); x.remove(); - System.out.println(x.next()); + System.err.println(x.next()); x.set("47"); - System.out.println(a); + System.err.println(a); // Traverse the list backwards: x = a.listIterator(a.size()); while(x.hasPrevious()) - System.out.print(x.previous() + " "); - System.out.println(); - System.out.println("testVisual finished"); + System.err.print(x.previous() + " "); + System.err.println(); + System.err.println("testVisual finished"); } // There are some things that only LinkedLists can do: public static void testLinkedList() { LinkedList ll = new LinkedList<>(); ll.addAll(LIST); - System.out.println(ll); + System.err.println(ll); // Treat it like a stack, pushing: ll.addFirst("one"); ll.addFirst("two"); - System.out.println(ll); + System.err.println(ll); // Like "peeking" at the top of a stack: - System.out.println(ll.getFirst()); + System.err.println(ll.getFirst()); // Like popping a stack: - System.out.println(ll.removeFirst()); - System.out.println(ll.removeFirst()); + System.err.println(ll.removeFirst()); + System.err.println(ll.removeFirst()); // Treat it like a queue, pulling elements // off the tail end: - System.out.println(ll.removeLast()); - System.out.println(ll); + System.err.println(ll.removeLast()); + System.err.println(ll); } public static void main(String[] args) { // Make and fill a new list each time: diff --git a/collectiontopics/ListSortSearch.java b/collectiontopics/ListSortSearch.java index 4d1fbcf8c..1e1965235 100644 --- a/collectiontopics/ListSortSearch.java +++ b/collectiontopics/ListSortSearch.java @@ -10,32 +10,32 @@ public static void main(String[] args) { List list = new ArrayList<>(Utilities.list); list.addAll(Utilities.list); - System.out.println(list); + System.err.println(list); Collections.shuffle(list, new Random(47)); - System.out.println("Shuffled: " + list); + System.err.println("Shuffled: " + list); // Use ListIterator to trim off last elements: ListIterator it = list.listIterator(10); while(it.hasNext()) { it.next(); it.remove(); } - System.out.println("Trimmed: " + list); + System.err.println("Trimmed: " + list); Collections.sort(list); - System.out.println("Sorted: " + list); + System.err.println("Sorted: " + list); String key = list.get(7); int index = Collections.binarySearch(list, key); - System.out.println( + System.err.println( "Location of " + key + " is " + index + ", list.get(" + index + ") = " + list.get(index)); Collections.sort(list, String.CASE_INSENSITIVE_ORDER); - System.out.println( + System.err.println( "Case-insensitive sorted: " + list); key = list.get(7); index = Collections.binarySearch(list, key, String.CASE_INSENSITIVE_ORDER); - System.out.println( + System.err.println( "Location of " + key + " is " + index + ", list.get(" + index + ") = " + list.get(index)); diff --git a/collectiontopics/MapOps.java b/collectiontopics/MapOps.java index b214fa2d6..c7e08ad56 100644 --- a/collectiontopics/MapOps.java +++ b/collectiontopics/MapOps.java @@ -10,40 +10,40 @@ public class MapOps { public static void printKeys(Map map) { - System.out.print("Size = " + map.size() + ", "); - System.out.print("Keys: "); + System.err.print("Size = " + map.size() + ", "); + System.err.print("Keys: "); // Produce a Set of the keys: - System.out.println(map.keySet()); + System.err.println(map.keySet()); } public static void test(Map map) { - System.out.println( + System.err.println( map.getClass().getSimpleName()); map.putAll(new CountMap(25)); // Map has 'Set' behavior for keys: map.putAll(new CountMap(25)); printKeys(map); // Producing a Collection of the values: - System.out.print("Values: "); - System.out.println(map.values()); - System.out.println(map); - System.out.println("map.containsKey(11): " + + System.err.print("Values: "); + System.err.println(map.values()); + System.err.println(map); + System.err.println("map.containsKey(11): " + map.containsKey(11)); - System.out.println( + System.err.println( "map.get(11): " + map.get(11)); - System.out.println("map.containsValue(\"F0\"): " + System.err.println("map.containsValue(\"F0\"): " + map.containsValue("F0")); Integer key = map.keySet().iterator().next(); - System.out.println("First key in map: " + key); + System.err.println("First key in map: " + key); map.remove(key); printKeys(map); map.clear(); - System.out.println( + System.err.println( "map.isEmpty(): " + map.isEmpty()); map.putAll(new CountMap(25)); // Operations on the Set change the Map: map.keySet().removeAll(map.keySet()); - System.out.println( + System.err.println( "map.isEmpty(): " + map.isEmpty()); } public static void main(String[] args) { diff --git a/collectiontopics/QueueBehavior.java b/collectiontopics/QueueBehavior.java index 136fbaf8a..63b5ed323 100644 --- a/collectiontopics/QueueBehavior.java +++ b/collectiontopics/QueueBehavior.java @@ -14,11 +14,11 @@ static Stream strings() { "eight nine ten").split(" ")); } static void test(int id, Queue queue) { - System.out.print(id + ": "); + System.err.print(id + ": "); strings().map(queue::offer).count(); while(queue.peek() != null) - System.out.print(queue.remove() + " "); - System.out.println(); + System.err.print(queue.remove() + " "); + System.err.println(); } public static void main(String[] args) { int count = 10; diff --git a/collectiontopics/ReadOnly.java b/collectiontopics/ReadOnly.java index 93c336c4f..a1dc945f3 100644 --- a/collectiontopics/ReadOnly.java +++ b/collectiontopics/ReadOnly.java @@ -13,18 +13,18 @@ public static void main(String[] args) { Collection c = Collections.unmodifiableCollection( new ArrayList<>(data)); - System.out.println(c); // Reading is OK + System.err.println(c); // Reading is OK //- c.add("one"); // Can't change it List a = Collections.unmodifiableList( new ArrayList<>(data)); ListIterator lit = a.listIterator(); - System.out.println(lit.next()); // Reading is OK + System.err.println(lit.next()); // Reading is OK //- lit.add("one"); // Can't change it Set s = Collections.unmodifiableSet( new HashSet<>(data)); - System.out.println(s); // Reading is OK + System.err.println(s); // Reading is OK //- s.add("one"); // Can't change it // For a SortedSet: @@ -35,7 +35,7 @@ public static void main(String[] args) { Map m = Collections.unmodifiableMap( new HashMap<>(Countries.capitals(6))); - System.out.println(m); // Reading is OK + System.err.println(m); // Reading is OK //- m.put("Ralph", "Howdy!"); // For a SortedMap: diff --git a/collectiontopics/References.java b/collectiontopics/References.java index 5fcca9404..47e55fb93 100644 --- a/collectiontopics/References.java +++ b/collectiontopics/References.java @@ -16,7 +16,7 @@ class VeryBig { @SuppressWarnings("deprecation") @Override protected void finalize() { - System.out.println("Finalizing " + ident); + System.err.println("Finalizing " + ident); } } @@ -26,7 +26,7 @@ public class References { public static void checkQueue() { Reference inq = rq.poll(); if(inq != null) - System.out.println("In queue: " + inq.get()); + System.err.println("In queue: " + inq.get()); } public static void main(String[] args) { int size = 10; @@ -38,7 +38,7 @@ public static void main(String[] args) { for(int i = 0; i < size; i++) { sa.add(new SoftReference<>( new VeryBig("Soft " + i), rq)); - System.out.println( + System.err.println( "Just created: " + sa.getLast()); checkQueue(); } @@ -47,7 +47,7 @@ public static void main(String[] args) { for(int i = 0; i < size; i++) { wa.add(new WeakReference<>( new VeryBig("Weak " + i), rq)); - System.out.println( + System.err.println( "Just created: " + wa.getLast()); checkQueue(); } @@ -61,7 +61,7 @@ public static void main(String[] args) { for(int i = 0; i < size; i++) { pa.add(new PhantomReference<>( new VeryBig("Phantom " + i), rq)); - System.out.println( + System.err.println( "Just created: " + pa.getLast()); checkQueue(); } diff --git a/collectiontopics/SetOrder.java b/collectiontopics/SetOrder.java index 1c25be238..4a7dc7a4a 100644 --- a/collectiontopics/SetOrder.java +++ b/collectiontopics/SetOrder.java @@ -21,7 +21,7 @@ public class SetOrder { public static void main(String[] args) throws Exception { for(String type: sets) { - System.out.format("[-> %s <-]%n", + System.err.format("[-> %s <-]%n", type.substring(type.lastIndexOf('.') + 1)); @SuppressWarnings({"unchecked", "deprecation"}) Set set = (Set) diff --git a/collectiontopics/SimpleDeques.java b/collectiontopics/SimpleDeques.java index fbb4a5ff6..e7f82c1c9 100644 --- a/collectiontopics/SimpleDeques.java +++ b/collectiontopics/SimpleDeques.java @@ -25,25 +25,25 @@ static void test(Deque deque) { deque.offerFirst(s1.get()); deque.offerLast(s2.get()); // Same as offer() } - System.out.println(deque); + System.err.println(deque); String result = ""; while(deque.size() > 0) { - System.out.print(deque.peekFirst() + " "); + System.err.print(deque.peekFirst() + " "); result += deque.pollFirst() + " "; - System.out.print(deque.peekLast() + " "); + System.err.print(deque.peekLast() + " "); result += deque.pollLast() + " "; } - System.out.println("\n" + result); + System.err.println("\n" + result); } public static void main(String[] args) { int count = 10; - System.out.println("LinkedList"); + System.err.println("LinkedList"); test(new LinkedList<>()); - System.out.println("ArrayDeque"); + System.err.println("ArrayDeque"); test(new ArrayDeque<>()); - System.out.println("LinkedBlockingDeque"); + System.err.println("LinkedBlockingDeque"); test(new LinkedBlockingDeque<>(count)); - System.out.println("ConcurrentLinkedDeque"); + System.err.println("ConcurrentLinkedDeque"); test(new ConcurrentLinkedDeque<>()); } } diff --git a/collectiontopics/SortedMapDemo.java b/collectiontopics/SortedMapDemo.java index 4d57d34a7..e1f87c4c8 100644 --- a/collectiontopics/SortedMapDemo.java +++ b/collectiontopics/SortedMapDemo.java @@ -10,11 +10,11 @@ public class SortedMapDemo { public static void main(String[] args) { TreeMap sortedMap = new TreeMap<>(new CountMap(10)); - System.out.println(sortedMap); + System.err.println(sortedMap); Integer low = sortedMap.firstKey(); Integer high = sortedMap.lastKey(); - System.out.println(low); - System.out.println(high); + System.err.println(low); + System.err.println(high); Iterator it = sortedMap.keySet().iterator(); for(int i = 0; i <= 6; i++) { @@ -22,11 +22,11 @@ public static void main(String[] args) { if(i == 6) high = it.next(); else it.next(); } - System.out.println(low); - System.out.println(high); - System.out.println(sortedMap.subMap(low, high)); - System.out.println(sortedMap.headMap(high)); - System.out.println(sortedMap.tailMap(low)); + System.err.println(low); + System.err.println(high); + System.err.println(sortedMap.subMap(low, high)); + System.err.println(sortedMap.headMap(high)); + System.err.println(sortedMap.tailMap(low)); } } /* Output: diff --git a/collectiontopics/SortedSetDemo.java b/collectiontopics/SortedSetDemo.java index 6ed81fb16..92a5d1783 100644 --- a/collectiontopics/SortedSetDemo.java +++ b/collectiontopics/SortedSetDemo.java @@ -12,22 +12,22 @@ public static void main(String[] args) { "one two three four five six seven eight" .split(" ")) .collect(toCollection(TreeSet::new)); - System.out.println(sortedSet); + System.err.println(sortedSet); String low = sortedSet.first(); String high = sortedSet.last(); - System.out.println(low); - System.out.println(high); + System.err.println(low); + System.err.println(high); Iterator it = sortedSet.iterator(); for(int i = 0; i <= 6; i++) { if(i == 3) low = it.next(); if(i == 6) high = it.next(); else it.next(); } - System.out.println(low); - System.out.println(high); - System.out.println(sortedSet.subSet(low, high)); - System.out.println(sortedSet.headSet(high)); - System.out.println(sortedSet.tailSet(low)); + System.err.println(low); + System.err.println(high); + System.err.println(sortedSet.subSet(low, high)); + System.err.println(sortedSet.headSet(high)); + System.err.println(sortedSet.tailSet(low)); } } /* Output: diff --git a/collectiontopics/Stacks.java b/collectiontopics/Stacks.java index 79a684cbb..1ba2f4c66 100644 --- a/collectiontopics/Stacks.java +++ b/collectiontopics/Stacks.java @@ -14,22 +14,22 @@ public static void main(String[] args) { Stack stack = new Stack<>(); for(Month m : Month.values()) stack.push(m.toString()); - System.out.println("stack = " + stack); + System.err.println("stack = " + stack); // Treating a stack as a Vector: stack.addElement("The last line"); - System.out.println( + System.err.println( "element 5 = " + stack.elementAt(5)); - System.out.println("popping elements:"); + System.err.println("popping elements:"); while(!stack.empty()) - System.out.print(stack.pop() + " "); + System.err.print(stack.pop() + " "); // Using a LinkedList as a Stack: LinkedList lstack = new LinkedList<>(); for(Month m : Month.values()) lstack.addFirst(m.toString()); - System.out.println("lstack = " + lstack); + System.err.println("lstack = " + lstack); while(!lstack.isEmpty()) - System.out.print(lstack.removeFirst() + " "); + System.err.print(lstack.removeFirst() + " "); // Using the Stack class from // the Collections Chapter: @@ -37,9 +37,9 @@ public static void main(String[] args) { new onjava.Stack<>(); for(Month m : Month.values()) stack2.push(m.toString()); - System.out.println("stack2 = " + stack2); + System.err.println("stack2 = " + stack2); while(!stack2.isEmpty()) - System.out.print(stack2.pop() + " "); + System.err.print(stack2.pop() + " "); } } diff --git a/collectiontopics/StreamFillMaps.java b/collectiontopics/StreamFillMaps.java index 816a74b31..acb6db89b 100644 --- a/collectiontopics/StreamFillMaps.java +++ b/collectiontopics/StreamFillMaps.java @@ -24,7 +24,7 @@ public static void main(String[] args) { .limit(11) .collect(Collectors .toMap(Pair::key, Pair::value)); - System.out.println(m); + System.err.println(m); // Two separate Suppliers: Rand.String rs = new Rand.String(3); @@ -34,7 +34,7 @@ public static void main(String[] args) { .limit(8) .collect(Collectors .toMap(Pair::key, Pair::value)); - System.out.println(mcs); + System.err.println(mcs); // A key Supplier and a single value: Map mcs2 = Stream.generate( @@ -42,7 +42,7 @@ public static void main(String[] args) { .limit(8) .collect(Collectors .toMap(Pair::key, Pair::value)); - System.out.println(mcs2); + System.err.println(mcs2); } } /* Output: diff --git a/collectiontopics/Suppliers.java b/collectiontopics/Suppliers.java new file mode 100644 index 000000000..4b5b09245 --- /dev/null +++ b/collectiontopics/Suppliers.java @@ -0,0 +1,38 @@ +// onjava/Suppliers.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// A utility to use with Suppliers +//package onjava; + +import java.util.Collection; +import java.util.function.BiConsumer; +import java.util.function.Supplier; +import java.util.stream.Stream; + +public class Suppliers { + // Create a collection and fill it: + public static > C + create(Supplier factory, Supplier gen, int n) { + return Stream.generate(gen) + .limit(n) + .collect(factory, C::add, C::addAll); + } + // Fill an existing collection: + public static > + C fill(C coll, Supplier gen, int n) { + Stream.generate(gen) + .limit(n) + .forEach(coll::add); + return coll; + } + // Use an unbound method reference to + // produce a more general method: + public static H fill(H holder, + BiConsumer adder, Supplier gen, int n) { + Stream.generate(gen) + .limit(n) + .forEach(a -> adder.accept(holder, a)); + return holder; + } +} diff --git a/collectiontopics/SuppliersCollectionTest.java b/collectiontopics/SuppliersCollectionTest.java index b30f1490d..dd1c70078 100644 --- a/collectiontopics/SuppliersCollectionTest.java +++ b/collectiontopics/SuppliersCollectionTest.java @@ -24,29 +24,29 @@ public static void main(String[] args) { // Suppliers class from the Generics chapter: Set set = Suppliers.create( LinkedHashSet::new, new Government(), 15); - System.out.println(set); + System.err.println(set); List list = Suppliers.create( LinkedList::new, new Government(), 15); - System.out.println(list); + System.err.println(list); list = new ArrayList<>(); Suppliers.fill(list, new Government(), 15); - System.out.println(list); + System.err.println(list); // Or we can use Streams: set = Arrays.stream(Government.foundation) .collect(Collectors.toSet()); - System.out.println(set); + System.err.println(set); list = Arrays.stream(Government.foundation) .collect(Collectors.toList()); - System.out.println(list); + System.err.println(list); list = Arrays.stream(Government.foundation) .collect(Collectors .toCollection(LinkedList::new)); - System.out.println(list); + System.err.println(list); set = Arrays.stream(Government.foundation) .collect(Collectors .toCollection(LinkedHashSet::new)); - System.out.println(set); + System.err.println(set); } } /* Output: diff --git a/collectiontopics/ToDoList.java b/collectiontopics/ToDoList.java index b288e8e1e..bab0ed1f0 100644 --- a/collectiontopics/ToDoList.java +++ b/collectiontopics/ToDoList.java @@ -43,7 +43,7 @@ public static void main(String[] args) { toDo.add(new ToDoItem("Water lawn", 'A', 1)); toDo.add(new ToDoItem("Feed cat", 'B', 1)); while(!toDo.isEmpty()) - System.out.println(toDo.remove()); + System.err.println(toDo.remove()); } } /* Output: diff --git a/collectiontopics/TypesForSets.java b/collectiontopics/TypesForSets.java index 9950b0032..59ac0627c 100644 --- a/collectiontopics/TypesForSets.java +++ b/collectiontopics/TypesForSets.java @@ -53,7 +53,7 @@ public class TypesForSets { fill(set, type); fill(set, type); // Try to add duplicates fill(set, type); - System.out.println(set); + System.err.println(set); } public static void main(String[] args) { test(new HashSet<>(), HashType::new); @@ -67,12 +67,12 @@ public static void main(String[] args) { try { test(new TreeSet<>(), SetType::new); } catch(Exception e) { - System.out.println(e.getMessage()); + System.err.println(e.getMessage()); } try { test(new TreeSet<>(), HashType::new); } catch(Exception e) { - System.out.println(e.getMessage()); + System.err.println(e.getMessage()); } } } diff --git a/collectiontopics/Unsupported.java b/collectiontopics/Unsupported.java index a66b1cfdb..da4524f36 100644 --- a/collectiontopics/Unsupported.java +++ b/collectiontopics/Unsupported.java @@ -11,11 +11,11 @@ public class Unsupported { try { tst.run(); } catch(Exception e) { - System.out.println(description + "(): " + e); + System.err.println(description + "(): " + e); } } static void test(String msg, List list) { - System.out.println("--- " + msg + " ---"); + System.err.println("--- " + msg + " ---"); Collection c = list; Collection subList = list.subList(1,8); // Copy of the sublist: diff --git a/collectiontopics/Utilities.java b/collectiontopics/Utilities.java index a2acc4278..8ec8816be 100644 --- a/collectiontopics/Utilities.java +++ b/collectiontopics/Utilities.java @@ -9,48 +9,48 @@ public class Utilities { static List list = Arrays.asList( "one Two three Four five six one".split(" ")); public static void main(String[] args) { - System.out.println(list); - System.out.println("'list' disjoint (Four)?: " + + System.err.println(list); + System.err.println("'list' disjoint (Four)?: " + Collections.disjoint(list, Collections.singletonList("Four"))); - System.out.println( + System.err.println( "max: " + Collections.max(list)); - System.out.println( + System.err.println( "min: " + Collections.min(list)); - System.out.println( + System.err.println( "max w/ comparator: " + Collections.max(list, String.CASE_INSENSITIVE_ORDER)); - System.out.println( + System.err.println( "min w/ comparator: " + Collections.min(list, String.CASE_INSENSITIVE_ORDER)); List sublist = Arrays.asList("Four five six".split(" ")); - System.out.println("indexOfSubList: " + + System.err.println("indexOfSubList: " + Collections.indexOfSubList(list, sublist)); - System.out.println("lastIndexOfSubList: " + + System.err.println("lastIndexOfSubList: " + Collections.lastIndexOfSubList(list, sublist)); Collections.replaceAll(list, "one", "Yo"); - System.out.println("replaceAll: " + list); + System.err.println("replaceAll: " + list); Collections.reverse(list); - System.out.println("reverse: " + list); + System.err.println("reverse: " + list); Collections.rotate(list, 3); - System.out.println("rotate: " + list); + System.err.println("rotate: " + list); List source = Arrays.asList("in the matrix".split(" ")); Collections.copy(list, source); - System.out.println("copy: " + list); + System.err.println("copy: " + list); Collections.swap(list, 0, list.size() - 1); - System.out.println("swap: " + list); + System.err.println("swap: " + list); Collections.shuffle(list, new Random(47)); - System.out.println("shuffled: " + list); + System.err.println("shuffled: " + list); Collections.fill(list, "pop"); - System.out.println("fill: " + list); - System.out.println("frequency of 'pop': " + + System.err.println("fill: " + list); + System.err.println("frequency of 'pop': " + Collections.frequency(list, "pop")); List dups = Collections.nCopies(3, "snap"); - System.out.println("dups: " + dups); - System.out.println("'list' disjoint 'dups'?: " + + System.err.println("dups: " + dups); + System.err.println("'list' disjoint 'dups'?: " + Collections.disjoint(list, dups)); // Getting an old-style Enumeration: Enumeration e = @@ -62,7 +62,7 @@ public static void main(String[] args) { // to a List via an Enumeration: ArrayList arrayList = Collections.list(v.elements()); - System.out.println("arrayList: " + arrayList); + System.err.println("arrayList: " + arrayList); } } /* Output: diff --git a/com/mindviewinc/simple/List.java b/com/mindviewinc/simple/List.java index 84b30315b..15230958c 100644 --- a/com/mindviewinc/simple/List.java +++ b/com/mindviewinc/simple/List.java @@ -7,6 +7,6 @@ public class List { public List() { - System.out.println("com.mindviewinc.simple.List"); + System.err.println("com.mindviewinc.simple.List"); } } diff --git a/com/mindviewinc/simple/Vector.java b/com/mindviewinc/simple/Vector.java index 19824ccec..3ab6ab293 100644 --- a/com/mindviewinc/simple/Vector.java +++ b/com/mindviewinc/simple/Vector.java @@ -7,6 +7,6 @@ public class Vector { public Vector() { - System.out.println("com.mindviewinc.simple.Vector"); + System.err.println("com.mindviewinc.simple.Vector"); } } diff --git a/compression/GZIPcompress.java b/compression/GZIPcompress.java index c9022e780..853c02818 100644 --- a/compression/GZIPcompress.java +++ b/compression/GZIPcompress.java @@ -10,7 +10,7 @@ public class GZIPcompress { public static void main(String[] args) { if(args.length == 0) { - System.out.println( + System.err.println( "Usage: \nGZIPcompress file\n" + "\tUses GZIP compression to compress " + "the file to test.gz"); @@ -24,14 +24,14 @@ public static void main(String[] args) { new GZIPOutputStream( new FileOutputStream("test.gz"))) ) { - System.out.println("Writing file"); + System.err.println("Writing file"); int c; while((c = in.read()) != -1) out.write(c); } catch(IOException e) { throw new RuntimeException(e); } - System.out.println("Reading file"); + System.err.println("Reading file"); try( BufferedReader in2 = new BufferedReader( new InputStreamReader(new GZIPInputStream( diff --git a/compression/ZipCompress.java b/compression/ZipCompress.java index f9ce76705..d4595532d 100644 --- a/compression/ZipCompress.java +++ b/compression/ZipCompress.java @@ -24,7 +24,7 @@ public static void main(String[] args) { zos.setComment("A test of Java Zipping"); // No corresponding getComment(), though. for(String arg : args) { - System.out.println("Writing file " + arg); + System.err.println("Writing file " + arg); try( InputStream in = new BufferedInputStream( new FileInputStream(arg)) @@ -37,13 +37,13 @@ public static void main(String[] args) { out.flush(); } // Checksum valid only after the file is closed! - System.out.println( + System.err.println( "Checksum: " + csum.getChecksum().getValue()); } catch(IOException e) { throw new RuntimeException(e); } // Now extract the files: - System.out.println("Reading file"); + System.err.println("Reading file"); try( FileInputStream fi = new FileInputStream("test.zip"); @@ -55,13 +55,13 @@ public static void main(String[] args) { ) { ZipEntry ze; while((ze = in2.getNextEntry()) != null) { - System.out.println("Reading file " + ze); + System.err.println("Reading file " + ze); int x; while((x = bis.read()) != -1) - System.out.write(x); + System.err.write(x); } if(args.length == 1) - System.out.println( + System.err.println( "Checksum: "+csumi.getChecksum().getValue()); } catch(IOException e) { throw new RuntimeException(e); @@ -73,7 +73,7 @@ public static void main(String[] args) { Enumeration e = zf.entries(); while(e.hasMoreElements()) { ZipEntry ze2 = (ZipEntry)e.nextElement(); - System.out.println("File: " + ze2); + System.err.println("File: " + ze2); // ... and extract the data as before } } catch(IOException e) { diff --git a/concurrent/Breakable.java b/concurrent/Breakable.java index facd70951..a509ad1d5 100644 --- a/concurrent/Breakable.java +++ b/concurrent/Breakable.java @@ -18,12 +18,12 @@ public String toString() { } public static Breakable work(Breakable b) { if(--b.failcount == 0) { - System.out.println( + System.err.println( "Throwing Exception for " + b.id + ""); throw new RuntimeException( "Breakable_" + b.id + " failed"); } - System.out.println(b); + System.err.println(b); return b; } } diff --git a/concurrent/CachedThreadPool3.java b/concurrent/CachedThreadPool3.java index 4b6e6d2e0..043e9e3e6 100644 --- a/concurrent/CachedThreadPool3.java +++ b/concurrent/CachedThreadPool3.java @@ -28,7 +28,7 @@ public static void main(String[] args) Integer sum = futures.stream() .map(CachedThreadPool3::extractResult) .reduce(0, Integer::sum); - System.out.println("sum = " + sum); + System.err.println("sum = " + sum); exec.shutdown(); } } diff --git a/concurrent/CatchCompletableExceptions.java b/concurrent/CatchCompletableExceptions.java index 67451ed46..465c0a12b 100644 --- a/concurrent/CatchCompletableExceptions.java +++ b/concurrent/CatchCompletableExceptions.java @@ -12,11 +12,11 @@ static void handleException(int failcount) { .test("exceptionally", failcount) .exceptionally((ex) -> { // Function if(ex == null) - System.out.println("I don't get it yet"); + System.err.println("I don't get it yet"); return new Breakable(ex.getMessage(), 0); }) .thenAccept(str -> - System.out.println("result: " + str)); + System.err.println("result: " + str)); // Create a new result (recover): CompletableExceptions @@ -28,24 +28,24 @@ static void handleException(int failcount) { return result + " is good"; }) .thenAccept(str -> - System.out.println("result: " + str)); + System.err.println("result: " + str)); // Do something but pass the same result through: CompletableExceptions .test("whenComplete", failcount) .whenComplete((result, fail) -> { // BiConsumer if(fail != null) - System.out.println("It failed"); + System.err.println("It failed"); else - System.out.println(result + " OK"); + System.err.println(result + " OK"); }) .thenAccept(r -> - System.out.println("result: " + r)); + System.err.println("result: " + r)); } public static void main(String[] args) { - System.out.println("**** Failure Mode ****"); + System.err.println("**** Failure Mode ****"); handleException(2); - System.out.println("**** Success Mode ****"); + System.err.println("**** Success Mode ****"); handleException(0); } } diff --git a/concurrent/CollectionIntoStream.java b/concurrent/CollectionIntoStream.java index 2dc51a7e0..1725e8af1 100644 --- a/concurrent/CollectionIntoStream.java +++ b/concurrent/CollectionIntoStream.java @@ -18,7 +18,7 @@ public static void main(String[] args) { .map(String::toUpperCase) .map(s -> s.substring(2)) .reduce(":", (s1, s2) -> s1 + s2); - System.out.println(result); + System.err.println(result); } } /* Output: diff --git a/concurrent/CompletableApplyAsync.java b/concurrent/CompletableApplyAsync.java index fa7c92711..5a1195102 100644 --- a/concurrent/CompletableApplyAsync.java +++ b/concurrent/CompletableApplyAsync.java @@ -15,9 +15,9 @@ public static void main(String[] args) { .thenApplyAsync(Machina::work) .thenApplyAsync(Machina::work) .thenApplyAsync(Machina::work); - System.out.println(timer.duration()); - System.out.println(cf.join()); - System.out.println(timer.duration()); + System.err.println(timer.duration()); + System.err.println(cf.join()); + System.err.println(timer.duration()); } } /* Output: diff --git a/concurrent/CompletableApplyChained.java b/concurrent/CompletableApplyChained.java index aa6828d56..59abf5131 100644 --- a/concurrent/CompletableApplyChained.java +++ b/concurrent/CompletableApplyChained.java @@ -15,7 +15,7 @@ public static void main(String[] args) { .thenApply(Machina::work) .thenApply(Machina::work) .thenApply(Machina::work); - System.out.println(timer.duration()); + System.err.println(timer.duration()); } } /* Output: diff --git a/concurrent/CompletableExceptions.java b/concurrent/CompletableExceptions.java index 624815d5f..61cd59d55 100644 --- a/concurrent/CompletableExceptions.java +++ b/concurrent/CompletableExceptions.java @@ -26,23 +26,23 @@ public static void main(String[] args) { try { test("F", 2).get(); // or join() } catch(Exception e) { - System.out.println(e.getMessage()); + System.err.println(e.getMessage()); } // Test for exceptions: - System.out.println( + System.err.println( test("G", 2).isCompletedExceptionally()); // Counts as "done": - System.out.println(test("H", 2).isDone()); + System.err.println(test("H", 2).isDone()); // Force an exception: CompletableFuture cfi = new CompletableFuture<>(); - System.out.println("done? " + cfi.isDone()); + System.err.println("done? " + cfi.isDone()); cfi.completeExceptionally( new RuntimeException("forced")); try { cfi.get(); } catch(Exception e) { - System.out.println(e.getMessage()); + System.err.println(e.getMessage()); } } } diff --git a/concurrent/CompletableOperations.java b/concurrent/CompletableOperations.java index d03e8422a..ae756fc5f 100644 --- a/concurrent/CompletableOperations.java +++ b/concurrent/CompletableOperations.java @@ -14,14 +14,14 @@ static CompletableFuture cfi(int i) { public static void main(String[] args) { showr(cfi(1)); // Basic test voidr(cfi(2).runAsync(() -> - System.out.println("runAsync"))); + System.err.println("runAsync"))); voidr(cfi(3).thenRunAsync(() -> - System.out.println("thenRunAsync"))); + System.err.println("thenRunAsync"))); voidr(CompletableFuture.runAsync(() -> - System.out.println("runAsync is static"))); + System.err.println("runAsync is static"))); showr(CompletableFuture.supplyAsync(() -> 99)); voidr(cfi(4).thenAcceptAsync(i -> - System.out.println("thenAcceptAsync: " + i))); + System.err.println("thenAcceptAsync: " + i))); showr(cfi(5).thenApplyAsync(i -> i + 42)); showr(cfi(6).thenComposeAsync(i -> cfi(i + 99))); CompletableFuture c = cfi(7); @@ -33,21 +33,21 @@ public static void main(String[] args) { showr(c); c = new CompletableFuture<>(); c.cancel(true); - System.out.println("cancelled: " + + System.err.println("cancelled: " + c.isCancelled()); - System.out.println("completed exceptionally: " + + System.err.println("completed exceptionally: " + c.isCompletedExceptionally()); - System.out.println("done: " + c.isDone()); - System.out.println(c); + System.err.println("done: " + c.isDone()); + System.err.println(c); c = new CompletableFuture<>(); - System.out.println(c.getNow(777)); + System.err.println(c.getNow(777)); c = new CompletableFuture<>(); c.thenApplyAsync(i -> i + 42) .thenApplyAsync(i -> i * 12); - System.out.println("dependents: " + + System.err.println("dependents: " + c.getNumberOfDependents()); c.thenApplyAsync(i -> i / 2); - System.out.println("dependents: " + + System.err.println("dependents: " + c.getNumberOfDependents()); } } diff --git a/concurrent/CompletablePizza.java b/concurrent/CompletablePizza.java index 97b68545f..ba6cda44c 100644 --- a/concurrent/CompletablePizza.java +++ b/concurrent/CompletablePizza.java @@ -24,7 +24,7 @@ public class CompletablePizza { public static void show(CompletableFuture cf) { try { - System.out.println(cf.get()); + System.err.println(cf.get()); } catch(Exception e) { throw new RuntimeException(e); } @@ -36,9 +36,9 @@ public static void main(String[] args) { .mapToObj(Pizza::new) .map(CompletablePizza::makeCF) .collect(Collectors.toList()); - System.out.println(timer.duration()); + System.err.println(timer.duration()); pizzas.forEach(CompletablePizza::show); - System.out.println(timer.duration()); + System.err.println(timer.duration()); } } /* Output: diff --git a/concurrent/CompletableUtilities.java b/concurrent/CompletableUtilities.java index 8f3a0e51a..226b9fb99 100644 --- a/concurrent/CompletableUtilities.java +++ b/concurrent/CompletableUtilities.java @@ -9,7 +9,7 @@ public class CompletableUtilities { // Get and show value stored in a CF: public static void showr(CompletableFuture c) { try { - System.out.println(c.get()); + System.err.println(c.get()); } catch(InterruptedException | ExecutionException e) { throw new RuntimeException(e); diff --git a/concurrent/CountingStream.java b/concurrent/CountingStream.java index 4cebb24e1..694f49761 100644 --- a/concurrent/CountingStream.java +++ b/concurrent/CountingStream.java @@ -9,7 +9,7 @@ public class CountingStream { public static void main(String[] args) { - System.out.println( + System.err.println( IntStream.range(0, 10) .parallel() .mapToObj(CountingTask::new) diff --git a/concurrent/CountingTask.java b/concurrent/CountingTask.java index b1fb7b89f..71fbc163c 100644 --- a/concurrent/CountingTask.java +++ b/concurrent/CountingTask.java @@ -12,7 +12,7 @@ public Integer call() { Integer val = 0; for(int i = 0; i < 100; i++) val++; - System.out.println(id + " " + + System.err.println(id + " " + Thread.currentThread().getName() + " " + val); return val; } diff --git a/concurrent/DualCompletableOperations.java b/concurrent/DualCompletableOperations.java index 420523121..e5233c593 100644 --- a/concurrent/DualCompletableOperations.java +++ b/concurrent/DualCompletableOperations.java @@ -14,42 +14,42 @@ static void init() { static void join() { cfA.join(); cfB.join(); - System.out.println("*****************"); + System.err.println("*****************"); } public static void main(String[] args) { init(); voidr(cfA.runAfterEitherAsync(cfB, () -> - System.out.println("runAfterEither"))); + System.err.println("runAfterEither"))); join(); init(); voidr(cfA.runAfterBothAsync(cfB, () -> - System.out.println("runAfterBoth"))); + System.err.println("runAfterBoth"))); join(); init(); showr(cfA.applyToEitherAsync(cfB, w -> { - System.out.println("applyToEither: " + w); + System.err.println("applyToEither: " + w); return w; })); join(); init(); voidr(cfA.acceptEitherAsync(cfB, w -> { - System.out.println("acceptEither: " + w); + System.err.println("acceptEither: " + w); })); join(); init(); voidr(cfA.thenAcceptBothAsync(cfB, (w1, w2) -> { - System.out.println("thenAcceptBoth: " + System.err.println("thenAcceptBoth: " + w1 + ", " + w2); })); join(); init(); showr(cfA.thenCombineAsync(cfB, (w1, w2) -> { - System.out.println("thenCombine: " + System.err.println("thenCombine: " + w1 + ", " + w2); return w1; })); @@ -61,7 +61,7 @@ public static void main(String[] args) { cfD = Workable.make("D", 0.09); CompletableFuture.anyOf(cfA, cfB, cfC, cfD) .thenRunAsync(() -> - System.out.println("anyOf")); + System.err.println("anyOf")); join(); init(); @@ -69,7 +69,7 @@ public static void main(String[] args) { cfD = Workable.make("D", 0.09); CompletableFuture.allOf(cfA, cfB, cfC, cfD) .thenRunAsync(() -> - System.out.println("allOf")); + System.err.println("allOf")); join(); } } diff --git a/concurrent/Futures.java b/concurrent/Futures.java index 888e7f0d9..6255202ff 100644 --- a/concurrent/Futures.java +++ b/concurrent/Futures.java @@ -13,7 +13,7 @@ public static void main(String[] args) Executors.newSingleThreadExecutor(); Future f = exec.submit(new CountingTask(99)); - System.out.println(f.get()); // [1] + System.err.println(f.get()); // [1] exec.shutdown(); } } diff --git a/concurrent/IDChecker.java b/concurrent/IDChecker.java index 845c9e6a4..3f98bb904 100644 --- a/concurrent/IDChecker.java +++ b/concurrent/IDChecker.java @@ -32,7 +32,7 @@ public static void test(Supplier gen) { groupB = CompletableFuture .supplyAsync(new MakeObjects(gen)); groupA.thenAcceptBoth(groupB, (a, b) -> { - System.out.println( + System.err.println( Sets.intersection( Sets.newHashSet(a), Sets.newHashSet(b)).size()); diff --git a/concurrent/InterferingTask.java b/concurrent/InterferingTask.java index da08f6539..e11b6183e 100644 --- a/concurrent/InterferingTask.java +++ b/concurrent/InterferingTask.java @@ -11,7 +11,7 @@ public class InterferingTask implements Runnable { public void run() { for(int i = 0; i < 100; i++) val++; - System.out.println(id + " " + + System.err.println(id + " " + Thread.currentThread().getName() + " " + val); } } diff --git a/concurrent/LambdasAndMethodReferences.java b/concurrent/LambdasAndMethodReferences.java index 10552499a..fe57e8c08 100644 --- a/concurrent/LambdasAndMethodReferences.java +++ b/concurrent/LambdasAndMethodReferences.java @@ -6,13 +6,13 @@ class NotRunnable { public void go() { - System.out.println("NotRunnable"); + System.err.println("NotRunnable"); } } class NotCallable { public Integer get() { - System.out.println("NotCallable"); + System.err.println("NotCallable"); return 1; } } @@ -22,10 +22,10 @@ public static void main(String[] args) throws InterruptedException { ExecutorService exec = Executors.newCachedThreadPool(); - exec.submit(() -> System.out.println("Lambda1")); + exec.submit(() -> System.err.println("Lambda1")); exec.submit(new NotRunnable()::go); exec.submit(() -> { - System.out.println("Lambda2"); + System.err.println("Lambda2"); return 1; }); exec.submit(new NotCallable()::get); diff --git a/concurrent/Machina.java b/concurrent/Machina.java index e70cd2b4c..7ed761dc4 100644 --- a/concurrent/Machina.java +++ b/concurrent/Machina.java @@ -20,7 +20,7 @@ public static Machina work(Machina m) { new Nap(0.1); m.state = m.state.step(); } - System.out.println(m); + System.err.println(m); return m; } @Override diff --git a/concurrent/MoreTasksAfterShutdown.java b/concurrent/MoreTasksAfterShutdown.java index 28b96af83..b90d83c95 100644 --- a/concurrent/MoreTasksAfterShutdown.java +++ b/concurrent/MoreTasksAfterShutdown.java @@ -13,7 +13,7 @@ public static void main(String[] args) { try { exec.execute(new NapTask(99)); } catch(RejectedExecutionException e) { - System.out.println(e); + System.err.println(e); } } } diff --git a/concurrent/NapTask.java b/concurrent/NapTask.java index 92df6b602..63d96b11b 100644 --- a/concurrent/NapTask.java +++ b/concurrent/NapTask.java @@ -10,7 +10,7 @@ public class NapTask implements Runnable { @Override public void run() { new Nap(0.1); // Seconds - System.out.println(this + " " + + System.err.println(this + " " + Thread.currentThread().getName()); } @Override diff --git a/concurrent/OnePizza.java b/concurrent/OnePizza.java index f4f27249f..11613f642 100644 --- a/concurrent/OnePizza.java +++ b/concurrent/OnePizza.java @@ -7,7 +7,7 @@ public class OnePizza { public static void main(String[] args) { Pizza za = new Pizza(0); - System.out.println( + System.err.println( Timer.duration(() -> { while(!za.complete()) za.next(); diff --git a/concurrent/ParallelPrime.java b/concurrent/ParallelPrime.java index 97c025756..758ff1a7d 100644 --- a/concurrent/ParallelPrime.java +++ b/concurrent/ParallelPrime.java @@ -25,7 +25,7 @@ public static void main(String[] args) .limit(COUNT) .mapToObj(Long::toString) .collect(Collectors.toList()); - System.out.println(timer.duration()); + System.err.println(timer.duration()); Files.write(Paths.get("primes.txt"), primes, StandardOpenOption.CREATE); } diff --git a/concurrent/ParallelStreamPuzzle.java b/concurrent/ParallelStreamPuzzle.java index f57dec24a..a324cf34b 100644 --- a/concurrent/ParallelStreamPuzzle.java +++ b/concurrent/ParallelStreamPuzzle.java @@ -20,7 +20,7 @@ public static void main(String[] args) { .limit(10) .parallel() // [1] .collect(Collectors.toList()); - System.out.println(x); + System.err.println(x); } } /* Output: diff --git a/concurrent/ParallelStreamPuzzle2.java b/concurrent/ParallelStreamPuzzle2.java index 2fc11d482..2cd1e3ca2 100644 --- a/concurrent/ParallelStreamPuzzle2.java +++ b/concurrent/ParallelStreamPuzzle2.java @@ -29,7 +29,7 @@ public Integer get() { .limit(10) .parallel() .collect(Collectors.toList()); - System.out.println(x); + System.err.println(x); Files.write(Paths.get("PSP2.txt"), trace); } } diff --git a/concurrent/ParallelStreamPuzzle3.java b/concurrent/ParallelStreamPuzzle3.java index 757bddd5b..8b77261b0 100644 --- a/concurrent/ParallelStreamPuzzle3.java +++ b/concurrent/ParallelStreamPuzzle3.java @@ -9,13 +9,13 @@ public class ParallelStreamPuzzle3 { public static void main(String[] args) { List x = IntStream.range(0, 30) - .peek(e -> System.out.println(e + ": " + + .peek(e -> System.err.println(e + ": " + Thread.currentThread().getName())) .limit(10) .parallel() .boxed() .collect(Collectors.toList()); - System.out.println(x); + System.err.println(x); } } /* Output: diff --git a/concurrent/Philosopher.java b/concurrent/Philosopher.java index 48facb382..272e3db86 100644 --- a/concurrent/Philosopher.java +++ b/concurrent/Philosopher.java @@ -19,10 +19,10 @@ public String toString() { @Override public void run() { while(true) { - // System.out.println("Thinking"); // [1] + // System.err.println("Thinking"); // [1] right.pickUp(); left.pickUp(); - System.out.println(this + " eating"); + System.err.println(this + " eating"); right.putDown(); left.putDown(); } diff --git a/concurrent/Pizza.java b/concurrent/Pizza.java index 8cd5ff30b..d4801de80 100644 --- a/concurrent/Pizza.java +++ b/concurrent/Pizza.java @@ -22,7 +22,7 @@ Step forward() { public Pizza(int id) { this.id = id; } public Pizza next() { step = step.forward(); - System.out.println("Pizza " + id + ": " + step); + System.err.println("Pizza " + id + ": " + step); return this; } public Pizza next(Step previousStep) { diff --git a/concurrent/PizzaParallelSteps.java b/concurrent/PizzaParallelSteps.java index 605e99853..ec32c49a0 100644 --- a/concurrent/PizzaParallelSteps.java +++ b/concurrent/PizzaParallelSteps.java @@ -20,8 +20,8 @@ public static void main(String[] args) { .map(Pizza::bake) .map(Pizza::slice) .map(Pizza::box) - .forEach(za -> System.out.println(za)); - System.out.println(timer.duration()); + .forEach(za -> System.err.println(za)); + System.err.println(timer.duration()); } } /* Output: diff --git a/concurrent/PizzaStreams.java b/concurrent/PizzaStreams.java index 16be983a7..2b20f0881 100644 --- a/concurrent/PizzaStreams.java +++ b/concurrent/PizzaStreams.java @@ -17,7 +17,7 @@ public static void main(String[] args) { while(!za.complete()) za.next(); }); - System.out.println(timer.duration()); + System.err.println(timer.duration()); } } /* Output: diff --git a/concurrent/QuittableTask.java b/concurrent/QuittableTask.java index 3cf2a62e4..68e4c32a0 100644 --- a/concurrent/QuittableTask.java +++ b/concurrent/QuittableTask.java @@ -15,6 +15,6 @@ public class QuittableTask implements Runnable { public void run() { while(running.get()) // [1] new Nap(0.1); - System.out.print(id + " "); // [2] + System.err.print(id + " "); // [2] } } diff --git a/concurrent/SingleThreadExecutor.java b/concurrent/SingleThreadExecutor.java index ef89e3a53..f92231290 100644 --- a/concurrent/SingleThreadExecutor.java +++ b/concurrent/SingleThreadExecutor.java @@ -13,10 +13,10 @@ public static void main(String[] args) { IntStream.range(0, 10) .mapToObj(NapTask::new) .forEach(exec::execute); - System.out.println("All tasks submitted"); + System.err.println("All tasks submitted"); exec.shutdown(); while(!exec.isTerminated()) { - System.out.println( + System.err.println( Thread.currentThread().getName() + " awaiting termination"); new Nap(0.1); diff --git a/concurrent/StreamExceptions.java b/concurrent/StreamExceptions.java index 493daee1f..5e962933f 100644 --- a/concurrent/StreamExceptions.java +++ b/concurrent/StreamExceptions.java @@ -23,11 +23,11 @@ public static void main(String[] args) { test("D", 4); test("E", 5); // ... until there's a terminal operation: - System.out.println("Entering try"); + System.err.println("Entering try"); try { c.forEach(System.out::println); // [1] } catch(Exception e) { - System.out.println(e.getMessage()); + System.err.println(e.getMessage()); } } } diff --git a/concurrent/Summing.java b/concurrent/Summing.java index 321dcb573..ddc7cbad6 100644 --- a/concurrent/Summing.java +++ b/concurrent/Summing.java @@ -9,13 +9,13 @@ public class Summing { static void timeTest(String id, long checkValue, LongSupplier operation) { - System.out.print(id + ": "); + System.err.print(id + ": "); Timer timer = new Timer(); long result = operation.getAsLong(); if(result == checkValue) - System.out.println(timer.duration() + "ms"); + System.err.println(timer.duration() + "ms"); else - System.out.format("result: %d%ncheckValue: %d%n", + System.err.format("result: %d%ncheckValue: %d%n", result, checkValue); } public static final int SZ = 100_000_000; @@ -24,7 +24,7 @@ static void timeTest(String id, long checkValue, public static final long CHECK = (long)SZ * ((long)SZ + 1)/2; // Gauss's formula public static void main(String[] args) { - System.out.println(CHECK); + System.err.println(CHECK); timeTest("Sum Stream", CHECK, () -> LongStream.rangeClosed(0, SZ).sum()); timeTest("Sum Stream Parallel", CHECK, () -> diff --git a/concurrent/Summing2.java b/concurrent/Summing2.java index c046721f0..8f1289f96 100644 --- a/concurrent/Summing2.java +++ b/concurrent/Summing2.java @@ -19,7 +19,7 @@ static long basicSum(long[] ia) { public static final long CHECK = (long)SZ * ((long)SZ + 1)/2; public static void main(String[] args) { - System.out.println(CHECK); + System.err.println(CHECK); long[] la = new long[SZ+1]; Arrays.parallelSetAll(la, i -> i); Summing.timeTest("Array Stream Sum", CHECK, () -> diff --git a/concurrent/Summing3.java b/concurrent/Summing3.java index 252e96f7e..9cd476299 100644 --- a/concurrent/Summing3.java +++ b/concurrent/Summing3.java @@ -19,7 +19,7 @@ static long basicSum(Long[] ia) { public static final long CHECK = (long)SZ * ((long)SZ + 1)/2; public static void main(String[] args) { - System.out.println(CHECK); + System.err.println(CHECK); Long[] aL = new Long[SZ+1]; Arrays.parallelSetAll(aL, i -> (long)i); Summing.timeTest("Long Array Stream Reduce", diff --git a/concurrent/Summing4.java b/concurrent/Summing4.java index bb4fe2ea2..4fc62c0d3 100644 --- a/concurrent/Summing4.java +++ b/concurrent/Summing4.java @@ -7,7 +7,7 @@ public class Summing4 { public static void main(String[] args) { - System.out.println(Summing3.CHECK); + System.err.println(Summing3.CHECK); Long[] aL = new Long[Summing3.SZ+1]; Arrays.parallelSetAll(aL, i -> (long)i); Summing.timeTest("Long Parallel", diff --git a/concurrent/Workable.java b/concurrent/Workable.java index fcdbbbf80..17d48ce54 100644 --- a/concurrent/Workable.java +++ b/concurrent/Workable.java @@ -19,7 +19,7 @@ public String toString() { public static Workable work(Workable tt) { new Nap(tt.duration); // Seconds tt.id = tt.id + "W"; - System.out.println(tt); + System.err.println(tt); return tt; } public static CompletableFuture diff --git a/control/BreakAndContinue.java b/control/BreakAndContinue.java index 1faaaa034..f138f2d2c 100644 --- a/control/BreakAndContinue.java +++ b/control/BreakAndContinue.java @@ -10,16 +10,16 @@ public static void main(String[] args) { for(int i = 0; i < 100; i++) { // [1] if(i == 74) break; // Out of for loop if(i % 9 != 0) continue; // Next iteration - System.out.print(i + " "); + System.err.print(i + " "); } - System.out.println(); + System.err.println(); // Using for-in: for(int i : range(100)) { // [2] if(i == 74) break; // Out of for loop if(i % 9 != 0) continue; // Next iteration - System.out.print(i + " "); + System.err.print(i + " "); } - System.out.println(); + System.err.println(); int i = 0; // An "infinite loop": while(true) { // [3] @@ -27,7 +27,7 @@ public static void main(String[] args) { int j = i * 27; if(j == 1269) break; // Out of loop if(i % 10 != 0) continue; // Top of loop - System.out.print(i + " "); + System.err.print(i + " "); } } } diff --git a/control/CommaOperator.java b/control/CommaOperator.java index eae2df824..963962fa2 100644 --- a/control/CommaOperator.java +++ b/control/CommaOperator.java @@ -6,7 +6,7 @@ public class CommaOperator { public static void main(String[] args) { for(int i = 1, j = i + 10; i < 5; i++, j = i * 2) { - System.out.println("i = " + i + " j = " + j); + System.err.println("i = " + i + " j = " + j); } } } diff --git a/control/ForInFloat.java b/control/ForInFloat.java index cee845b57..dca6c59b6 100644 --- a/control/ForInFloat.java +++ b/control/ForInFloat.java @@ -11,7 +11,7 @@ public static void main(String[] args) { for(int i = 0; i < 10; i++) f[i] = rand.nextFloat(); for(float x : f) - System.out.println(x); + System.err.println(x); } } /* Output: diff --git a/control/ForInInt.java b/control/ForInInt.java index f6b283a35..e32fd03a6 100644 --- a/control/ForInInt.java +++ b/control/ForInInt.java @@ -7,17 +7,17 @@ public class ForInInt { public static void main(String[] args) { for(int i : range(10)) // 0..9 - System.out.print(i + " "); - System.out.println(); + System.err.print(i + " "); + System.err.println(); for(int i : range(5, 10)) // 5..9 - System.out.print(i + " "); - System.out.println(); + System.err.print(i + " "); + System.err.println(); for(int i : range(5, 20, 3)) // 5..20 step 3 - System.out.print(i + " "); - System.out.println(); + System.err.print(i + " "); + System.err.println(); for(int i : range(20, 5, -3)) // Count down - System.out.print(i + " "); - System.out.println(); + System.err.print(i + " "); + System.err.println(); } } /* Output: diff --git a/control/ForInString.java b/control/ForInString.java index 73e16538b..0f399c314 100644 --- a/control/ForInString.java +++ b/control/ForInString.java @@ -6,7 +6,7 @@ public class ForInString { public static void main(String[] args) { for(char c : "An African Swallow".toCharArray()) - System.out.print(c + " "); + System.err.print(c + " "); } } /* Output: diff --git a/control/IfElse.java b/control/IfElse.java index f40a07b7f..364e62039 100644 --- a/control/IfElse.java +++ b/control/IfElse.java @@ -15,11 +15,11 @@ else if(testval < target) // [1] } public static void main(String[] args) { test(10, 5); - System.out.println(result); + System.err.println(result); test(5, 10); - System.out.println(result); + System.err.println(result); test(5, 5); - System.out.println(result); + System.err.println(result); } } /* Output: diff --git a/control/LabeledFor.java b/control/LabeledFor.java index 2df79bad3..02c8e4f87 100644 --- a/control/LabeledFor.java +++ b/control/LabeledFor.java @@ -11,30 +11,30 @@ public static void main(String[] args) { for(; true ;) { // infinite loop inner: // Can't have statements here for(; i < 10; i++) { - System.out.println("i = " + i); + System.err.println("i = " + i); if(i == 2) { - System.out.println("continue"); + System.err.println("continue"); continue; } if(i == 3) { - System.out.println("break"); + System.err.println("break"); i++; // Otherwise i never // gets incremented. break; } if(i == 7) { - System.out.println("continue outer"); + System.err.println("continue outer"); i++; // Otherwise i never // gets incremented. continue outer; } if(i == 8) { - System.out.println("break outer"); + System.err.println("break outer"); break outer; } for(int k = 0; k < 5; k++) { if(k == 3) { - System.out.println("continue inner"); + System.err.println("continue inner"); continue inner; } } diff --git a/control/LabeledWhile.java b/control/LabeledWhile.java index 961f5ff38..01f55e837 100644 --- a/control/LabeledWhile.java +++ b/control/LabeledWhile.java @@ -9,24 +9,24 @@ public static void main(String[] args) { int i = 0; outer: while(true) { - System.out.println("Outer while loop"); + System.err.println("Outer while loop"); while(true) { i++; - System.out.println("i = " + i); + System.err.println("i = " + i); if(i == 1) { - System.out.println("continue"); + System.err.println("continue"); continue; } if(i == 3) { - System.out.println("continue outer"); + System.err.println("continue outer"); continue outer; } if(i == 5) { - System.out.println("break"); + System.err.println("break"); break; } if(i == 7) { - System.out.println("break outer"); + System.err.println("break outer"); break outer; } } diff --git a/control/ListCharacters.java b/control/ListCharacters.java index 43efce9f5..b753a86ab 100644 --- a/control/ListCharacters.java +++ b/control/ListCharacters.java @@ -8,7 +8,7 @@ public class ListCharacters { public static void main(String[] args) { for(char c = 0; c < 128; c++) if(Character.isLowerCase(c)) - System.out.println("value: " + (int)c + + System.err.println("value: " + (int)c + " character: " + c); } } diff --git a/control/RandomBounds.java b/control/RandomBounds.java index 6befc6f45..ece0b4cb3 100644 --- a/control/RandomBounds.java +++ b/control/RandomBounds.java @@ -13,17 +13,17 @@ public static void main(String[] args) { case "lower": while(Math.random() != 0.0) ; // Keep trying - System.out.println("Produced 0.0!"); + System.err.println("Produced 0.0!"); break; case "upper": while(Math.random() != 1.0) ; // Keep trying - System.out.println("Produced 1.0!"); + System.err.println("Produced 1.0!"); break; default: - System.out.println("Usage:"); - System.out.println("\tRandomBounds lower"); - System.out.println("\tRandomBounds upper"); + System.err.println("Usage:"); + System.err.println("\tRandomBounds lower"); + System.err.println("\tRandomBounds upper"); System.exit(1); } } diff --git a/control/StringSwitch.java b/control/StringSwitch.java index 638cc4276..700738fe3 100644 --- a/control/StringSwitch.java +++ b/control/StringSwitch.java @@ -8,32 +8,32 @@ public static void main(String[] args) { String color = "red"; // Old way: using if-then if("red".equals(color)) { - System.out.println("RED"); + System.err.println("RED"); } else if("green".equals(color)) { - System.out.println("GREEN"); + System.err.println("GREEN"); } else if("blue".equals(color)) { - System.out.println("BLUE"); + System.err.println("BLUE"); } else if("yellow".equals(color)) { - System.out.println("YELLOW"); + System.err.println("YELLOW"); } else { - System.out.println("Unknown"); + System.err.println("Unknown"); } // New way: Strings in switch switch(color) { case "red": - System.out.println("RED"); + System.err.println("RED"); break; case "green": - System.out.println("GREEN"); + System.err.println("GREEN"); break; case "blue": - System.out.println("BLUE"); + System.err.println("BLUE"); break; case "yellow": - System.out.println("YELLOW"); + System.err.println("YELLOW"); break; default: - System.out.println("Unknown"); + System.err.println("Unknown"); break; } } diff --git a/control/TestWithReturn.java b/control/TestWithReturn.java index efe05c907..032329a6f 100644 --- a/control/TestWithReturn.java +++ b/control/TestWithReturn.java @@ -12,9 +12,9 @@ static int test(int testval, int target) { return 0; // Match } public static void main(String[] args) { - System.out.println(test(10, 5)); - System.out.println(test(5, 10)); - System.out.println(test(5, 5)); + System.err.println(test(10, 5)); + System.err.println(test(5, 10)); + System.err.println(test(5, 5)); } } /* Output: diff --git a/control/TrueFalse.java b/control/TrueFalse.java index e87dade4f..ef68f7792 100644 --- a/control/TrueFalse.java +++ b/control/TrueFalse.java @@ -5,8 +5,8 @@ public class TrueFalse { public static void main(String[] args) { - System.out.println(1 == 1); - System.out.println(1 == 2); + System.err.println(1 == 1); + System.err.println(1 == 2); } } /* Output: diff --git a/control/VowelsAndConsonants.java b/control/VowelsAndConsonants.java index d3a192d0d..f465d859a 100644 --- a/control/VowelsAndConsonants.java +++ b/control/VowelsAndConsonants.java @@ -10,18 +10,18 @@ public static void main(String[] args) { Random rand = new Random(47); for(int i = 0; i < 100; i++) { int c = rand.nextInt(26) + 'a'; - System.out.print((char)c + ", " + c + ": "); + System.err.print((char)c + ", " + c + ": "); switch(c) { case 'a': case 'e': case 'i': case 'o': - case 'u': System.out.println("vowel"); + case 'u': System.err.println("vowel"); break; case 'y': - case 'w': System.out.println("Sometimes vowel"); + case 'w': System.err.println("Sometimes vowel"); break; - default: System.out.println("consonant"); + default: System.err.println("consonant"); } } } diff --git a/control/WhileTest.java b/control/WhileTest.java index 075068cfe..daefe515c 100644 --- a/control/WhileTest.java +++ b/control/WhileTest.java @@ -7,13 +7,13 @@ public class WhileTest { static boolean condition() { boolean result = Math.random() < 0.99; - System.out.print(result + ", "); + System.err.print(result + ", "); return result; } public static void main(String[] args) { while(condition()) - System.out.println("Inside 'while'"); - System.out.println("Exited 'while'"); + System.err.println("Inside 'while'"); + System.err.println("Exited 'while'"); } } /* Output: (First and Last 5 Lines) diff --git a/enums/BigEnumSet.java b/enums/BigEnumSet.java index 52ac34458..2dc5d328f 100644 --- a/enums/BigEnumSet.java +++ b/enums/BigEnumSet.java @@ -15,7 +15,7 @@ enum Big { A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A70, A71, A72, A73, A74, A75 } public static void main(String[] args) { EnumSet bigEnumSet = EnumSet.allOf(Big.class); - System.out.println(bigEnumSet); + System.err.println(bigEnumSet); } } /* Output: diff --git a/enums/Burrito2.java b/enums/Burrito2.java index 8b92ab0da..65a15e75b 100644 --- a/enums/Burrito2.java +++ b/enums/Burrito2.java @@ -16,9 +16,9 @@ public String toString() { return "Burrito is "+ degree; } public static void main(String[] args) { - System.out.println(new Burrito2(NOT)); - System.out.println(new Burrito2(MEDIUM)); - System.out.println(new Burrito2(HOT)); + System.err.println(new Burrito2(NOT)); + System.err.println(new Burrito2(MEDIUM)); + System.err.println(new Burrito2(HOT)); } } /* Output: diff --git a/enums/CarWash.java b/enums/CarWash.java index 95800e8fb..a8f924ec2 100644 --- a/enums/CarWash.java +++ b/enums/CarWash.java @@ -9,43 +9,43 @@ public enum Cycle { UNDERBODY { @Override void action() { - System.out.println("Spraying the underbody"); + System.err.println("Spraying the underbody"); } }, WHEELWASH { @Override void action() { - System.out.println("Washing the wheels"); + System.err.println("Washing the wheels"); } }, PREWASH { @Override void action() { - System.out.println("Loosening the dirt"); + System.err.println("Loosening the dirt"); } }, BASIC { @Override void action() { - System.out.println("The basic wash"); + System.err.println("The basic wash"); } }, HOTWAX { @Override void action() { - System.out.println("Applying hot wax"); + System.err.println("Applying hot wax"); } }, RINSE { @Override void action() { - System.out.println("Rinsing"); + System.err.println("Rinsing"); } }, BLOWDRY { @Override void action() { - System.out.println("Blowing dry"); + System.err.println("Blowing dry"); } }; abstract void action(); @@ -65,14 +65,14 @@ public String toString() { } public static void main(String[] args) { CarWash wash = new CarWash(); - System.out.println(wash); + System.err.println(wash); wash.washCar(); // Order of addition is unimportant: wash.add(Cycle.BLOWDRY); wash.add(Cycle.BLOWDRY); // Duplicates ignored wash.add(Cycle.RINSE); wash.add(Cycle.HOTWAX); - System.out.println(wash); + System.err.println(wash); wash.washCar(); } } diff --git a/enums/ConstantSpecificMethod.java b/enums/ConstantSpecificMethod.java index 913aa2919..9c7fdb367 100644 --- a/enums/ConstantSpecificMethod.java +++ b/enums/ConstantSpecificMethod.java @@ -29,7 +29,7 @@ String getInfo() { abstract String getInfo(); public static void main(String[] args) { for(ConstantSpecificMethod csm : values()) - System.out.println(csm.getInfo()); + System.err.println(csm.getInfo()); } } /* Output: diff --git a/enums/EnumClass.java b/enums/EnumClass.java index 061f8abfa..427014ef3 100644 --- a/enums/EnumClass.java +++ b/enums/EnumClass.java @@ -9,23 +9,23 @@ enum Shrubbery { GROUND, CRAWLING, HANGING } public class EnumClass { public static void main(String[] args) { for(Shrubbery s : Shrubbery.values()) { - System.out.println( + System.err.println( s + " ordinal: " + s.ordinal()); - System.out.print( + System.err.print( s.compareTo(Shrubbery.CRAWLING) + " "); - System.out.print( + System.err.print( s.equals(Shrubbery.CRAWLING) + " "); - System.out.println(s == Shrubbery.CRAWLING); - System.out.println(s.getDeclaringClass()); - System.out.println(s.name()); - System.out.println("********************"); + System.err.println(s == Shrubbery.CRAWLING); + System.err.println(s.getDeclaringClass()); + System.err.println(s.name()); + System.err.println("********************"); } // Produce an enum value from a String name: for(String s : "HANGING CRAWLING GROUND".split(" ")) { Shrubbery shrub = Enum.valueOf(Shrubbery.class, s); - System.out.println(shrub); + System.err.println(shrub); } } } diff --git a/enums/EnumMaps.java b/enums/EnumMaps.java index f75c5cd46..aa9f187e4 100644 --- a/enums/EnumMaps.java +++ b/enums/EnumMaps.java @@ -15,18 +15,18 @@ public static void main(String[] args) { EnumMap em = new EnumMap<>(AlarmPoints.class); em.put(KITCHEN, - () -> System.out.println("Kitchen fire!")); + () -> System.err.println("Kitchen fire!")); em.put(BATHROOM, - () -> System.out.println("Bathroom alert!")); + () -> System.err.println("Bathroom alert!")); for(Map.Entry e: em.entrySet()) { - System.out.print(e.getKey() + ": "); + System.err.print(e.getKey() + ": "); e.getValue().action(); } try { // If there's no value for a particular key: em.get(UTILITY).action(); } catch(Exception e) { - System.out.println("Expected: " + e); + System.err.println("Expected: " + e); } } } diff --git a/enums/EnumSets.java b/enums/EnumSets.java index 0e749cadc..172d1e47b 100644 --- a/enums/EnumSets.java +++ b/enums/EnumSets.java @@ -13,19 +13,19 @@ public static void main(String[] args) { EnumSet points = EnumSet.noneOf(AlarmPoints.class); // Empty points.add(BATHROOM); - System.out.println(points); + System.err.println(points); points.addAll( EnumSet.of(STAIR1, STAIR2, KITCHEN)); - System.out.println(points); + System.err.println(points); points = EnumSet.allOf(AlarmPoints.class); points.removeAll( EnumSet.of(STAIR1, STAIR2, KITCHEN)); - System.out.println(points); + System.err.println(points); points.removeAll( EnumSet.range(OFFICE1, OFFICE4)); - System.out.println(points); + System.err.println(points); points = EnumSet.complementOf(points); - System.out.println(points); + System.err.println(points); } } /* Output: diff --git a/enums/NonEnum.java b/enums/NonEnum.java index 344407307..9f499d2cc 100644 --- a/enums/NonEnum.java +++ b/enums/NonEnum.java @@ -8,9 +8,9 @@ public static void main(String[] args) { Class intClass = Integer.class; try { for(Object en : intClass.getEnumConstants()) - System.out.println(en); + System.err.println(en); } catch(Exception e) { - System.out.println("Expected: " + e); + System.err.println("Expected: " + e); } } } diff --git a/enums/NotClasses.java b/enums/NotClasses.java index 681e807d3..93c25dd90 100644 --- a/enums/NotClasses.java +++ b/enums/NotClasses.java @@ -9,19 +9,19 @@ enum LikeClasses { WINKEN { @Override void behavior() { - System.out.println("Behavior1"); + System.err.println("Behavior1"); } }, BLINKEN { @Override void behavior() { - System.out.println("Behavior2"); + System.err.println("Behavior2"); } }, NOD { @Override void behavior() { - System.out.println("Behavior3"); + System.err.println("Behavior3"); } }; abstract void behavior(); diff --git a/enums/OverrideConstantSpecific.java b/enums/OverrideConstantSpecific.java index 28e3343be..6d4c5714e 100644 --- a/enums/OverrideConstantSpecific.java +++ b/enums/OverrideConstantSpecific.java @@ -8,15 +8,15 @@ public enum OverrideConstantSpecific { WASHER { @Override void f() { - System.out.println("Overridden method"); + System.err.println("Overridden method"); } }; void f() { - System.out.println("default behavior"); + System.err.println("default behavior"); } public static void main(String[] args) { for(OverrideConstantSpecific ocs : values()) { - System.out.print(ocs + ": "); + System.err.print(ocs + ": "); ocs.f(); } } diff --git a/enums/OzWitch.java b/enums/OzWitch.java index c9eedb4fd..4240e17cb 100644 --- a/enums/OzWitch.java +++ b/enums/OzWitch.java @@ -19,7 +19,7 @@ private OzWitch(String description) { public String getDescription() { return description; } public static void main(String[] args) { for(OzWitch witch : OzWitch.values()) - System.out.println( + System.err.println( witch + ": " + witch.getDescription()); } } diff --git a/enums/PostOffice.java b/enums/PostOffice.java index 056348206..1e6b7b327 100644 --- a/enums/PostOffice.java +++ b/enums/PostOffice.java @@ -76,7 +76,7 @@ enum MailHandler { boolean handle(Mail m) { switch(m.generalDelivery) { case YES: - System.out.println( + System.err.println( "Using general delivery for " + m); return true; default: return false; @@ -92,7 +92,7 @@ boolean handle(Mail m) { switch(m.address) { case INCORRECT: return false; default: - System.out.println( + System.err.println( "Delivering "+ m + " automatically"); return true; } @@ -108,7 +108,7 @@ boolean handle(Mail m) { switch(m.address) { case INCORRECT: return false; default: - System.out.println( + System.err.println( "Delivering " + m + " normally"); return true; } @@ -121,7 +121,7 @@ boolean handle(Mail m) { switch(m.returnAddress) { case MISSING: return false; default: - System.out.println( + System.err.println( "Returning " + m + " to sender"); return true; } @@ -133,13 +133,13 @@ static void handle(Mail m) { for(MailHandler handler : MailHandler.values()) if(handler.handle(m)) return; - System.out.println(m + " is a dead letter"); + System.err.println(m + " is a dead letter"); } public static void main(String[] args) { for(Mail mail : Mail.generator(10)) { - System.out.println(mail.details()); + System.err.println(mail.details()); handle(mail); - System.out.println("*****"); + System.err.println("*****"); } } } diff --git a/enums/RandomTest.java b/enums/RandomTest.java index 92f2e481b..336311ff6 100644 --- a/enums/RandomTest.java +++ b/enums/RandomTest.java @@ -10,7 +10,7 @@ enum Activity { SITTING, LYING, STANDING, HOPPING, public class RandomTest { public static void main(String[] args) { for(int i = 0; i < 20; i++) - System.out.print( + System.err.print( Enums.random(Activity.class) + " "); } } diff --git a/enums/Reflection.java b/enums/Reflection.java index 822a134e8..86843c8dd 100644 --- a/enums/Reflection.java +++ b/enums/Reflection.java @@ -12,30 +12,30 @@ enum Explore { HERE, THERE } public class Reflection { public static Set analyze(Class enumClass) { - System.out.println( + System.err.println( "_____ Analyzing " + enumClass + " _____"); - System.out.println("Interfaces:"); + System.err.println("Interfaces:"); for(Type t : enumClass.getGenericInterfaces()) - System.out.println(t); - System.out.println( + System.err.println(t); + System.err.println( "Base: " + enumClass.getSuperclass()); - System.out.println("Methods: "); + System.err.println("Methods: "); Set methods = new TreeSet<>(); for(Method m : enumClass.getMethods()) methods.add(m.getName()); - System.out.println(methods); + System.err.println(methods); return methods; } public static void main(String[] args) { Set exploreMethods = analyze(Explore.class); Set enumMethods = analyze(Enum.class); - System.out.println( + System.err.println( "Explore.containsAll(Enum)? " + exploreMethods.containsAll(enumMethods)); - System.out.print("Explore.removeAll(Enum): "); + System.err.print("Explore.removeAll(Enum): "); exploreMethods.removeAll(enumMethods); - System.out.println(exploreMethods); + System.err.println(exploreMethods); // Decompile the code for the enum: OSExecute.command( "javap -cp build/classes/java/main Explore"); diff --git a/enums/RoShamBo.java b/enums/RoShamBo.java index 76b3d76fe..712f97f1a 100644 --- a/enums/RoShamBo.java +++ b/enums/RoShamBo.java @@ -9,7 +9,7 @@ public class RoShamBo { public static > void match(T a, T b) { - System.out.println( + System.err.println( a + " vs. " + b + ": " + a.compete(b)); } public static & Competitor> diff --git a/enums/RoShamBo1.java b/enums/RoShamBo1.java index abf52c9c9..e67254e31 100644 --- a/enums/RoShamBo1.java +++ b/enums/RoShamBo1.java @@ -72,7 +72,7 @@ public static Item newItem() { } } public static void match(Item a, Item b) { - System.out.println( + System.err.println( a + " vs. " + b + ": " + a.compete(b)); } public static void main(String[] args) { diff --git a/enums/SecurityCategory.java b/enums/SecurityCategory.java index 884cb56a2..e3a90e4a5 100644 --- a/enums/SecurityCategory.java +++ b/enums/SecurityCategory.java @@ -27,7 +27,7 @@ public static void main(String[] args) { for(int i = 0; i < 10; i++) { SecurityCategory category = Enums.random(SecurityCategory.class); - System.out.println(category + ": " + + System.err.println(category + ": " + category.randomSelection()); } } diff --git a/enums/TrafficLight.java b/enums/TrafficLight.java index b018e02c7..d0bd7be38 100644 --- a/enums/TrafficLight.java +++ b/enums/TrafficLight.java @@ -28,7 +28,7 @@ public String toString() { public static void main(String[] args) { TrafficLight t = new TrafficLight(); for(int i = 0; i < 7; i++) { - System.out.println(t); + System.err.println(t); t.change(); } } diff --git a/enums/UpcastEnum.java b/enums/UpcastEnum.java index a5df2a862..5f5cdedc8 100644 --- a/enums/UpcastEnum.java +++ b/enums/UpcastEnum.java @@ -12,7 +12,7 @@ public static void main(String[] args) { Enum e = Search.HITHER; // Upcast // e.values(); // No values() in Enum for(Enum en : e.getClass().getEnumConstants()) - System.out.println(en); + System.err.println(en); } } /* Output: diff --git a/enums/VendingMachine.java b/enums/VendingMachine.java index bc7d7c19e..a6544eab4 100644 --- a/enums/VendingMachine.java +++ b/enums/VendingMachine.java @@ -60,7 +60,7 @@ void next(Input input) { case ITEM_SELECTION: selection = input; if(amount < selection.amount()) - System.out.println( + System.err.println( "Insufficient money for " + selection); else state = DISPENSING; break; @@ -76,7 +76,7 @@ void next(Input input) { DISPENSING(StateDuration.TRANSIENT) { @Override void next() { - System.out.println("here is your " + selection); + System.err.println("here is your " + selection); amount -= selection.amount(); state = GIVING_CHANGE; } @@ -85,14 +85,14 @@ void next() { @Override void next() { if(amount > 0) { - System.out.println("Your change: " + amount); + System.err.println("Your change: " + amount); amount = 0; } state = RESTING; } }, TERMINAL {@Override - void output() { System.out.println("Halted"); } }; + void output() { System.err.println("Halted"); } }; private boolean isTransient = false; State() {} State(StateDuration trans) { isTransient = true; } @@ -105,7 +105,7 @@ void next() { "Only call next() for " + "StateDuration.TRANSIENT states"); } - void output() { System.out.println(amount); } + void output() { System.err.println(amount); } } static void run(Supplier gen) { while(state != State.TERMINAL) { diff --git a/enums/cartoons/EnumImplementation.java b/enums/cartoons/EnumImplementation.java index 58902e3fc..84ca25ae3 100644 --- a/enums/cartoons/EnumImplementation.java +++ b/enums/cartoons/EnumImplementation.java @@ -22,7 +22,7 @@ public CartoonCharacter get() { public class EnumImplementation { public static void printNext(Supplier rg) { - System.out.print(rg.get() + ", "); + System.err.print(rg.get() + ", "); } public static void main(String[] args) { // Choose any instance: diff --git a/enums/menu/Meal.java b/enums/menu/Meal.java index 64bc496d6..1e8ee7b8f 100644 --- a/enums/menu/Meal.java +++ b/enums/menu/Meal.java @@ -10,9 +10,9 @@ public static void main(String[] args) { for(int i = 0; i < 5; i++) { for(Course course : Course.values()) { Food food = course.randomSelection(); - System.out.println(food); + System.err.println(food); } - System.out.println("***"); + System.err.println("***"); } } } diff --git a/enums/menu/Meal2.java b/enums/menu/Meal2.java index df1b90a58..1786eb756 100644 --- a/enums/menu/Meal2.java +++ b/enums/menu/Meal2.java @@ -39,9 +39,9 @@ public static void main(String[] args) { for(int i = 0; i < 5; i++) { for(Meal2 meal : Meal2.values()) { Food food = meal.randomSelection(); - System.out.println(food); + System.err.println(food); } - System.out.println("***"); + System.err.println("***"); } } } diff --git a/equalshashcode/ComposedEquality.java b/equalshashcode/ComposedEquality.java index c224231ca..c615ea691 100644 --- a/equalshashcode/ComposedEquality.java +++ b/equalshashcode/ComposedEquality.java @@ -24,7 +24,7 @@ public class ComposedEquality extends SuccinctEquality { public ComposedEquality(int i, String s, double d) { super(i, s, d); part = new Part(s, d); - System.out.println("made 'ComposedEquality'"); + System.err.println("made 'ComposedEquality'"); } @Override public boolean equals(Object rval) { diff --git a/equalshashcode/CountedString.java b/equalshashcode/CountedString.java index 5a6ec5fab..1bfaf21fe 100644 --- a/equalshashcode/CountedString.java +++ b/equalshashcode/CountedString.java @@ -47,10 +47,10 @@ public static void main(String[] args) { cs[i] = new CountedString("hi"); map.put(cs[i], i); // Autobox int to Integer } - System.out.println(map); + System.err.println(map); for(CountedString cstring : cs) { - System.out.println("Looking up " + cstring); - System.out.println(map.get(cstring)); + System.err.println("Looking up " + cstring); + System.err.println(map.get(cstring)); } } } diff --git a/equalshashcode/DefaultComparison.java b/equalshashcode/DefaultComparison.java index d855de369..fbc1332ff 100644 --- a/equalshashcode/DefaultComparison.java +++ b/equalshashcode/DefaultComparison.java @@ -14,8 +14,8 @@ public static void main(String[] args) { DefaultComparison a = new DefaultComparison(1, 2, 3), b = new DefaultComparison(1, 2, 3); - System.out.println(a == a); - System.out.println(a == b); + System.err.println(a == a); + System.err.println(a == b); } } /* Output: diff --git a/equalshashcode/Equality.java b/equalshashcode/Equality.java index 6ab13e5e9..b90fb6664 100644 --- a/equalshashcode/Equality.java +++ b/equalshashcode/Equality.java @@ -12,7 +12,7 @@ public Equality(int i, String s, double d) { this.i = i; this.s = s; this.d = d; - System.out.println("made 'Equality'"); + System.err.println("made 'Equality'"); } @Override public boolean equals(Object rval) { @@ -33,7 +33,7 @@ public boolean equals(Object rval) { } public void test(String descr, String expected, Object rval) { - System.out.format("-- Testing %s --%n" + + System.err.format("-- Testing %s --%n" + "%s instanceof Equality: %s%n" + "Expected %s, got %s%n", descr, descr, rval instanceof Equality, diff --git a/equalshashcode/SimpleHashMap.java b/equalshashcode/SimpleHashMap.java index f82022a19..d2829c76f 100644 --- a/equalshashcode/SimpleHashMap.java +++ b/equalshashcode/SimpleHashMap.java @@ -64,8 +64,8 @@ public static void main(String[] args) { new SimpleHashMap<>(); m.putAll(Countries.capitals(8)); m.forEach((k, v) -> - System.out.println(k + "=" + v)); - System.out.println(m.get("BENIN")); + System.err.println(k + "=" + v)); + System.err.println(m.get("BENIN")); m.entrySet().forEach(System.out::println); } } diff --git a/equalshashcode/SlowMap.java b/equalshashcode/SlowMap.java index 63f17092d..15d8479ca 100644 --- a/equalshashcode/SlowMap.java +++ b/equalshashcode/SlowMap.java @@ -38,8 +38,8 @@ public static void main(String[] args) { SlowMap m= new SlowMap<>(); m.putAll(Countries.capitals(8)); m.forEach((k, v) -> - System.out.println(k + "=" + v)); - System.out.println(m.get("BENIN")); + System.err.println(k + "=" + v)); + System.err.println(m.get("BENIN")); m.entrySet().forEach(System.out::println); } } diff --git a/equalshashcode/SpringDetector.java b/equalshashcode/SpringDetector.java index 9b41bd3e2..cd1175337 100644 --- a/equalshashcode/SpringDetector.java +++ b/equalshashcode/SpringDetector.java @@ -27,14 +27,14 @@ void detectSpring(Class type) { Function.identity(), gh -> new Prediction())); map.forEach((k, v) -> - System.out.println(k + ": " + v)); + System.err.println(k + ": " + v)); Groundhog gh = ghog.newInstance(3); - System.out.println( + System.err.println( "Looking up prediction for " + gh); if(map.containsKey(gh)) - System.out.println(map.get(gh)); + System.err.println(map.get(gh)); else - System.out.println("Key not found: " + gh); + System.err.println("Key not found: " + gh); } catch(NoSuchMethodException | IllegalAccessException | InvocationTargetException | diff --git a/equalshashcode/StringHashCode.java b/equalshashcode/StringHashCode.java index 222fa612a..f79d21aaf 100644 --- a/equalshashcode/StringHashCode.java +++ b/equalshashcode/StringHashCode.java @@ -6,8 +6,8 @@ public class StringHashCode { public static void main(String[] args) { String[] hellos = "Hello Hello".split(" "); - System.out.println(hellos[0].hashCode()); - System.out.println(hellos[1].hashCode()); + System.err.println(hellos[0].hashCode()); + System.err.println(hellos[1].hashCode()); } } /* Output: diff --git a/equalshashcode/SuccinctEquality.java b/equalshashcode/SuccinctEquality.java index 55a0d8de6..fe3f51b50 100644 --- a/equalshashcode/SuccinctEquality.java +++ b/equalshashcode/SuccinctEquality.java @@ -7,7 +7,7 @@ public class SuccinctEquality extends Equality { public SuccinctEquality(int i, String s, double d) { super(i, s, d); - System.out.println("made 'SuccinctEquality'"); + System.err.println("made 'SuccinctEquality'"); } @Override public boolean equals(Object rval) { diff --git a/exceptions/AlwaysFinally.java b/exceptions/AlwaysFinally.java index bb2270f77..27807696b 100644 --- a/exceptions/AlwaysFinally.java +++ b/exceptions/AlwaysFinally.java @@ -8,19 +8,19 @@ class FourException extends Exception {} public class AlwaysFinally { public static void main(String[] args) { - System.out.println("Entering first try block"); + System.err.println("Entering first try block"); try { - System.out.println("Entering second try block"); + System.err.println("Entering second try block"); try { throw new FourException(); } finally { - System.out.println("finally in 2nd try block"); + System.err.println("finally in 2nd try block"); } } catch(FourException e) { - System.out.println( + System.err.println( "Caught FourException in 1st try block"); } finally { - System.out.println("finally in 1st try block"); + System.err.println("finally in 1st try block"); } } } diff --git a/exceptions/AutoCloseableDetails.java b/exceptions/AutoCloseableDetails.java index 24a22e9d6..7abf7b07a 100644 --- a/exceptions/AutoCloseableDetails.java +++ b/exceptions/AutoCloseableDetails.java @@ -6,10 +6,10 @@ class Reporter implements AutoCloseable { String name = getClass().getSimpleName(); Reporter() { - System.out.println("Creating " + name); + System.err.println("Creating " + name); } public void close() { - System.out.println("Closing " + name); + System.err.println("Closing " + name); } } diff --git a/exceptions/BodyException.java b/exceptions/BodyException.java index 3e907f8ab..f1f732c69 100644 --- a/exceptions/BodyException.java +++ b/exceptions/BodyException.java @@ -11,12 +11,12 @@ public static void main(String[] args) { First f = new First(); Second s2 = new Second() ) { - System.out.println("In body"); + System.err.println("In body"); Third t = new Third(); new SecondExcept(); - System.out.println("End of body"); + System.err.println("End of body"); } catch(CE e) { - System.out.println("Caught: " + e); + System.err.println("Caught: " + e); } } } diff --git a/exceptions/Cleanup.java b/exceptions/Cleanup.java index 3d072304f..a2733acb9 100644 --- a/exceptions/Cleanup.java +++ b/exceptions/Cleanup.java @@ -14,13 +14,13 @@ public static void main(String[] args) { while((s = in.getLine()) != null) ; // Perform line-by-line processing here... } catch(Exception e) { - System.out.println("Caught Exception in main"); + System.err.println("Caught Exception in main"); e.printStackTrace(System.out); } finally { in.dispose(); } } catch(Exception e) { - System.out.println( + System.err.println( "InputFile construction failed"); } } diff --git a/exceptions/CleanupIdiom.java b/exceptions/CleanupIdiom.java index e8dd62c46..68688c14e 100644 --- a/exceptions/CleanupIdiom.java +++ b/exceptions/CleanupIdiom.java @@ -8,7 +8,7 @@ class NeedsCleanup { // Construction can't fail private static long counter = 1; private final long id = counter++; public void dispose() { - System.out.println( + System.err.println( "NeedsCleanup " + id + " disposed"); } } @@ -54,12 +54,12 @@ public static void main(String[] args) { nc5.dispose(); } } catch(ConstructionException e) { // nc5 const. - System.out.println(e); + System.err.println(e); } finally { nc4.dispose(); } } catch(ConstructionException e) { // nc4 const. - System.out.println(e); + System.err.println(e); } } } diff --git a/exceptions/CloseExceptions.java b/exceptions/CloseExceptions.java index 4309a888f..0a867785a 100644 --- a/exceptions/CloseExceptions.java +++ b/exceptions/CloseExceptions.java @@ -8,10 +8,10 @@ class CloseException extends Exception {} class Reporter2 implements AutoCloseable { String name = getClass().getSimpleName(); Reporter2() { - System.out.println("Creating " + name); + System.err.println("Creating " + name); } public void close() throws CloseException { - System.out.println("Closing " + name); + System.err.println("Closing " + name); } } @@ -30,9 +30,9 @@ public static void main(String[] args) { Closer c = new Closer(); Second s = new Second() ) { - System.out.println("In body"); + System.err.println("In body"); } catch(CloseException e) { - System.out.println("Caught: " + e); + System.err.println("Caught: " + e); } } } diff --git a/exceptions/ConstructorException.java b/exceptions/ConstructorException.java index 54eaaba35..07c684881 100644 --- a/exceptions/ConstructorException.java +++ b/exceptions/ConstructorException.java @@ -19,9 +19,9 @@ public static void main(String[] args) { SecondExcept s = new SecondExcept(); Second s2 = new Second() ) { - System.out.println("In body"); + System.err.println("In body"); } catch(CE e) { - System.out.println("Caught: " + e); + System.err.println("Caught: " + e); } } } diff --git a/exceptions/DynamicFields.java b/exceptions/DynamicFields.java index da3b9617f..ff8315cc2 100644 --- a/exceptions/DynamicFields.java +++ b/exceptions/DynamicFields.java @@ -31,8 +31,7 @@ private int hasField(String id) { return i; return -1; } - private int getFieldNumber(String id) - throws NoSuchFieldException { + private int getFieldNumber(String id) throws NoSuchFieldException { int fieldNum = hasField(id); if(fieldNum == -1) throw new NoSuchFieldException(); @@ -54,20 +53,18 @@ private int makeField(String id) { // Recursive call with expanded fields: return makeField(id); } - public Object - getField(String id) throws NoSuchFieldException { + public Object getField(String id) throws NoSuchFieldException { return fields[getFieldNumber(id)][1]; } - public Object setField(String id, Object value) - throws DynamicFieldsException { + public Object setField(String id, Object value) throws DynamicFieldsException { if(value == null) { // Most exceptions don't have a "cause" // constructor. In these cases you must use // initCause(), available in all // Throwable subclasses. - DynamicFieldsException dfe = - new DynamicFieldsException(); - dfe.initCause(new NullPointerException()); + DynamicFieldsException dfe = new DynamicFieldsException(); + dfe.initCause(new NullPointerException());//self-note: 这样做就会在错误输出里多一句 Caused by: java.lang.NullPointerException + throw dfe; } int fieldNumber = hasField(id); @@ -78,26 +75,25 @@ public Object setField(String id, Object value) result = getField(id); // Get old value } catch(NoSuchFieldException e) { // Use constructor that takes "cause": - throw new RuntimeException(e); + throw new RuntimeException(e);//self-note: 这里用了cause参数构造器 RuntimeException(Throwable cause) } fields[fieldNumber][1] = value; return result; } public static void main(String[] args) { DynamicFields df = new DynamicFields(3); - System.out.println(df); + System.err.println("df-->"+df); try { df.setField("d", "A value for d"); df.setField("number", 47); df.setField("number2", 48); - System.out.println(df); + System.err.println(df); df.setField("d", "A new value for d"); df.setField("number3", 11); - System.out.println("df: " + df); - System.out.println("df.getField(\"d\") : " + System.err.println("df: " + df); + System.err.println("df.getField(\"d\") : " + df.getField("d")); - Object field = - df.setField("d", null); // Exception + Object field = df.setField("d", null); // Exception } catch(NoSuchFieldException | DynamicFieldsException e) { e.printStackTrace(System.out); diff --git a/exceptions/ExceptionMethods.java b/exceptions/ExceptionMethods.java index bd6e82598..a10d18875 100644 --- a/exceptions/ExceptionMethods.java +++ b/exceptions/ExceptionMethods.java @@ -9,13 +9,13 @@ public static void main(String[] args) { try { throw new Exception("My Exception"); } catch(Exception e) { - System.out.println("Caught Exception"); - System.out.println( + System.err.println("Caught Exception"); + System.err.println( "getMessage():" + e.getMessage()); - System.out.println("getLocalizedMessage():" + + System.err.println("getLocalizedMessage():" + e.getLocalizedMessage()); - System.out.println("toString():" + e); - System.out.println("printStackTrace():"); + System.err.println("toString():" + e); + System.err.println("printStackTrace():"); e.printStackTrace(System.out); } } diff --git a/exceptions/ExtraFeatures.java b/exceptions/ExtraFeatures.java index 8aa922afd..21286a110 100644 --- a/exceptions/ExtraFeatures.java +++ b/exceptions/ExtraFeatures.java @@ -22,17 +22,17 @@ public String getMessage() { public class ExtraFeatures { public static void f() throws MyException2 { - System.out.println( + System.err.println( "Throwing MyException2 from f()"); throw new MyException2(); } public static void g() throws MyException2 { - System.out.println( + System.err.println( "Throwing MyException2 from g()"); throw new MyException2("Originated in g()"); } public static void h() throws MyException2 { - System.out.println( + System.err.println( "Throwing MyException2 from h()"); throw new MyException2("Originated in h()", 47); } @@ -51,7 +51,7 @@ public static void main(String[] args) { h(); } catch(MyException2 e) { e.printStackTrace(System.out); - System.out.println("e.val() = " + e.val()); + System.err.println("e.val() = " + e.val()); } } } diff --git a/exceptions/FinallyWorks.java b/exceptions/FinallyWorks.java index fc4fec0a4..7c3566266 100644 --- a/exceptions/FinallyWorks.java +++ b/exceptions/FinallyWorks.java @@ -14,11 +14,11 @@ public static void main(String[] args) { // Post-increment is zero first time: if(count++ == 0) throw new ThreeException(); - System.out.println("No exception"); + System.err.println("No exception"); } catch(ThreeException e) { - System.out.println("ThreeException"); + System.err.println("ThreeException"); } finally { - System.out.println("In finally clause"); + System.err.println("In finally clause"); if(count == 2) break; // out of "while" } } diff --git a/exceptions/FullConstructors.java b/exceptions/FullConstructors.java index f5b4c9ff2..096975cec 100644 --- a/exceptions/FullConstructors.java +++ b/exceptions/FullConstructors.java @@ -10,11 +10,11 @@ class MyException extends Exception { public class FullConstructors { public static void f() throws MyException { - System.out.println("Throwing MyException from f()"); + System.err.println("Throwing MyException from f()"); throw new MyException(); } public static void g() throws MyException { - System.out.println("Throwing MyException from g()"); + System.err.println("Throwing MyException from g()"); throw new MyException("Originated in g()"); } public static void main(String[] args) { diff --git a/exceptions/Human.java b/exceptions/Human.java index 7ee7dcaae..93a6e697a 100644 --- a/exceptions/Human.java +++ b/exceptions/Human.java @@ -13,15 +13,15 @@ public static void main(String[] args) { try { throw new Sneeze(); } catch(Sneeze s) { - System.out.println("Caught Sneeze"); + System.err.println("Caught Sneeze"); } catch(Annoyance a) { - System.out.println("Caught Annoyance"); + System.err.println("Caught Annoyance"); } // Catch the base type: try { throw new Sneeze(); } catch(Annoyance a) { - System.out.println("Caught Annoyance"); + System.err.println("Caught Annoyance"); } } } diff --git a/exceptions/InheritingExceptions.java b/exceptions/InheritingExceptions.java index abb80c3b6..156243c38 100644 --- a/exceptions/InheritingExceptions.java +++ b/exceptions/InheritingExceptions.java @@ -8,7 +8,7 @@ class SimpleException extends Exception {} public class InheritingExceptions { public void f() throws SimpleException { - System.out.println( + System.err.println( "Throw SimpleException from f()"); throw new SimpleException(); } @@ -18,7 +18,7 @@ public static void main(String[] args) { try { sed.f(); } catch(SimpleException e) { - System.out.println("Caught it!"); + System.err.println("Caught it!"); } } } diff --git a/exceptions/InputFile.java b/exceptions/InputFile.java index 5c269851d..3823cb847 100644 --- a/exceptions/InputFile.java +++ b/exceptions/InputFile.java @@ -12,7 +12,7 @@ public InputFile(String fname) throws Exception { in = new BufferedReader(new FileReader(fname)); // Other code that might throw exceptions } catch(FileNotFoundException e) { - System.out.println("Could not open " + fname); + System.err.println("Could not open " + fname); // Wasn't open, so don't close it throw e; } catch(Exception e) { @@ -20,7 +20,7 @@ public InputFile(String fname) throws Exception { try { in.close(); } catch(IOException e2) { - System.out.println("in.close() unsuccessful"); + System.err.println("in.close() unsuccessful"); } throw e; // Rethrow } finally { @@ -39,7 +39,7 @@ public String getLine() { public void dispose() { try { in.close(); - System.out.println("dispose() successful"); + System.err.println("dispose() successful"); } catch(IOException e2) { throw new RuntimeException("in.close() failed"); } diff --git a/exceptions/LoggingExceptions.java b/exceptions/LoggingExceptions.java index 0120ee17f..261c816d0 100644 --- a/exceptions/LoggingExceptions.java +++ b/exceptions/LoggingExceptions.java @@ -8,8 +8,7 @@ import java.io.*; class LoggingException extends Exception { - private static Logger logger = - Logger.getLogger("LoggingException"); + private static Logger logger = Logger.getLogger("LoggingException"); LoggingException() { StringWriter trace = new StringWriter(); printStackTrace(new PrintWriter(trace)); diff --git a/exceptions/LoggingExceptions2.java b/exceptions/LoggingExceptions2.java index 21a921379..db2a107a7 100644 --- a/exceptions/LoggingExceptions2.java +++ b/exceptions/LoggingExceptions2.java @@ -8,8 +8,7 @@ import java.io.*; public class LoggingExceptions2 { - private static Logger logger = - Logger.getLogger("LoggingExceptions2"); + private static Logger logger = Logger.getLogger("LoggingExceptions2"); static void logException(Exception e) { StringWriter trace = new StringWriter(); e.printStackTrace(new PrintWriter(trace)); diff --git a/exceptions/LostMessage.java b/exceptions/LostMessage.java index 1446d9033..2056169a4 100644 --- a/exceptions/LostMessage.java +++ b/exceptions/LostMessage.java @@ -35,7 +35,7 @@ public static void main(String[] args) { } } catch(VeryImportantException | HoHumException e) { - System.out.println(e); + System.err.println(e); } } } diff --git a/exceptions/MultipleReturns.java b/exceptions/MultipleReturns.java index 3f667b335..7ff6f70a6 100644 --- a/exceptions/MultipleReturns.java +++ b/exceptions/MultipleReturns.java @@ -5,19 +5,19 @@ public class MultipleReturns { public static void f(int i) { - System.out.println( + System.err.println( "Initialization that requires cleanup"); try { - System.out.println("Point 1"); + System.err.println("Point 1"); if(i == 1) return; - System.out.println("Point 2"); + System.err.println("Point 2"); if(i == 2) return; - System.out.println("Point 3"); + System.err.println("Point 3"); if(i == 3) return; - System.out.println("End"); + System.err.println("End"); return; } finally { - System.out.println("Performing cleanup"); + System.err.println("Performing cleanup"); } } public static void main(String[] args) { diff --git a/exceptions/OnOffSwitch.java b/exceptions/OnOffSwitch.java index fe05fa351..b05025321 100644 --- a/exceptions/OnOffSwitch.java +++ b/exceptions/OnOffSwitch.java @@ -15,10 +15,10 @@ public static void main(String[] args) { f(); sw.off(); } catch(OnOffException1 e) { - System.out.println("OnOffException1"); + System.err.println("OnOffException1"); sw.off(); } catch(OnOffException2 e) { - System.out.println("OnOffException2"); + System.err.println("OnOffException2"); sw.off(); } } diff --git a/exceptions/RethrowNew.java b/exceptions/RethrowNew.java index daa4ad418..fb5319505 100644 --- a/exceptions/RethrowNew.java +++ b/exceptions/RethrowNew.java @@ -14,7 +14,7 @@ class TwoException extends Exception { public class RethrowNew { public static void f() throws OneException { - System.out.println( + System.err.println( "originating the exception in f()"); throw new OneException("thrown from f()"); } @@ -23,13 +23,13 @@ public static void main(String[] args) { try { f(); } catch(OneException e) { - System.out.println( + System.err.println( "Caught in inner try, e.printStackTrace()"); e.printStackTrace(System.out); throw new TwoException("from inner try"); } } catch(TwoException e) { - System.out.println( + System.err.println( "Caught in outer try, e.printStackTrace()"); e.printStackTrace(System.out); } diff --git a/exceptions/Rethrowing.java b/exceptions/Rethrowing.java index 5bf1a6357..74094b229 100644 --- a/exceptions/Rethrowing.java +++ b/exceptions/Rethrowing.java @@ -6,16 +6,16 @@ public class Rethrowing { public static void f() throws Exception { - System.out.println( - "originating the exception in f()"); + System.err.println( + "originating the exception in f()---------------------"); throw new Exception("thrown from f()"); } public static void g() throws Exception { try { f(); } catch(Exception e) { - System.out.println( - "Inside g(), e.printStackTrace()"); + System.err.println( + "Inside g(), e.printStackTrace()---------------------"); e.printStackTrace(System.out); throw e; } @@ -24,8 +24,8 @@ public static void h() throws Exception { try { f(); } catch(Exception e) { - System.out.println( - "Inside h(), e.printStackTrace()"); + System.err.println( + "Inside h(), e.printStackTrace()---------------------"); e.printStackTrace(System.out); throw (Exception)e.fillInStackTrace(); } @@ -34,13 +34,13 @@ public static void main(String[] args) { try { g(); } catch(Exception e) { - System.out.println("main: printStackTrace()"); + System.err.println("main: printStackTrace()"); e.printStackTrace(System.out); } try { h(); } catch(Exception e) { - System.out.println("main: printStackTrace()"); + System.err.println("main: printStackTrace()"); e.printStackTrace(System.out); } } diff --git a/exceptions/StormyInning.java b/exceptions/StormyInning.java index 644c10ba8..688df4792 100644 --- a/exceptions/StormyInning.java +++ b/exceptions/StormyInning.java @@ -57,11 +57,11 @@ public static void main(String[] args) { StormyInning si = new StormyInning(); si.atBat(); } catch(PopFoul e) { - System.out.println("Pop foul"); + System.err.println("Pop foul"); } catch(RainedOut e) { - System.out.println("Rained out"); + System.err.println("Rained out"); } catch(BaseballException e) { - System.out.println("Generic baseball exception"); + System.err.println("Generic baseball exception"); } // Strike not thrown in derived version. try { @@ -71,13 +71,13 @@ public static void main(String[] args) { // You must catch the exceptions from the // base-class version of the method: } catch(Strike e) { - System.out.println("Strike"); + System.err.println("Strike"); } catch(Foul e) { - System.out.println("Foul"); + System.err.println("Foul"); } catch(RainedOut e) { - System.out.println("Rained out"); + System.err.println("Rained out"); } catch(BaseballException e) { - System.out.println("Generic baseball exception"); + System.err.println("Generic baseball exception"); } } } diff --git a/exceptions/Switch.java b/exceptions/Switch.java index 7d491d004..351efec8a 100644 --- a/exceptions/Switch.java +++ b/exceptions/Switch.java @@ -8,11 +8,11 @@ public class Switch { public boolean read() { return state; } public void on() { state = true; - System.out.println(this); + System.err.println(this); } public void off() { state = false; - System.out.println(this); + System.err.println(this); } @Override public String toString() { diff --git a/exceptions/TurnOffChecking.java b/exceptions/TurnOffChecking.java index 898431b64..e7af8fb4c 100644 --- a/exceptions/TurnOffChecking.java +++ b/exceptions/TurnOffChecking.java @@ -40,18 +40,18 @@ public static void main(String[] args) { else throw new SomeOtherException(); } catch(SomeOtherException e) { - System.out.println( + System.err.println( "SomeOtherException: " + e); } catch(RuntimeException re) { try { throw re.getCause(); } catch(FileNotFoundException e) { - System.out.println( - "FileNotFoundException: " + e); + System.err.println( + "1 FileNotFoundException: " + e); } catch(IOException e) { - System.out.println("IOException: " + e); + System.err.println("2 IOException: " + e); } catch(Throwable e) { - System.out.println("Throwable: " + e); + System.err.println("3 Throwable: " + e); } } } diff --git a/exceptions/WhoCalled.java b/exceptions/WhoCalled.java index 4c4e01041..5274e57c8 100644 --- a/exceptions/WhoCalled.java +++ b/exceptions/WhoCalled.java @@ -11,16 +11,16 @@ static void f() { throw new Exception(); } catch(Exception e) { for(StackTraceElement ste : e.getStackTrace()) - System.out.println(ste.getMethodName()); + System.err.println(ste.getMethodName()); } } static void g() { f(); } static void h() { g(); } public static void main(String[] args) { f(); - System.out.println("*******"); + System.err.println("*******"); g(); - System.out.println("*******"); + System.err.println("*******"); h(); } } diff --git a/exceptions/WithFinally.java b/exceptions/WithFinally.java index 9d3efc3a4..5b2721cb8 100644 --- a/exceptions/WithFinally.java +++ b/exceptions/WithFinally.java @@ -12,9 +12,9 @@ public static void main(String[] args) { // Code that can throw exceptions... OnOffSwitch.f(); } catch(OnOffException1 e) { - System.out.println("OnOffException1"); + System.err.println("OnOffException1"); } catch(OnOffException2 e) { - System.out.println("OnOffException2"); + System.err.println("OnOffException2"); } finally { sw.off(); } diff --git a/files/AddAndSubtractPaths.java b/files/AddAndSubtractPaths.java index f3984d19c..d6e6c66f8 100644 --- a/files/AddAndSubtractPaths.java +++ b/files/AddAndSubtractPaths.java @@ -10,21 +10,25 @@ public class AddAndSubtractPaths { .toAbsolutePath() .normalize(); static void show(int id, Path result) { +// System.err.println("AAA*---"+result); if(result.isAbsolute()) - System.out.println("(" + id + ")r " + + System.err.println("(" + id + ")[relativize] " + base.relativize(result)); else - System.out.println("(" + id + ") " + result); + System.err.println("(" + id + ") " + result); try { - System.out.println("RealPath: " + System.err.println("RealPath: " + result.toRealPath()); } catch(IOException e) { - System.out.println(e); + System.err.println("--------------------------"+e); } + System.err.println(); + System.err.println(); } public static void main(String[] args) { - System.out.println(System.getProperty("os.name")); - System.out.println(base); + System.err.println(System.getProperty("os.name")); + System.err.println(base); + Path p = Paths.get("AddAndSubtractPaths.java") .toAbsolutePath(); show(1, p); diff --git a/files/Directories.java b/files/Directories.java index 10ad9beec..c4525dcd5 100644 --- a/files/Directories.java +++ b/files/Directories.java @@ -4,16 +4,15 @@ // Visit http://OnJava8.com for more book information. import java.util.*; import java.nio.file.*; -import onjava.RmDir; +//import onjava.RmDir; public class Directories { static Path test = Paths.get("test"); - static String sep = - FileSystems.getDefault().getSeparator(); - static List parts = - Arrays.asList("foo", "bar", "baz", "bag"); + static String sep = FileSystems.getDefault().getSeparator(); + static List parts = Arrays.asList("foo", "bar", "baz", "bag"); + static Path makeVariant() { - Collections.rotate(parts, 1); + Collections.rotate(parts, 1);//self-note: 每次调用都轮转一次来输出不同的路径 return Paths.get("test", String.join(sep, parts)); } static void refreshTestDir() throws Exception { @@ -22,8 +21,7 @@ static void refreshTestDir() throws Exception { if(!Files.exists(test)) Files.createDirectory(test); } - public static void - main(String[] args) throws Exception { + public static void main(String[] args) throws Exception { refreshTestDir(); Files.createFile(test.resolve("Hello.txt")); Path variant = makeVariant(); @@ -31,12 +29,12 @@ static void refreshTestDir() throws Exception { try { Files.createDirectory(variant); } catch(Exception e) { - System.out.println("Nope, that doesn't work."); + System.err.println("Nope, that doesn't work."); } populateTestDir(); - Path tempdir = - Files.createTempDirectory(test, "DIR_"); - Files.createTempFile(tempdir, "pre", ".non"); + Path tempdir = Files.createTempDirectory(test, "DIR_"); + Path fileName = Files.createTempFile(tempdir, "pre", ".non").getFileName(); + System.err.println("tmp文件名"+fileName); Files.newDirectoryStream(test) .forEach(System.out::println); System.out.println("*********"); @@ -46,7 +44,7 @@ static void populateTestDir() throws Exception { for(int i = 0; i < parts.size(); i++) { Path variant = makeVariant(); if(!Files.exists(variant)) { - Files.createDirectories(variant); + Files.createDirectories(variant);//self-note: 创建多级目录 Files.copy(Paths.get("Directories.java"), variant.resolve("File.txt")); Files.createTempFile(variant, null, null); diff --git a/files/FileSystemDemo.java b/files/FileSystemDemo.java index 3d9024ca8..1a1aa1914 100644 --- a/files/FileSystemDemo.java +++ b/files/FileSystemDemo.java @@ -6,11 +6,13 @@ public class FileSystemDemo { static void show(String id, Object o) { - System.out.println(id + ": " + o); + System.err.println(id + ": " + o); } public static void main(String[] args) { - System.out.println(System.getProperty("os.name")); + System.err.println(System.getProperty("os.name")); FileSystem fsys = FileSystems.getDefault(); +// FileSystems.getFileSystem() //self-note: 通过uri参数得到文件系统 +// FileSystems.newFileSystem() for(FileStore fs : fsys.getFileStores()) show("File Store", fs); for(Path rd : fsys.getRootDirectories()) diff --git a/files/Find.java b/files/Find.java index ac97ebdce..5fced2a78 100644 --- a/files/Find.java +++ b/files/Find.java @@ -19,7 +19,7 @@ public class Find { Files.walk(test) .filter(matcher::matches) .forEach(System.out::println); - System.out.println("***************"); + System.out.println("***************DONE 0"); PathMatcher matcher2 = FileSystems.getDefault() .getPathMatcher("glob:*.tmp"); @@ -27,7 +27,7 @@ public class Find { .map(Path::getFileName) .filter(matcher2::matches) .forEach(System.out::println); - System.out.println("***************"); + System.out.println("***************DONE 2"); Files.walk(test) // Only look for files .filter(Files::isRegularFile) diff --git a/files/PartsOfPaths.java b/files/PartsOfPaths.java index 1170fc688..d699ddcb6 100644 --- a/files/PartsOfPaths.java +++ b/files/PartsOfPaths.java @@ -6,19 +6,25 @@ public class PartsOfPaths { public static void main(String[] args) { - System.out.println(System.getProperty("os.name")); - Path p = - Paths.get("PartsOfPaths.java").toAbsolutePath(); - for(int i = 0; i < p.getNameCount(); i++) - System.out.println(p.getName(i)); - System.out.println("ends with '.java': " + - p.endsWith(".java")); + System.err.println(System.getProperty("os.name")); + Path p = Paths.get("PartsOfPaths.java").toAbsolutePath(); + System.err.println(p); + System.err.println(Files.exists(p)); + + for(int i = 0; i < p.getNameCount(); i++) { + System.err.println("第" + i + "部分--"+p.getName(i)); + } + + + System.err.println("ends with '.java'1: " + p.endsWith(".java")); + System.err.println("ends with '.java'2: " + p.endsWith("PartsOfPaths.java")); + for(Path pp : p) { - System.out.print(pp + ": "); - System.out.print(p.startsWith(pp) + " : "); - System.out.println(p.endsWith(pp)); + System.err.print(pp + ": "); + System.err.print(p.startsWith(pp) + " : "); + System.err.println(p.endsWith(pp)); } - System.out.println("Starts with " + p.getRoot() + + System.err.println("Starts with " + p.getRoot() + " " + p.startsWith(p.getRoot())); } } diff --git a/files/PathAnalysis.java b/files/PathAnalysis.java index 117119cdd..fb0adf81d 100644 --- a/files/PathAnalysis.java +++ b/files/PathAnalysis.java @@ -7,12 +7,12 @@ public class PathAnalysis { static void say(String id, Object result) { - System.out.print(id + ": "); - System.out.println(result); + System.err.print(id + ": "); + System.err.println(result); } public static void main(String[] args) throws IOException { - System.out.println(System.getProperty("os.name")); + System.err.println(System.getProperty("os.name")); Path p = Paths.get("PathAnalysis.java").toAbsolutePath(); say("Exists", Files.exists(p)); diff --git a/files/PathInfo.java b/files/PathInfo.java index 96af9d938..67f579316 100644 --- a/files/PathInfo.java +++ b/files/PathInfo.java @@ -9,7 +9,7 @@ public class PathInfo { static void show(String id, Object p) { - System.out.println(id + ": " + p); + System.err.println(id + ": " + p); } static void info(Path p) { show("toString", p); @@ -20,27 +20,36 @@ static void info(Path p) { show("FileName", p.getFileName()); show("Parent", p.getParent()); show("Root", p.getRoot()); - System.out.println("******************"); + System.err.println("******************"); } public static void main(String[] args) { - System.out.println(System.getProperty("os.name")); + System.err.println(System.getProperty("os.name")); + info(Paths.get( "C:", "path", "to", "nowhere", "NoFile.txt")); + Path p = Paths.get("PathInfo.java"); info(p); + Path ap = p.toAbsolutePath(); info(ap); + info(ap.getParent()); + try { info(p.toRealPath()); } catch(IOException e) { - System.out.println(e); + System.err.println(e); } + URI u = p.toUri(); - System.out.println("URI: " + u); + System.err.println("URI: " + u); + Path puri = Paths.get(u); - System.out.println(Files.exists(puri)); - File f = ap.toFile(); // Don't be fooled + System.err.println(Files.exists(puri)); + + File f = ap.toFile(); // Don't be fooled //self-note: 这是 java.io.File的产物, 和nio.file无关; + System.err.println("|||"+f); } } /* Output: diff --git a/files/PathWatcher.java b/files/PathWatcher.java index 162641d72..b88f57a99 100644 --- a/files/PathWatcher.java +++ b/files/PathWatcher.java @@ -17,7 +17,7 @@ static void delTxtFiles() { f.toString().endsWith(".txt")) .forEach(f -> { try { - System.out.println("deleting " + f); + System.err.println("deleting " + f); Files.delete(f); } catch(IOException e) { throw new RuntimeException(e); @@ -27,21 +27,23 @@ static void delTxtFiles() { throw new RuntimeException(e); } } - public static void - main(String[] args) throws Exception { + public static void main(String[] args) throws Exception { Directories.refreshTestDir(); Directories.populateTestDir(); Files.createFile(test.resolve("Hello.txt")); - WatchService watcher = - FileSystems.getDefault().newWatchService(); + WatchService watcher = FileSystems.getDefault().newWatchService(); test.register(watcher, ENTRY_DELETE); + Executors.newSingleThreadScheduledExecutor() - .schedule( - PathWatcher::delTxtFiles, - 250, TimeUnit.MILLISECONDS); - WatchKey key = watcher.take(); + .schedule( + PathWatcher::delTxtFiles, + 5, TimeUnit.SECONDS); + // delTxtFiles(); + WatchKey key = watcher.take(); + + for(WatchEvent evt : key.pollEvents()) { - System.out.println( + System.err.println( "evt.context(): " + evt.context() + "\nevt.count(): " + evt.count() + "\nevt.kind(): " + evt.kind()); diff --git a/files/RmDir.java b/files/RmDir.java new file mode 100644 index 000000000..8701a2b8b --- /dev/null +++ b/files/RmDir.java @@ -0,0 +1,29 @@ +// onjava/RmDir.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +//package onjava; + +import java.io.IOException; +import java.nio.file.FileVisitResult; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.SimpleFileVisitor; +import java.nio.file.attribute.BasicFileAttributes; + +public class RmDir { + public static void rmdir(Path dir) throws IOException { + Files.walkFileTree(dir, new SimpleFileVisitor() { + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { + Files.delete(file); + return FileVisitResult.CONTINUE; + } + @Override + public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { + Files.delete(dir); + return FileVisitResult.CONTINUE; + } + }); + } +} diff --git a/files/StreamInAndOut.java b/files/StreamInAndOut.java index ec17c7008..5fe34e182 100644 --- a/files/StreamInAndOut.java +++ b/files/StreamInAndOut.java @@ -9,10 +9,8 @@ public class StreamInAndOut { public static void main(String[] args) { try( - Stream input = - Files.lines(Paths.get("StreamInAndOut.java")); - PrintWriter output = - new PrintWriter("StreamInAndOut.txt") + Stream input = Files.lines(Paths.get("./files/StreamInAndOut.java")); + PrintWriter output = new PrintWriter("./files/StreamInAndOut.txt") ) { input .map(String::toUpperCase) @@ -21,4 +19,4 @@ public static void main(String[] args) { throw new RuntimeException(e); } } -} +}Immutable diff --git a/files/TreeWatcher.java b/files/TreeWatcher.java index f0660888d..d850a402b 100644 --- a/files/TreeWatcher.java +++ b/files/TreeWatcher.java @@ -9,7 +9,9 @@ import java.util.concurrent.*; public class TreeWatcher { + static int i=1; static void watchDir(Path dir) { + System.err.println("树" + i++);//self-note: 开了十七个额外线程,每个线程监听一个子目录! try { WatchService watcher = FileSystems.getDefault().newWatchService(); @@ -18,7 +20,7 @@ static void watchDir(Path dir) { try { WatchKey key = watcher.take(); for(WatchEvent evt : key.pollEvents()) { - System.out.println( + System.err.println( "evt.context(): " + evt.context() + "\nevt.count(): " + evt.count() + "\nevt.kind(): " + evt.kind()); @@ -32,8 +34,7 @@ static void watchDir(Path dir) { throw new RuntimeException(e); } } - public static void - main(String[] args) throws Exception { + public static void main(String[] args) throws Exception { Directories.refreshTestDir(); Directories.populateTestDir(); Files.walk(Paths.get("test")) diff --git a/files/Writing.java b/files/Writing.java index 68a04fbcd..13b328ffe 100644 --- a/files/Writing.java +++ b/files/Writing.java @@ -8,20 +8,19 @@ public class Writing { static Random rand = new Random(47); static final int SIZE = 1000; - public static void - main(String[] args) throws Exception { + public static void main(String[] args) throws Exception { // Write bytes to a file: byte[] bytes = new byte[SIZE]; rand.nextBytes(bytes); Files.write(Paths.get("bytes.dat"), bytes); - System.out.println("bytes.dat: " + + System.err.println("bytes.dat: " + Files.size(Paths.get("bytes.dat"))); // Write an iterable to a file: List lines = Files.readAllLines( - Paths.get("../streams/Cheese.dat")); + Paths.get("./streams/Cheese.dat"));////self-note: 相对路径 写法... Files.write(Paths.get("Cheese.txt"), lines); - System.out.println("Cheese.txt: " + + System.err.println("Cheese.txt: " + Files.size(Paths.get("Cheese.txt"))); } } diff --git a/functional/AnonymousClosure.java b/functional/AnonymousClosure.java index 497a1a526..b2c9ac06b 100644 --- a/functional/AnonymousClosure.java +++ b/functional/AnonymousClosure.java @@ -5,13 +5,51 @@ import java.util.function.*; public class AnonymousClosure { + //fun1 IntSupplier makeFun(int x) { int i = 0; - // Same rules apply: - // i++; // Not "effectively final" - // x++; // Ditto + return () -> x + i; + } + + //fun2 是fun1的繁写 + IntSupplier makeFun2(int x) { + int i = 0; return new IntSupplier() { + @Override public int getAsInt() { return x + i; } }; } + + /** + * + * x和i是方法的局部变量, 但是匿名内部类用到了这些变量,而局部变量生命周期短于 内部类, 导致 变量 发生变化 + * + * self-note: + * 内部类和外部类是处于同一个级别的,内部类不会因为定义在方法中,就会随着方法的执行完毕就被销毁. + * 这里就会产生问题: + * 当外部类的方法结束时,局部变量就会被销毁了,但是内部类对象可能还存在(只有没有人再引用它时,才会死亡)。 + * 这里就出现了一个矛盾:内部类对象访问了一个不存在的变量。 + * + * + * 为了妥协, 将局部变量复制了一份作为内部类的成员变量 确保相同的生命周期; + * 这样当局部变量死亡后,内部类仍可以访问它,实际访问的是局部变量的"copy"。 + * 如果我们在内部类中修改了成员变量,方法中的局部变量也得跟着改变,怎么解决问题呢? + * 再次为了妥协, 变量都必须为final,都不可变. + * + * + * 总而言之, java机制帮我们解决了外层方法局部变量作为内部类成员引用时生命周期的问题:复制外层方法局部变量,构造方法再把拷贝赋值给类成员变量; + * 此时可能导致数据不同步,因此要用final修饰. + * + * + * 实际上只要有内部类,就会有闭包(Java 8 只是简化了闭包操作)。 + * 在 Java 8 之前,变量 `x` 和 `i` 必须被明确声明为 `final`。在 Java 8 中,内部类的规则放宽,包括**等同 final 效果**。 + * + * + * 严格来说,闭包需要满足三个条件:【1】访问所在作用域;【2】函数嵌套;【3】在所在作用域外被调用 + * + * 有些人觉得只满足条件1就可以,所以IIFE(立即调用函数表达式)是闭包; + * 有些人觉得满足条件1和2才可以,所以被嵌套的函数才是闭包; + * 有些人觉得3个条件都满足才可以,所以在作用域以外的地方被调用的函数才是闭包 + */ + } diff --git a/functional/BiConsumerPermutations.java b/functional/BiConsumerPermutations.java index 75b7c32d5..9fa38fe93 100644 --- a/functional/BiConsumerPermutations.java +++ b/functional/BiConsumerPermutations.java @@ -6,11 +6,11 @@ public class BiConsumerPermutations { static BiConsumer bicid = (i, d) -> - System.out.format("%d, %f%n", i, d); + System.err.format("%d, %f%n", i, d); static BiConsumer bicdi = (d, i) -> - System.out.format("%d, %f%n", i, d); + System.err.format("%d, %f%n", i, d); static BiConsumer bicil = (i, l) -> - System.out.format("%d, %d%n", i, l); + System.err.format("%d, %d%n", i, l); public static void main(String[] args) { bicid.accept(47, 11.34); bicdi.accept(22.45, 92); diff --git a/functional/Closure1.java b/functional/Closure1.java index 2f504f42c..168752d66 100644 --- a/functional/Closure1.java +++ b/functional/Closure1.java @@ -2,7 +2,9 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -import java.util.function.*; +//import java.util.function.*; + +import java.util.function.IntSupplier; public class Closure1 { int i; diff --git a/functional/Closure8.java b/functional/Closure8.java index 7ec059b2a..5247888c1 100644 --- a/functional/Closure8.java +++ b/functional/Closure8.java @@ -16,12 +16,12 @@ public static void main(String[] args) { List l1 = c7.makeFun().get(), l2 = c7.makeFun().get(); - System.out.println(l1); - System.out.println(l2); + System.err.println(l1); + System.err.println(l2); l1.add(42); l2.add(96); - System.out.println(l1); - System.out.println(l2); + System.err.println(l1); + System.err.println(l2); } } /* Output: diff --git a/functional/CurriedIntAdd.java b/functional/CurriedIntAdd.java index e89ac8e28..b3d88187f 100644 --- a/functional/CurriedIntAdd.java +++ b/functional/CurriedIntAdd.java @@ -9,7 +9,7 @@ public static void main(String[] args) { IntFunction curriedIntAdd = a -> b -> a + b; IntUnaryOperator add4 = curriedIntAdd.apply(4); - System.out.println(add4.applyAsInt(5)); + System.err.println(add4.applyAsInt(5)); } } /* Output: diff --git a/functional/Curry3Args.java b/functional/Curry3Args.java index 0fd376bc2..d69dab961 100644 --- a/functional/Curry3Args.java +++ b/functional/Curry3Args.java @@ -15,7 +15,7 @@ public static void main(String[] args) { sum.apply("Hi "); Function ho = hi.apply("Ho "); - System.out.println(ho.apply("Hup")); + System.err.println(ho.apply("Hup")); } } /* Output: diff --git a/functional/CurryingAndPartials.java b/functional/CurryingAndPartials.java index 0addb8115..de9aceadf 100644 --- a/functional/CurryingAndPartials.java +++ b/functional/CurryingAndPartials.java @@ -2,30 +2,34 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. + import java.util.function.*; public class CurryingAndPartials { - // Uncurried: - static String uncurried(String a, String b) { - return a + b; - } - public static void main(String[] args) { - // Curried function: - Function> sum = - a -> b -> a + b; // [1] - - System.out.println(uncurried("Hi ", "Ho")); - - Function - hi = sum.apply("Hi "); // [2] - System.out.println(hi.apply("Ho")); - - // Partial application: - Function sumHi = - sum.apply("Hup "); - System.out.println(sumHi.apply("Ho")); - System.out.println(sumHi.apply("Hey")); - } + // Uncurried: + static String uncurried(String a, String b) { + return a + b; + } + + public static void main(String[] args) { + System.err.println(uncurried("Hi ", "Ho")); + + // Curried function: + Function> sum = a -> b -> a + b; // [1] + + Function hi = sum.apply("Hi "); // [2] + String ho = hi.apply("Ho"); + System.err.println(ho); + + + System.err.println(sum.apply("A ").apply("B")); + + // Partial application: + Function sumHi = sum.apply("Hup "); + + System.err.println(sumHi.apply("Ho")); + System.err.println(sumHi.apply("Hey")); + } } /* Output: Hi Ho diff --git a/functional/FunctionComposition.java b/functional/FunctionComposition.java index a183039d0..383c73757 100644 --- a/functional/FunctionComposition.java +++ b/functional/FunctionComposition.java @@ -7,14 +7,14 @@ public class FunctionComposition { static Function f1 = s -> { - System.out.println(s); + System.err.println(s); return s.replace('A', '_'); }, f2 = s -> s.substring(3), f3 = s -> s.toLowerCase(), f4 = f1.compose(f2).andThen(f3); public static void main(String[] args) { - System.out.println( + System.err.println( f4.apply("GO AFTER ALL AMBULANCES")); } } diff --git a/functional/LambdaExpressions.java b/functional/LambdaExpressions.java index fe7e3acb1..25e6c8d77 100644 --- a/functional/LambdaExpressions.java +++ b/functional/LambdaExpressions.java @@ -26,16 +26,16 @@ public class LambdaExpressions { static Multi mult = (h, n) -> h + n; // [4] static Description moreLines = () -> { // [5] - System.out.println("moreLines()"); + System.err.println("moreLines()"); return "from moreLines()"; }; public static void main(String[] args) { - System.out.println(bod.detailed("Oh!")); - System.out.println(bod2.detailed("Hi!")); - System.out.println(desc.brief()); - System.out.println(mult.twoArg("Pi! ", 3.14159)); - System.out.println(moreLines.brief()); + System.err.println(bod.detailed("Oh!")); + System.err.println(bod2.detailed("Hi!")); + System.err.println(desc.brief()); + System.err.println(mult.twoArg("Pi! ", 3.14159)); + System.err.println(moreLines.brief()); } } /* Output: diff --git a/functional/MethodConversion.java b/functional/MethodConversion.java index 008ecfc0c..461d8d799 100644 --- a/functional/MethodConversion.java +++ b/functional/MethodConversion.java @@ -9,10 +9,10 @@ class In2 {} public class MethodConversion { static void accept(In1 i1, In2 i2) { - System.out.println("accept()"); + System.err.println("accept()"); } static void someOtherName(In1 i1, In2 i2) { - System.out.println("someOtherName()"); + System.err.println("someOtherName()"); } public static void main(String[] args) { BiConsumer bic; @@ -21,7 +21,7 @@ public static void main(String[] args) { bic.accept(new In1(), new In2()); bic = MethodConversion::someOtherName; - // bic.someOtherName(new In1(), new In2()); // Nope +// bic.someOtherName(new In1(), new In2()); // Nope bic.accept(new In1(), new In2()); } } diff --git a/functional/MethodReferences.java b/functional/MethodReferences.java index 63bc365d8..e75516f5b 100644 --- a/functional/MethodReferences.java +++ b/functional/MethodReferences.java @@ -7,41 +7,50 @@ interface Callable { // [1] void call(String s); } - +interface Callable2 { + void call2(Describe describe,String msg); //非绑定方法引用 的 接口, 要求第一个参数是 this对象 的 类型, 并传入该对象。 +} class Describe { void show(String msg) { // [2] - System.out.println(msg); + System.err.println(msg); } } public class MethodReferences { static void hello(String name) { // [3] - System.out.println("Hello, " + name); + System.err.println("Hello, " + name); } static class Description { String about; Description(String desc) { about = desc; } void help(String msg) { // [4] - System.out.println(about + " " + msg); + System.err.println(about + " " + msg); } } static class Helper { static void assist(String msg) { // [5] - System.out.println(msg); + System.err.println(msg); } } + //self-note: public static void main(String[] args) { Describe d = new Describe(); - Callable c = d::show; // [6] + Callable c = d::show; // [6] 我们将 **Describe** 对象的方法引用赋值给 **Callable** c.call("call()"); // [7] - c = MethodReferences::hello; // [8] + Callable2 c2 = Describe::show; // 非绑定方法引用,类似静态方法引用的写法,但是要求传入this对象。 + c2.call2(d,"非绑定方法引用。"); + + + + + c = MethodReferences::hello; // [8] 这是一个**静态**方法引用。 c.call("Bob"); - c = new Description("valuable")::help; // [9] + c = new Description("valuable")::help; // [9] 这是 **[6]** 的另一个版本:对已实例化对象的方法的引用,有时称为*绑定方法引用*。 c.call("information"); - c = Helper::assist; // [10] + c = Helper::assist; // [10] **[10]** 最后,获取静态内部类中静态方法的引用与 **[8]** 中通过外部类引用相似。 c.call("Help!"); } } diff --git a/functional/ProduceFunction.java b/functional/ProduceFunction.java index 034716011..4605da2c5 100644 --- a/functional/ProduceFunction.java +++ b/functional/ProduceFunction.java @@ -2,19 +2,22 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. + import java.util.function.*; -interface -FuncSS extends Function {} // [1] +interface FuncSS extends Function { +} // [1] public class ProduceFunction { - static FuncSS produce() { - return s -> s.toLowerCase(); // [2] - } - public static void main(String[] args) { - FuncSS f = produce(); - System.out.println(f.apply("YELLING")); - } + static FuncSS produce() { + return s -> s.toLowerCase(); //self-note: produce()是高阶函数, 意思是一个消费或返回函数的函数。 + // [2] + } + + public static void main(String[] args) { + FuncSS f = produce(); + System.err.println(f.apply("YELLING")); + } } /* Output: yelling diff --git a/functional/RecursiveFactorial.java b/functional/RecursiveFactorial.java index 2d6104413..b5cb56d5b 100644 --- a/functional/RecursiveFactorial.java +++ b/functional/RecursiveFactorial.java @@ -8,7 +8,7 @@ public class RecursiveFactorial { public static void main(String[] args) { fact = n -> n == 0 ? 1 : n * fact.call(n - 1); for(int i = 0; i <= 10; i++) - System.out.println(fact.call(i)); + System.err.println(fact.call(i)); } } /* Output: diff --git a/functional/RecursiveFibonacci.java b/functional/RecursiveFibonacci.java index 9be43dc62..7938c7dc8 100644 --- a/functional/RecursiveFibonacci.java +++ b/functional/RecursiveFibonacci.java @@ -14,7 +14,7 @@ public class RecursiveFibonacci { public static void main(String[] args) { RecursiveFibonacci rf = new RecursiveFibonacci(); for(int i = 0; i <= 10; i++) - System.out.println(rf.fibonacci(i)); + System.err.println(rf.fibonacci(i)); } } /* Output: diff --git a/functional/RunnableMethodReference.java b/functional/RunnableMethodReference.java index 5fb8cd002..e6709cad6 100644 --- a/functional/RunnableMethodReference.java +++ b/functional/RunnableMethodReference.java @@ -5,26 +5,46 @@ // Method references with interface Runnable class Go { - static void go() { - System.out.println("Go::go()"); - } + static void go() { + System.err.println("Go::go()"); + } +} +class MyThread implements Runnable{ + private String name; + public MyThread(String name){ + this.name=name; + } + @Override + public void run() { + for (int i = 0; i < 20; i++) { + System.err.print(this.name+"==>"+i); + } + System.err.println(); + } } - public class RunnableMethodReference { - public static void main(String[] args) { - new Thread(new Runnable() { - public void run() { - System.out.println("Anonymous"); - } - }).start(); + public static void main(String[] args) { + new Thread(new MyThread("a")).start(); + + + + new Thread( + new Runnable() { + @Override + public void run() { + System.err.println("Anonymous"); + } + } + ).start(); - new Thread( - () -> System.out.println("lambda") - ).start(); + new Thread( + //self-note: 上面的简写 + () -> System.err.println("lambda") + ).start(); - new Thread(Go::go).start(); - } + new Thread(Go::go).start(); + } } /* Output: Anonymous diff --git a/functional/SharedStorage.java b/functional/SharedStorage.java index c2a41f66a..17e023a90 100644 --- a/functional/SharedStorage.java +++ b/functional/SharedStorage.java @@ -7,12 +7,12 @@ public class SharedStorage { public static void main(String[] args) { Closure1 c1 = new Closure1(); - IntSupplier f1 = c1.makeFun(0); + System.err.println( c1.makeFun(0).getAsInt()); IntSupplier f2 = c1.makeFun(0); IntSupplier f3 = c1.makeFun(0); - System.out.println(f1.getAsInt()); - System.out.println(f2.getAsInt()); - System.out.println(f3.getAsInt()); +// System.err.println(f1.getAsInt()); + System.err.println(f2.getAsInt()); + System.err.println(f3.getAsInt()); } } /* Output: diff --git a/functional/Strategize.java b/functional/Strategize.java index e46c91434..16ff808cb 100644 --- a/functional/Strategize.java +++ b/functional/Strategize.java @@ -8,6 +8,7 @@ interface Strategy { } class Soft implements Strategy { + @Override public String approach(String msg) { return msg.toLowerCase() + "?"; } @@ -27,26 +28,34 @@ public class Strategize { this.msg = msg; } void communicate() { - System.out.println(strategy.approach(msg)); + System.err.println(strategy.approach(msg)); } void changeStrategy(Strategy strategy) { this.strategy = strategy; } + + public static void main(String[] args) { Strategy[] strategies = { + + //fun1 new Strategy() { // [2] + @Override public String approach(String msg) { return msg.toUpperCase() + "!"; } }, + //fun1的简写 msg -> msg.toUpperCase() + "!", msg -> msg.substring(0, 5), // [3] Unrelated::twice // [4] }; Strategize s = new Strategize("Hello there"); - s.communicate(); + s.communicate(); //最原始 + + for(Strategy newStrategy : strategies) { s.changeStrategy(newStrategy); // [5] - s.communicate(); // [6] + s.communicate(); // [6] //余下的几种 } } } diff --git a/functional/TransformFunction.java b/functional/TransformFunction.java index 1a046eb12..62d6375c8 100644 --- a/functional/TransformFunction.java +++ b/functional/TransformFunction.java @@ -17,16 +17,20 @@ class O { public class TransformFunction { static Function transform(Function in) { return in.andThen(o -> { - System.out.println(o); + System.err.println(o); return o; }); } public static void main(String[] args) { Function f2 = transform(i -> { - System.out.println(i); + System.err.println(i); return new O(); }); O o = f2.apply(new I()); + //self-note: + /** + * 在这里,运行高阶函数f2,然后会运行传入的函数in,其结果再运行andThen()部分. + */ } } /* Output: diff --git a/functional/TriFunctionTest.java b/functional/TriFunctionTest.java index fccf8b9a2..b48376510 100644 --- a/functional/TriFunctionTest.java +++ b/functional/TriFunctionTest.java @@ -6,8 +6,12 @@ public class TriFunctionTest { static int f(int i, long l, double d) { return 99; } public static void main(String[] args) { + TriFunction tf = TriFunctionTest::f; + tf = (i, l, d) -> 12; + //self-note: 这里我们同时测试了方法引用和 Lambda 表达式。 + } } diff --git a/functional/UnboundMethodReference.java b/functional/UnboundMethodReference.java index da2c78729..8046868f2 100644 --- a/functional/UnboundMethodReference.java +++ b/functional/UnboundMethodReference.java @@ -4,25 +4,42 @@ // Visit http://OnJava8.com for more book information. // Method reference without an object +interface MakeString { + String make(); +} + class X { String f() { return "X::f()"; } } -interface MakeString { +interface MakeString2 { String make(); } +class X2 { + String f() { + System.err.println("success!"); + return "success!"; + } +} + interface TransformX { String transform(X x); } public class UnboundMethodReference { public static void main(String[] args) { - // MakeString ms = X::f; // [1] - TransformX sp = X::f; - X x = new X(); - System.out.println(sp.transform(x)); // [2] - System.out.println(x.f()); // Same effect + + X2 x2 = new X2(); +// MakeString2 c = X2::f; 没有实例 + MakeString2 c = x2::f; + c.make(); + +// MakeString ms = X::f; // [1] self-note: 这个是大写的X,不是上面例子的小写d了,没有实例,因此其实需要一个实例用作参数. + TransformX sp = X::f; //总之静态方法引用 X::f 写法是需要多一个参数,要么就用非静态的方法引用 x2::f + X x3 = new X(); + System.err.println(sp.transform(x3)); // [2] + System.err.println(x3.f()); // Same effect } } /* Output: diff --git a/generics/Apply.java b/generics/Apply.java index c93786113..dd38b9d84 100644 --- a/generics/Apply.java +++ b/generics/Apply.java @@ -8,6 +8,7 @@ public class Apply { public static > void apply(S seq, Method f, Object... args) { + System.err.println("---------apply------"); try { for(T t: seq) f.invoke(t, args); diff --git a/generics/ApplyFunctional.java b/generics/ApplyFunctional.java index 4cce156e8..94507ef1d 100644 --- a/generics/ApplyFunctional.java +++ b/generics/ApplyFunctional.java @@ -2,32 +2,38 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. + import java.util.*; import java.util.stream.*; import java.util.function.*; -import onjava.*; +//import onjava.*; public class ApplyFunctional { - public static void main(String[] args) { - Stream.of( - Stream.generate(Shape::new).limit(2), - Stream.generate(Square::new).limit(2)) - .flatMap(c -> c) // flatten into one stream - .peek(Shape::rotate) - .forEach(s -> s.resize(7)); + public static void main(String[] args) { + Stream.of( + Stream.generate(Shape::new).limit(2), + Stream.generate(Square::new).limit(2)) + .flatMap(c -> c) // flatten into one stream + .peek(Shape::rotate) + .forEach(s -> s.resize(7)); + + new FilledList<>(Shape::new, 2) + .forEach(Shape::rotate); + /* new FilledList<>(Square::new, 2) + .forEach(Shape::rotate);*/ + + System.err.println("------------------ 1 ----------------"); + SimpleQueue shapeQ = Suppliers.fill( + new SimpleQueue<>(), SimpleQueue::add, + Shape::new, 2); + System.err.println("------------------ 2 ----------------"); - new FilledList<>(Shape::new, 2) - .forEach(Shape::rotate); - new FilledList<>(Square::new, 2) - .forEach(Shape::rotate); + Suppliers.fill(shapeQ, SimpleQueue::add, + Square::new, 2); + System.err.println("------------------ 3 ----------------"); - SimpleQueue shapeQ = Suppliers.fill( - new SimpleQueue<>(), SimpleQueue::add, - Shape::new, 2); - Suppliers.fill(shapeQ, SimpleQueue::add, - Square::new, 2); - shapeQ.forEach(Shape::rotate); - } + shapeQ.forEach(Shape::rotate); + } } /* Output: Shape 0 rotate diff --git a/generics/ApplyTest.java b/generics/ApplyTest.java index 62ef4eecf..31e86821d 100644 --- a/generics/ApplyTest.java +++ b/generics/ApplyTest.java @@ -4,11 +4,10 @@ // Visit http://OnJava8.com for more book information. import java.util.*; import java.util.function.*; -import onjava.*; +//import onjava.*; public class ApplyTest { - public static - void main(String[] args) throws Exception { + public static void main(String[] args) throws Exception { List shapes = Suppliers.create(ArrayList::new, Shape::new, 3); Apply.apply(shapes, @@ -16,6 +15,9 @@ void main(String[] args) throws Exception { Apply.apply(shapes, Shape.class.getMethod("resize", int.class), 7); + System.err.println("-------------------1"); + + List squares = Suppliers.create(ArrayList::new, Square::new, 3); Apply.apply(squares, @@ -23,6 +25,9 @@ void main(String[] args) throws Exception { Apply.apply(squares, Shape.class.getMethod("resize", int.class), 7); + System.err.println("-------------------2"); + + Apply.apply(new FilledList<>(Shape::new, 3), Shape.class.getMethod("rotate")); Apply.apply(new FilledList<>(Square::new, 3), diff --git a/generics/ArrayMaker.java b/generics/ArrayMaker.java index f1bb6b9a4..d8197cdfa 100644 --- a/generics/ArrayMaker.java +++ b/generics/ArrayMaker.java @@ -16,7 +16,7 @@ public static void main(String[] args) { ArrayMaker stringMaker = new ArrayMaker<>(String.class); String[] stringArray = stringMaker.create(9); - System.out.println(Arrays.toString(stringArray)); + System.err.println(Arrays.toString(stringArray)); } } /* Output: diff --git a/generics/ArrayOfGeneric.java b/generics/ArrayOfGeneric.java index 67e6cb97c..cca516125 100644 --- a/generics/ArrayOfGeneric.java +++ b/generics/ArrayOfGeneric.java @@ -11,11 +11,11 @@ public static void main(String[] args) { try { gia = (Generic[])new Object[SIZE]; } catch(ClassCastException e) { - System.out.println(e.getMessage()); + System.err.println("异常1:"+e.getMessage()); } // Runtime type is the raw (erased) type: gia = (Generic[])new Generic[SIZE]; - System.out.println(gia.getClass().getSimpleName()); + System.err.println("222: "+gia.getClass().getSimpleName()); gia[0] = new Generic<>(); //- gia[1] = new Object(); // Compile-time error // Discovers type mismatch at compile time: diff --git a/generics/BankTeller.java b/generics/BankTeller.java index 68301996d..c0003a249 100644 --- a/generics/BankTeller.java +++ b/generics/BankTeller.java @@ -34,7 +34,7 @@ public void put(BankTeller bt) { public class BankTeller { public static void serve(Teller t, Customer c) { - System.out.println(t + " serves " + c); + System.err.println(t + " serves " + c); } public static void main(String[] args) { // Demonstrate create(): diff --git a/generics/BasicBounds.java b/generics/BasicBounds.java index 434d0fd8f..1b9ff95bf 100644 --- a/generics/BasicBounds.java +++ b/generics/BasicBounds.java @@ -17,6 +17,8 @@ class Coord { public int x, y, z; } // This fails. Class must be first, then interfaces: // class WithColorCoord { +// +// } // Multiple bounds: class WithColorCoord { @@ -44,8 +46,11 @@ class Solid { int weight() { return item.weight(); } } -class Bounded -extends Coord implements HasColor, Weight { +class Bounded extends Coord implements HasColor, Weight { + public Bounded() { + System.err.println("Bounded 构造器"); + } + @Override public java.awt.Color getColor() { return null; } @Override diff --git a/generics/BasicHolder.java b/generics/BasicHolder.java index 2b8b8a9b1..b6c008122 100644 --- a/generics/BasicHolder.java +++ b/generics/BasicHolder.java @@ -8,7 +8,7 @@ public class BasicHolder { void set(T arg) { element = arg; } T get() { return element; } void f() { - System.out.println( + System.err.println( element.getClass().getSimpleName()); } } diff --git a/generics/CaptureConversion.java b/generics/CaptureConversion.java index 163484682..da6c0fe9f 100644 --- a/generics/CaptureConversion.java +++ b/generics/CaptureConversion.java @@ -6,7 +6,7 @@ public class CaptureConversion { static void f1(Holder holder) { T t = holder.get(); - System.out.println(t.getClass().getSimpleName()); + System.err.println(t.getClass().getSimpleName()); } static void f2(Holder holder) { f1(holder); // Call with captured type diff --git a/generics/Cat.java b/generics/Cat.java new file mode 100644 index 000000000..2dd8d154b --- /dev/null +++ b/generics/Cat.java @@ -0,0 +1,9 @@ +// typeinfo/pets/Cat.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. + +public class Cat extends Pet { + public Cat(String name) { super(name); } + public Cat() { super(); } +} diff --git a/generics/CheckedList.java b/generics/CheckedList.java index 6e330cf6b..5f40b9393 100644 --- a/generics/CheckedList.java +++ b/generics/CheckedList.java @@ -3,7 +3,7 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Using Collection.checkedList() -import typeinfo.pets.*; +//import typeinfo.pets.*; import java.util.*; public class CheckedList { @@ -19,7 +19,7 @@ public static void main(String[] args) { try { oldStyleMethod(dogs2); // Throws an exception } catch(Exception e) { - System.out.println("Expected: " + e); + System.err.println("Expected: " + e); } // Derived types work fine: List pets = Collections.checkedList( diff --git a/generics/ClassTypeCapture.java b/generics/ClassTypeCapture.java index ab193dfe6..d6779b881 100644 --- a/generics/ClassTypeCapture.java +++ b/generics/ClassTypeCapture.java @@ -17,12 +17,12 @@ public boolean f(Object arg) { public static void main(String[] args) { ClassTypeCapture ctt1 = new ClassTypeCapture<>(Building.class); - System.out.println(ctt1.f(new Building())); - System.out.println(ctt1.f(new House())); + System.err.println(ctt1.f(new Building())); + System.err.println(ctt1.f(new House())); ClassTypeCapture ctt2 = new ClassTypeCapture<>(House.class); - System.out.println(ctt2.f(new Building())); - System.out.println(ctt2.f(new House())); + System.err.println(ctt2.f(new Building())); + System.err.println(ctt2.f(new House())); } } /* Output: diff --git a/generics/CovariantArrays.java b/generics/CovariantArrays.java index e202ca079..a7d8b0e2b 100644 --- a/generics/CovariantArrays.java +++ b/generics/CovariantArrays.java @@ -3,26 +3,37 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -class Fruit {} -class Apple extends Fruit {} -class Jonathan extends Apple {} -class Orange extends Fruit {} +class Fruit { +} + +class Apple extends Fruit { +} + +class Jonathan extends Apple { +} + +class Orange extends Fruit { +} public class CovariantArrays { - public static void main(String[] args) { - Fruit[] fruit = new Apple[10]; - fruit[0] = new Apple(); // OK - fruit[1] = new Jonathan(); // OK - // Runtime type is Apple[], not Fruit[] or Orange[]: - try { - // Compiler allows you to add Fruit: - fruit[0] = new Fruit(); // ArrayStoreException - } catch(Exception e) { System.out.println(e); } - try { - // Compiler allows you to add Oranges: - fruit[0] = new Orange(); // ArrayStoreException - } catch(Exception e) { System.out.println(e); } - } + public static void main(String[] args) { + Fruit[] fruit = new Apple[10]; + fruit[0] = new Apple(); // OK + fruit[1] = new Jonathan(); // OK + // Runtime type is Apple[], not Fruit[] or Orange[]: + try { + // Compiler allows you to add Fruit: + fruit[0] = new Fruit(); // ArrayStoreException + } catch (Exception e) { + System.err.println(e); + } + try { + // Compiler allows you to add Oranges: + fruit[0] = new Orange(); // ArrayStoreException + } catch (Exception e) { + System.err.println(e); + } + } } /* Output: java.lang.ArrayStoreException: Fruit diff --git a/generics/CreatorGeneric.java b/generics/CreatorGeneric.java index 7fd90df46..3bf9ce44c 100644 --- a/generics/CreatorGeneric.java +++ b/generics/CreatorGeneric.java @@ -15,7 +15,7 @@ class XCreator extends GenericWithCreate { @Override X create() { return new X(); } void f() { - System.out.println( + System.err.println( element.getClass().getSimpleName()); } } diff --git a/generics/Dog.java b/generics/Dog.java new file mode 100644 index 000000000..8deda5e86 --- /dev/null +++ b/generics/Dog.java @@ -0,0 +1,9 @@ +// typeinfo/pets/Dog.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. + +public class Dog extends Pet { + public Dog(String name) { super(name); } + public Dog() { super(); } +} diff --git a/generics/DogsAndRobotMethodReferences.java b/generics/DogsAndRobotMethodReferences.java index 7c3fa3575..ddf9562da 100644 --- a/generics/DogsAndRobotMethodReferences.java +++ b/generics/DogsAndRobotMethodReferences.java @@ -7,14 +7,14 @@ import java.util.function.*; class PerformingDogA extends Dog { - public void speak() { System.out.println("Woof!"); } - public void sit() { System.out.println("Sitting"); } + public void speak() { System.err.println("Woof!"); } + public void sit() { System.err.println("Sitting"); } public void reproduce() {} } class RobotA { - public void speak() { System.out.println("Click!"); } - public void sit() { System.out.println("Clank!"); } + public void speak() { System.err.println("Click!"); } + public void sit() { System.err.println("Clank!"); } public void oilChange() {} } diff --git a/generics/DogsAndRobots.java b/generics/DogsAndRobots.java index b61511227..951fe0dc6 100644 --- a/generics/DogsAndRobots.java +++ b/generics/DogsAndRobots.java @@ -7,15 +7,15 @@ class PerformingDog extends Dog implements Performs { @Override - public void speak() { System.out.println("Woof!"); } + public void speak() { System.err.println("Woof!"); } @Override - public void sit() { System.out.println("Sitting"); } + public void sit() { System.err.println("Sitting"); } public void reproduce() {} } class Robot implements Performs { - public void speak() { System.out.println("Click!"); } - public void sit() { System.out.println("Clank!"); } + public void speak() { System.err.println("Click!"); } + public void sit() { System.err.println("Clank!"); } public void oilChange() {} } diff --git a/generics/DynamicProxyMixin.java b/generics/DynamicProxyMixin.java index 38431e31d..c7e3f46cc 100644 --- a/generics/DynamicProxyMixin.java +++ b/generics/DynamicProxyMixin.java @@ -2,62 +2,66 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. + import java.lang.reflect.*; import java.util.*; -import onjava.*; -import static onjava.Tuple.*; +//import onjava.*; +//import static onjava.Tuple.*; +//import static Tuple.tuple.*; class MixinProxy implements InvocationHandler { - Map delegatesByMethod; - @SuppressWarnings("unchecked") - MixinProxy(Tuple2>... pairs) { - delegatesByMethod = new HashMap<>(); - for(Tuple2> pair : pairs) { - for(Method method : pair.a2.getMethods()) { + Map delegatesByMethod; + + @SuppressWarnings("unchecked") + MixinProxy(Tuple2>... pairs) { + delegatesByMethod = new HashMap<>(); + for (Tuple2> pair : pairs) { + for (Method method : pair.a2.getMethods()) { + String methodName = method.getName(); + // The first interface in the map + // implements the method. + if (!delegatesByMethod.containsKey(methodName)) + delegatesByMethod.put(methodName, pair.a1); + } + } + } + + @Override + public Object invoke(Object proxy, Method method, + Object[] args) throws Throwable { String methodName = method.getName(); - // The first interface in the map - // implements the method. - if(!delegatesByMethod.containsKey(methodName)) - delegatesByMethod.put(methodName, pair.a1); - } + Object delegate = delegatesByMethod.get(methodName); + return method.invoke(delegate, args); } - } - @Override - public Object invoke(Object proxy, Method method, - Object[] args) throws Throwable { - String methodName = method.getName(); - Object delegate = delegatesByMethod.get(methodName); - return method.invoke(delegate, args); - } - @SuppressWarnings("unchecked") - public static Object newInstance(Tuple2... pairs) { - Class[] interfaces = new Class[pairs.length]; - for(int i = 0; i < pairs.length; i++) { - interfaces[i] = (Class)pairs[i].a2; + + @SuppressWarnings("unchecked") + public static Object newInstance(Tuple2... pairs) { + Class[] interfaces = new Class[pairs.length]; + for (int i = 0; i < pairs.length; i++) { + interfaces[i] = (Class) pairs[i].a2; + } + ClassLoader cl = pairs[0].a1.getClass().getClassLoader(); + return Proxy.newProxyInstance( + cl, interfaces, new MixinProxy(pairs)); } - ClassLoader cl = - pairs[0].a1.getClass().getClassLoader(); - return Proxy.newProxyInstance( - cl, interfaces, new MixinProxy(pairs)); - } } public class DynamicProxyMixin { - public static void main(String[] args) { - @SuppressWarnings("unchecked") - Object mixin = MixinProxy.newInstance( - tuple(new BasicImp(), Basic.class), - tuple(new TimeStampedImp(), TimeStamped.class), - tuple(new SerialNumberedImp(), - SerialNumbered.class)); - Basic b = (Basic)mixin; - TimeStamped t = (TimeStamped)mixin; - SerialNumbered s = (SerialNumbered)mixin; - b.set("Hello"); - System.out.println(b.get()); - System.out.println(t.getStamp()); - System.out.println(s.getSerialNumber()); - } + public static void main(String[] args) { + @SuppressWarnings("unchecked") + Object mixin = MixinProxy.newInstance( + Tuple.tuple(new BasicImp(), Basic.class), + Tuple.tuple(new TimeStampedImp(), TimeStamped.class), + Tuple.tuple(new SerialNumberedImp(), + SerialNumbered.class)); + Basic b = (Basic) mixin; + TimeStamped t = (TimeStamped) mixin; + SerialNumbered s = (SerialNumbered) mixin; + b.set("Hello"); + System.err.println(b.get()); + System.err.println(t.getStamp()); + System.err.println(s.getSerialNumber()); + } } /* Output: Hello diff --git a/generics/EpicBattle.java b/generics/EpicBattle.java index 908a33437..9233e7235 100644 --- a/generics/EpicBattle.java +++ b/generics/EpicBattle.java @@ -3,72 +3,97 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Bounds in Java generics + import java.util.*; -interface SuperPower {} +interface SuperPower { +} interface XRayVision extends SuperPower { - void seeThroughWalls(); + void seeThroughWalls(); } interface SuperHearing extends SuperPower { - void hearSubtleNoises(); + void hearSubtleNoises(); } interface SuperSmell extends SuperPower { - void trackBySmell(); + void trackBySmell(); } class SuperHero { - POWER power; - SuperHero(POWER power) { this.power = power; } - POWER getPower() { return power; } + POWER power; + + SuperHero(POWER power) { + this.power = power; + } + + POWER getPower() { + return power; + } } -class SuperSleuth -extends SuperHero { - SuperSleuth(POWER power) { super(power); } - void see() { power.seeThroughWalls(); } +class SuperSleuth extends SuperHero { + SuperSleuth(POWER power) { + super(power); + } + + void see() { + power.seeThroughWalls(); + } } class -CanineHero -extends SuperHero { - CanineHero(POWER power) { super(power); } - void hear() { power.hearSubtleNoises(); } - void smell() { power.trackBySmell(); } +CanineHero extends SuperHero { + CanineHero(POWER power) { + super(power); + } + + void hear() { + power.hearSubtleNoises(); + } + + void smell() { + power.trackBySmell(); + } } -class SuperHearSmell -implements SuperHearing, SuperSmell { - @Override - public void hearSubtleNoises() {} - @Override - public void trackBySmell() {} +class SuperHearSmell implements SuperHearing, SuperSmell { + @Override + public void hearSubtleNoises() { + } + + @Override + public void trackBySmell() { + } } class DogPerson extends CanineHero { - DogPerson() { super(new SuperHearSmell()); } + DogPerson() { + super(new SuperHearSmell()); + } } public class EpicBattle { - // Bounds in generic methods: - static - void useSuperHearing(SuperHero hero) { - hero.getPower().hearSubtleNoises(); - } - static - void superFind(SuperHero hero) { - hero.getPower().hearSubtleNoises(); - hero.getPower().trackBySmell(); - } - public static void main(String[] args) { - DogPerson dogPerson = new DogPerson(); - useSuperHearing(dogPerson); - superFind(dogPerson); - // You can do this: - List audioPeople; - // But you can't do this: - // List dogPs; - } + // Bounds in generic methods: + static + void useSuperHearing(SuperHero hero) { + hero.getPower().hearSubtleNoises(); + } + + static + void superFind(SuperHero hero) { + hero.getPower().hearSubtleNoises(); + hero.getPower().trackBySmell(); + } + + public static void main(String[] args) { + DogPerson dogPerson = new DogPerson(); + useSuperHearing(dogPerson); + superFind(dogPerson); + // You can do this: + List audioPeople; + // But you can't do this: +// List dogPs; + } } diff --git a/generics/ErasedTypeEquivalence.java b/generics/ErasedTypeEquivalence.java index 6034b3048..4945d243e 100644 --- a/generics/ErasedTypeEquivalence.java +++ b/generics/ErasedTypeEquivalence.java @@ -8,7 +8,7 @@ public class ErasedTypeEquivalence { public static void main(String[] args) { Class c1 = new ArrayList().getClass(); Class c2 = new ArrayList().getClass(); - System.out.println(c1 == c2); + System.err.println(c1 == c2); } } /* Output: diff --git a/generics/ErasureAndInheritance.java b/generics/ErasureAndInheritance.java index 44a07b625..9efa95481 100644 --- a/generics/ErasureAndInheritance.java +++ b/generics/ErasureAndInheritance.java @@ -23,6 +23,8 @@ public class ErasureAndInheritance { public static void main(String[] args) { Derived2 d2 = new Derived2(); Object obj = d2.get(); - d2.set(obj); // Warning here! + // Warning here! Unchecked call to 'set(T)' as a member of raw type 'GenericBase' + d2.set(obj); + } } diff --git a/generics/FactoryConstraint.java b/generics/FactoryConstraint.java index f06510732..98f900ff8 100644 --- a/generics/FactoryConstraint.java +++ b/generics/FactoryConstraint.java @@ -21,8 +21,7 @@ class Widget { public String toString() { return "Widget " + id; } - public static - class Factory implements Supplier { + public static class Factory implements Supplier { private int i = 0; @Override public Widget get() { return new Widget(++i); } @@ -32,6 +31,14 @@ class Factory implements Supplier { class Fudge { private static int count = 1; private int n = count++; + public Fudge() { + System.err.println("构造器启用"); + } + + public Fudge(int n) { + this.n = n; + } + @Override public String toString() { return "Fudge " + n; } } @@ -47,11 +54,11 @@ class Foo2 { public class FactoryConstraint { public static void main(String[] args) { - System.out.println( + System.err.println( new Foo2<>(new IntegerFactory())); - System.out.println( + System.err.println( new Foo2<>(new Widget.Factory())); - System.out.println( + System.err.println( new Foo2<>(Fudge::new)); } } diff --git a/generics/FilledList.java b/generics/FilledList.java index e24423cef..b20459382 100644 --- a/generics/FilledList.java +++ b/generics/FilledList.java @@ -16,10 +16,10 @@ public FilledList(T t, int size) { } public static void main(String[] args) { List list = new FilledList<>("Hello", 4); - System.out.println(list); + System.err.println(list); // Supplier version: List ilist = new FilledList<>(() -> 47, 4); - System.out.println(ilist); + System.err.println(ilist); } } /* Output: diff --git a/generics/GenericArray.java b/generics/GenericArray.java index f0ffba3d2..f960bcd44 100644 --- a/generics/GenericArray.java +++ b/generics/GenericArray.java @@ -4,29 +4,37 @@ // Visit http://OnJava8.com for more book information. public class GenericArray { - private T[] array; - @SuppressWarnings("unchecked") - public GenericArray(int sz) { - array = (T[])new Object[sz]; - } - public void put(int index, T item) { - array[index] = item; - } - public T get(int index) { return array[index]; } - // Method that exposes the underlying representation: - public T[] rep() { return array; } - public static void main(String[] args) { - GenericArray gai = new GenericArray<>(10); - try { - Integer[] ia = gai.rep(); - } catch(ClassCastException e) { - System.out.println(e.getMessage()); + private T[] array; + + @SuppressWarnings("unchecked") + public GenericArray(int sz) { + array = (T[]) new Object[sz]; + } + + public void put(int index, T item) { + array[index] = item; + } + + public T get(int index) { + return array[index]; + } + + // Method that exposes the underlying representation: + public T[] rep() { + return array; + } + + public static void main(String[] args) { + GenericArray gai = new GenericArray<>(10); + try { + Integer[] ia = gai.rep(); + } catch (ClassCastException e) { + System.err.println(e.getMessage()); + } + // This is OK: + Object[] oa = gai.rep(); } - // This is OK: - Object[] oa = gai.rep(); - } } /* Output: -[Ljava.lang.Object; cannot be cast to -[Ljava.lang.Integer; +[Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer; */ diff --git a/generics/GenericArray2.java b/generics/GenericArray2.java index 7ef4179ec..0f28c27cd 100644 --- a/generics/GenericArray2.java +++ b/generics/GenericArray2.java @@ -23,12 +23,12 @@ public static void main(String[] args) { for(int i = 0; i < 10; i ++) gai.put(i, i); for(int i = 0; i < 10; i ++) - System.out.print(gai.get(i) + " "); - System.out.println(); + System.err.print(gai.get(i) + " "); + System.err.println(); try { Integer[] ia = gai.rep(); } catch(Exception e) { - System.out.println(e); + System.err.println(e); } } } diff --git a/generics/GenericArrayWithTypeToken.java b/generics/GenericArrayWithTypeToken.java index 6ea36a767..985082f23 100644 --- a/generics/GenericArrayWithTypeToken.java +++ b/generics/GenericArrayWithTypeToken.java @@ -23,5 +23,23 @@ public static void main(String[] args) { Integer.class, 10); // This now works: Integer[] ia = gai.rep(); + System.err.println(ia.length); + + //self-note: 深入研究泛型的数组【】 + try { + Object obj = new Object(); + String str = (String)obj; + } catch (Exception e) { + System.err.println("not OK! "+e); + } + + try { + String str = new String(); + Object obj = str; + String str2 = (String)obj; + System.err.println("OK!"); + } catch (Exception e) { + System.err.println(e); + } } } diff --git a/generics/GenericCast.java b/generics/GenericCast.java index c3f82dac7..f7e7e1550 100644 --- a/generics/GenericCast.java +++ b/generics/GenericCast.java @@ -35,7 +35,7 @@ public static void main(String[] args) { new FixedSizeStack<>(letters.length); Arrays.stream("ABCDEFGHIJKLMNOPQRS".split("")) .forEach(strings::push); - System.out.println(strings.pop()); + System.err.println(strings.pop()); strings.stream() .map(s -> s + " ") .forEach(System.out::print); diff --git a/generics/GenericMethods.java b/generics/GenericMethods.java index 66f40e72d..3a84cf2a3 100644 --- a/generics/GenericMethods.java +++ b/generics/GenericMethods.java @@ -5,7 +5,7 @@ public class GenericMethods { public void f(T x) { - System.out.println(x.getClass().getName()); + System.err.println(x.getClass().getName()); } public static void main(String[] args) { GenericMethods gm = new GenericMethods(); diff --git a/generics/GenericReading.java b/generics/GenericReading.java index 5709c7a92..216575111 100644 --- a/generics/GenericReading.java +++ b/generics/GenericReading.java @@ -5,8 +5,7 @@ import java.util.*; public class GenericReading { - static List apples = - Arrays.asList(new Apple()); + static List apples = Arrays.asList(new Apple()); static List fruit = Arrays.asList(new Fruit()); static T readExact(List list) { return list.get(0); @@ -25,9 +24,9 @@ static class Reader { static void f2() { Reader fruitReader = new Reader<>(); Fruit f = fruitReader.readExact(fruit); - //- Fruit a = fruitReader.readExact(apples); - // error: incompatible types: List - // cannot be converted to List + //- +// Fruit a = fruitReader.readExact(apples); + // error: incompatible types: List cannot be converted to List } static class CovariantReader { T readCovariant(List list) { diff --git a/generics/GenericVarargs.java b/generics/GenericVarargs.java index 3a6e348ca..c2a846c02 100644 --- a/generics/GenericVarargs.java +++ b/generics/GenericVarargs.java @@ -14,12 +14,14 @@ public static List makeList(T... args) { } public static void main(String[] args) { List ls = makeList("A"); - System.out.println(ls); + System.err.println(ls); ls = makeList("A", "B", "C"); - System.out.println(ls); + System.err.println(ls); + String[] split = "ABCDEFFHIJKLMNOPQRSTUVWXYZ".split(""); + System.err.println(Arrays.toString(split)); ls = makeList( - "ABCDEFFHIJKLMNOPQRSTUVWXYZ".split("")); - System.out.println(ls); + split); + System.err.println(ls); } } /* Output: diff --git a/generics/GenericsAndCovariance.java b/generics/GenericsAndCovariance.java index f16b837be..5cbe93f8c 100644 --- a/generics/GenericsAndCovariance.java +++ b/generics/GenericsAndCovariance.java @@ -9,11 +9,14 @@ public static void main(String[] args) { // Wildcards allow covariance: List flist = new ArrayList<>(); // Compile Error: can't add any type of object: - // flist.add(new Apple()); +// flist.add(new Apple()); // flist.add(new Fruit()); // flist.add(new Object()); flist.add(null); // Legal but uninteresting // We know it returns at least Fruit: Fruit f = flist.get(0); + List flist2 = new ArrayList(); +// flist.add(new Object()); + } } diff --git a/generics/HasF.java b/generics/HasF.java index f967386e3..2b777d61a 100644 --- a/generics/HasF.java +++ b/generics/HasF.java @@ -5,6 +5,6 @@ public class HasF { public void f() { - System.out.println("HasF.f()"); + System.err.println("HasF.f()"); } } diff --git a/generics/Holder.java b/generics/Holder.java index e4301dc66..ce43d896c 100644 --- a/generics/Holder.java +++ b/generics/Holder.java @@ -26,13 +26,14 @@ public static void main(String[] args) { // Holder Fruit = apple; // Cannot upcast Holder fruit = apple; // OK Fruit p = fruit.get(); - d = (Apple)fruit.get(); // Returns 'Object' + Apple ccc = (Apple)fruit.get(); // Returns 'Object' + System.err.println("D->"+ccc); try { Orange c = (Orange)fruit.get(); // No warning - } catch(Exception e) { System.out.println(e); } + } catch(Exception e) { System.err.println(e); } // fruit.set(new Apple()); // Cannot call set() // fruit.set(new Fruit()); // Cannot call set() - System.out.println(fruit.equals(d)); // OK + System.err.println(fruit.equals(d)); // OK } } /* Output: diff --git a/generics/Individual.java b/generics/Individual.java new file mode 100644 index 000000000..96295ec33 --- /dev/null +++ b/generics/Individual.java @@ -0,0 +1,46 @@ +// typeinfo/pets/Individual.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. + +import java.util.Objects; + +public class +Individual implements Comparable { + private static long counter = 0; + private final long id = counter++; + private String name; + public Individual(String name) { this.name = name; } + // 'name' is optional: + public Individual() {} + @Override + public String toString() { + return getClass().getSimpleName() + + (name == null ? "" : " " + name); + } + public long id() { return id; } + @Override + public boolean equals(Object o) { + return o instanceof Individual && + Objects.equals(id, ((Individual)o).id); + } + @Override + public int hashCode() { + return Objects.hash(name, id); + } + @Override + public int compareTo(Individual arg) { + // Compare by class name first: + String first = getClass().getSimpleName(); + String argFirst = arg.getClass().getSimpleName(); + int firstCompare = first.compareTo(argFirst); + if(firstCompare != 0) + return firstCompare; + if(name != null && arg.name != null) { + int secondCompare = name.compareTo(arg.name); + if(secondCompare != 0) + return secondCompare; + } + return (arg.id < id ? -1 : (arg.id == id ? 0 : 1)); + } +} diff --git a/generics/InheritBounds.java b/generics/InheritBounds.java index fddd25431..677a67f0e 100644 --- a/generics/InheritBounds.java +++ b/generics/InheritBounds.java @@ -5,27 +5,37 @@ class HoldItem { T item; - HoldItem(T item) { this.item = item; } + HoldItem(T item) { this.item = item;System.err.println("HoldItem 构造器"); } + + + T getItem() { return item; } } -class WithColor2 -extends HoldItem { - WithColor2(T item) { super(item); } +class WithColor2 extends HoldItem { + WithColor2(T item) { super(item); System.err.println("WithColor2 构造器");} + + + java.awt.Color color() { return item.getColor(); } } class WithColorCoord2 extends WithColor2 { - WithColorCoord2(T item) { super(item); } + WithColorCoord2(T item) { super(item); System.err.println("WithColorCoord2 构造器");} + + + int getX() { return item.x; } int getY() { return item.y; } int getZ() { return item.z; } } -class Solid2 -extends WithColorCoord2 { - Solid2(T item) { super(item); } +class Solid2 extends WithColorCoord2 { + + + Solid2(T item) { super(item); System.err.println("Solid2 构造器"); + } int weight() { return item.weight(); } } diff --git a/generics/InstantiateGenericType.java b/generics/InstantiateGenericType.java index 9424c9a1d..5bf6978c6 100644 --- a/generics/InstantiateGenericType.java +++ b/generics/InstantiateGenericType.java @@ -30,13 +30,13 @@ public class InstantiateGenericType { public static void main(String[] args) { ClassAsFactory fe = new ClassAsFactory<>(Employee.class); - System.out.println(fe.get()); + System.err.println(fe.get()); ClassAsFactory fi = new ClassAsFactory<>(Integer.class); try { - System.out.println(fi.get()); + System.err.println(fi.get()); } catch(Exception e) { - System.out.println(e.getMessage()); + System.err.println(e.getMessage()); } } } diff --git a/generics/IterableFibonacci.java b/generics/IterableFibonacci.java index b5ccf285a..abc058fb4 100644 --- a/generics/IterableFibonacci.java +++ b/generics/IterableFibonacci.java @@ -5,8 +5,7 @@ // Adapt the Fibonacci class to make it Iterable import java.util.*; -public class IterableFibonacci -extends Fibonacci implements Iterable { +public class IterableFibonacci extends Fibonacci implements Iterable { private int n; public IterableFibonacci(int count) { n = count; } @Override @@ -27,10 +26,13 @@ public void remove() { // Not implemented } public static void main(String[] args) { for(int i : new IterableFibonacci(18)) - System.out.print(i + " "); + System.err.print(i + " "); } } /* Output: 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 */ +//self-note: 创建一个 *适配器* (Adapter) 来实现所需的接口 [类适配器模式] +//类适配器模式需要新定义一个适配器类,它实现了需求对应的接口,并继承现有的业务类, +//通过在接口方法中显式地调用父类的方法的方式,达到适应新需求同时又复用现有方法代码的目的。 diff --git a/generics/LatentReflection.java b/generics/LatentReflection.java index 0e9511a34..c87590adf 100644 --- a/generics/LatentReflection.java +++ b/generics/LatentReflection.java @@ -9,7 +9,7 @@ class Mime { public void walkAgainstTheWind() {} public void sit() { - System.out.println("Pretending to sit"); + System.err.println("Pretending to sit"); } public void pushInvisibleWalls() {} @Override @@ -18,8 +18,8 @@ public void pushInvisibleWalls() {} // Does not implement Performs: class SmartDog { - public void speak() { System.out.println("Woof!"); } - public void sit() { System.out.println("Sitting"); } + public void speak() { System.err.println("Woof!"); } + public void sit() { System.err.println("Sitting"); } public void reproduce() {} } @@ -31,13 +31,13 @@ public static void perform(Object speaker) { Method speak = spkr.getMethod("speak"); speak.invoke(speaker); } catch(NoSuchMethodException e) { - System.out.println(speaker + " cannot speak"); + System.err.println(speaker + " cannot speak"); } try { Method sit = spkr.getMethod("sit"); sit.invoke(speaker); } catch(NoSuchMethodException e) { - System.out.println(speaker + " cannot sit"); + System.err.println(speaker + " cannot sit"); } } catch(SecurityException | IllegalAccessException | diff --git a/generics/LinkedStack.java b/generics/LinkedStack.java index 5142bcc73..d7f7c5eec 100644 --- a/generics/LinkedStack.java +++ b/generics/LinkedStack.java @@ -33,7 +33,7 @@ public static void main(String[] args) { lss.push(s); String s; while((s = lss.pop()) != null) - System.out.println(s); + System.err.println(s); } } /* Output: diff --git a/generics/ListOfInt.java b/generics/ListOfInt.java index f8ac8e11d..031f76598 100644 --- a/generics/ListOfInt.java +++ b/generics/ListOfInt.java @@ -12,7 +12,7 @@ public static void main(String[] args) { List li = IntStream.range(38, 48) .boxed() // Converts ints to Integers .collect(Collectors.toList()); - System.out.println(li); + System.err.println(li); } } /* Output: diff --git a/generics/LostInformation.java b/generics/LostInformation.java index e27430d2e..31c8785c2 100644 --- a/generics/LostInformation.java +++ b/generics/LostInformation.java @@ -15,13 +15,13 @@ public static void main(String[] args) { Map map = new HashMap<>(); Quark quark = new Quark<>(); Particle p = new Particle<>(); - System.out.println(Arrays.toString( + System.err.println(Arrays.toString( list.getClass().getTypeParameters())); - System.out.println(Arrays.toString( + System.err.println(Arrays.toString( map.getClass().getTypeParameters())); - System.out.println(Arrays.toString( + System.err.println(Arrays.toString( quark.getClass().getTypeParameters())); - System.out.println(Arrays.toString( + System.err.println(Arrays.toString( p.getClass().getTypeParameters())); } } diff --git a/generics/Mixins.java b/generics/Mixins.java index af58b81e0..37f3d6c85 100644 --- a/generics/Mixins.java +++ b/generics/Mixins.java @@ -57,10 +57,10 @@ public static void main(String[] args) { Mixin mixin1 = new Mixin(), mixin2 = new Mixin(); mixin1.set("test string 1"); mixin2.set("test string 2"); - System.out.println(mixin1.get() + " " + + System.err.println(mixin1.get() + " " + mixin1.getStamp() + " " + mixin1.getSerialNumber()); - System.out.println(mixin2.get() + " " + + System.err.println(mixin2.get() + " " + mixin2.getStamp() + " " + mixin2.getSerialNumber()); } diff --git a/generics/OrdinaryArguments.java b/generics/OrdinaryArguments.java index 6e50550d9..5c464e4b4 100644 --- a/generics/OrdinaryArguments.java +++ b/generics/OrdinaryArguments.java @@ -5,13 +5,13 @@ class OrdinarySetter { void set(Base base) { - System.out.println("OrdinarySetter.set(Base)"); + System.err.println("OrdinarySetter.set(Base)"); } } class DerivedSetter extends OrdinarySetter { void set(Derived derived) { - System.out.println("DerivedSetter.set(Derived)"); + System.err.println("DerivedSetter.set(Derived)"); } } diff --git a/generics/Pet.java b/generics/Pet.java new file mode 100644 index 000000000..547090a1c --- /dev/null +++ b/generics/Pet.java @@ -0,0 +1,9 @@ +// typeinfo/pets/Pet.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. + +public class Pet extends Individual { + public Pet(String name) { super(name); } + public Pet() { super(); } +} diff --git a/generics/PlainGenericInheritance.java b/generics/PlainGenericInheritance.java index 93eb61c68..4725c1052 100644 --- a/generics/PlainGenericInheritance.java +++ b/generics/PlainGenericInheritance.java @@ -5,13 +5,13 @@ class GenericSetter { // Not self-bounded void set(T arg) { - System.out.println("GenericSetter.set(Base)"); + System.err.println("GenericSetter.set(Base)"); } } class DerivedGS extends GenericSetter { void set(Derived derived) { - System.out.println("DerivedGS.set(Derived)"); + System.err.println("DerivedGS.set(Derived)"); } } diff --git a/generics/PrimitiveGenericTest.java b/generics/PrimitiveGenericTest.java index 793564379..18883c3ce 100644 --- a/generics/PrimitiveGenericTest.java +++ b/generics/PrimitiveGenericTest.java @@ -2,7 +2,7 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -import onjava.*; +//import onjava.*; import java.util.*; import java.util.function.*; @@ -30,10 +30,10 @@ public class PrimitiveGenericTest { public static void main(String[] args) { String[] strings = FillArray.fill( new String[5], new Rand.String(9)); - System.out.println(Arrays.toString(strings)); + System.err.println(Arrays.toString(strings)); int[] integers = FillArray.fill( new int[9], new Rand.Pint()); - System.out.println(Arrays.toString(integers)); + System.err.println(Arrays.toString(integers)); } } /* Output: diff --git a/generics/Rand.java b/generics/Rand.java new file mode 100644 index 000000000..246d83fc0 --- /dev/null +++ b/generics/Rand.java @@ -0,0 +1,247 @@ +// onjava/Rand.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// Generate random values of different types + +import java.util.*; +import java.util.function.*; +import static onjava.ConvertTo.*; + +public interface Rand { + int MOD = 10_000; + class Boolean + implements Supplier { + SplittableRandom r = new SplittableRandom(47); + @Override + public java.lang.Boolean get() { + return r.nextBoolean(); + } + public java.lang.Boolean get(int n) { + return get(); + } + public java.lang.Boolean[] array(int sz) { + java.lang.Boolean[] result = + new java.lang.Boolean[sz]; + Arrays.setAll(result, n -> get()); + return result; + } + } + class Pboolean { + public boolean[] array(int sz) { + return primitive(new Boolean().array(sz)); + } + } + class Byte + implements Supplier { + SplittableRandom r = new SplittableRandom(47); + @Override + public java.lang.Byte get() { + return (byte)r.nextInt(MOD); + } + public java.lang.Byte get(int n) { + return get(); + } + public java.lang.Byte[] array(int sz) { + java.lang.Byte[] result = + new java.lang.Byte[sz]; + Arrays.setAll(result, n -> get()); + return result; + } + } + class Pbyte { + public byte[] array(int sz) { + return primitive(new Byte().array(sz)); + } + } + class Character + implements Supplier { + SplittableRandom r = new SplittableRandom(47); + @Override + public java.lang.Character get() { + return (char)r.nextInt('a', 'z' + 1); + } + public java.lang.Character get(int n) { + return get(); + } + public java.lang.Character[] array(int sz) { + java.lang.Character[] result = + new java.lang.Character[sz]; + Arrays.setAll(result, n -> get()); + return result; + } + } + class Pchar { + public char[] array(int sz) { + return primitive(new Character().array(sz)); + } + } + class Short + implements Supplier { + SplittableRandom r = new SplittableRandom(47); + @Override + public java.lang.Short get() { + return (short)r.nextInt(MOD); + } + public java.lang.Short get(int n) { + return get(); + } + public java.lang.Short[] array(int sz) { + java.lang.Short[] result = + new java.lang.Short[sz]; + Arrays.setAll(result, n -> get()); + return result; + } + } + class Pshort { + public short[] array(int sz) { + return primitive(new Short().array(sz)); + } + } + class Integer + implements Supplier { + SplittableRandom r = new SplittableRandom(47); + @Override + public java.lang.Integer get() { + return r.nextInt(MOD); + } + public java.lang.Integer get(int n) { + return get(); + } + public java.lang.Integer[] array(int sz) { + int[] primitive = new Pint().array(sz); + java.lang.Integer[] result = + new java.lang.Integer[sz]; + for(int i = 0; i < sz; i++) + result[i] = primitive[i]; + return result; + } + } + class Pint implements IntSupplier { + SplittableRandom r = new SplittableRandom(47); + @Override + public int getAsInt() { + return r.nextInt(MOD); + } + public int get(int n) { return getAsInt(); } + public int[] array(int sz) { + return r.ints(sz, 0, MOD).toArray(); + } + } + class Long + implements Supplier { + SplittableRandom r = new SplittableRandom(47); + @Override + public java.lang.Long get() { + return r.nextLong(MOD); + } + public java.lang.Long get(int n) { + return get(); + } + public java.lang.Long[] array(int sz) { + long[] primitive = new Plong().array(sz); + java.lang.Long[] result = + new java.lang.Long[sz]; + for(int i = 0; i < sz; i++) + result[i] = primitive[i]; + return result; + } + } + class Plong implements LongSupplier { + SplittableRandom r = new SplittableRandom(47); + @Override + public long getAsLong() { + return r.nextLong(MOD); + } + public long get(int n) { return getAsLong(); } + public long[] array(int sz) { + return r.longs(sz, 0, MOD).toArray(); + } + } + class Float + implements Supplier { + SplittableRandom r = new SplittableRandom(47); + @Override + public java.lang.Float get() { + return (float)trim(r.nextDouble()); + } + public java.lang.Float get(int n) { + return get(); + } + public java.lang.Float[] array(int sz) { + java.lang.Float[] result = + new java.lang.Float[sz]; + Arrays.setAll(result, n -> get()); + return result; + } + } + class Pfloat { + public float[] array(int sz) { + return primitive(new Float().array(sz)); + } + } + static double trim(double d) { + return + ((double)Math.round(d * 1000.0)) / 100.0; + } + class Double + implements Supplier { + SplittableRandom r = new SplittableRandom(47); + @Override + public java.lang.Double get() { + return trim(r.nextDouble()); + } + public java.lang.Double get(int n) { + return get(); + } + public java.lang.Double[] array(int sz) { + double[] primitive = + new Pdouble().array(sz); + java.lang.Double[] result = + new java.lang.Double[sz]; + for(int i = 0; i < sz; i++) + result[i] = primitive[i]; + return result; + } + } + class Pdouble implements DoubleSupplier { + SplittableRandom r = new SplittableRandom(47); + @Override + public double getAsDouble() { + return trim(r.nextDouble()); + } + public double get(int n) { + return getAsDouble(); + } + public double[] array(int sz) { + double[] result = r.doubles(sz).toArray(); + Arrays.setAll(result, + n -> result[n] = trim(result[n])); + return result; + } + } + class String implements Supplier { + SplittableRandom r = new SplittableRandom(47); + private int strlen = 7; // Default length + public String() {} + public String(int strLength) { + strlen = strLength; + } + @Override + public java.lang.String get() { + return r.ints(strlen, 'a', 'z' + 1) + .collect(StringBuilder::new, + StringBuilder::appendCodePoint, + StringBuilder::append).toString(); + } + public java.lang.String get(int n) { + return get(); + } + public java.lang.String[] array(int sz) { + java.lang.String[] result = + new java.lang.String[sz]; + Arrays.setAll(result, n -> get()); + return result; + } + } +} diff --git a/generics/RandomList.java b/generics/RandomList.java index d4f198bcf..4d1f81b28 100644 --- a/generics/RandomList.java +++ b/generics/RandomList.java @@ -17,7 +17,7 @@ public static void main(String[] args) { "the lazy brown dog").split(" ")) .forEach(rs::add); IntStream.range(0, 11).forEach(i -> - System.out.print(rs.select() + " ")); + System.err.print(rs.select() + " ")); } } /* Output: diff --git a/generics/RestrictedComparablePets.java b/generics/RestrictedComparablePets.java index 16146d7b5..117d58f68 100644 --- a/generics/RestrictedComparablePets.java +++ b/generics/RestrictedComparablePets.java @@ -3,8 +3,8 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -class Hamster extends ComparablePet -implements Comparable { +class Hamster extends ComparablePet implements Comparable { + @Override public int compareTo(ComparablePet arg) { return 0; } @@ -13,6 +13,8 @@ public int compareTo(ComparablePet arg) { // Or just: class Gecko extends ComparablePet { + + @Override public int compareTo(ComparablePet arg) { return 0; } diff --git a/generics/SelfBoundingAndCovariantArguments.java b/generics/SelfBoundingAndCovariantArguments.java index 34262b0ed..681419530 100644 --- a/generics/SelfBoundingAndCovariantArguments.java +++ b/generics/SelfBoundingAndCovariantArguments.java @@ -14,7 +14,7 @@ public class SelfBoundingAndCovariantArguments { void testA(Setter s1, Setter s2, SelfBoundSetter sbs) { s1.set(s2); - //- s1.set(sbs); +// s1.set(sbs); // error: method set in interface SelfBoundSetter // cannot be applied to given types; // s1.set(sbs); diff --git a/generics/Sets.java b/generics/Sets.java new file mode 100644 index 000000000..7d90c18b4 --- /dev/null +++ b/generics/Sets.java @@ -0,0 +1,31 @@ +// onjava/Sets.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +//package onjava; + +import java.util.HashSet; +import java.util.Set; + +public class Sets { + public static Set union(Set a, Set b) { + Set result = new HashSet<>(a); + result.addAll(b); + return result; + } + public static Set intersection(Set a, Set b) { + Set result = new HashSet<>(a); + result.retainAll(b); + return result; + } + // Subtract subset from superset: + public static Set difference(Set superset, Set subset) { + Set result = new HashSet<>(superset); + result.removeAll(subset); + return result; + } + // Reflexive--everything not in the intersection: + public static Set complement(Set a, Set b) { + return difference(union(a, b), intersection(a, b)); + } +} diff --git a/generics/Shape.java b/generics/Shape.java index dd2458c2b..9f951c411 100644 --- a/generics/Shape.java +++ b/generics/Shape.java @@ -11,9 +11,9 @@ public String toString() { return getClass().getSimpleName() + " " + id; } public void rotate() { - System.out.println(this + " rotate"); + System.err.println(this + " rotate"); } public void resize(int newSize) { - System.out.println(this + " resize " + newSize); + System.err.println(this + " resize " + newSize); } } diff --git a/generics/Square.java b/generics/Square.java index e3bcad934..79172e5ca 100644 --- a/generics/Square.java +++ b/generics/Square.java @@ -2,4 +2,21 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. + + public class Square extends Shape {} + +/*public class Square { + private static long counter = 0; + private final long id = counter++; + @Override + public String toString() { + return getClass().getSimpleName() + " " + id; + } + public void rotate() { + System.err.println(this + " rotateSS"); + } + public void resize(int newSize) { + System.err.println(this + " resizeSS " + newSize); + } +}*/ diff --git a/generics/Store.java b/generics/Store.java index c165926a3..348ce3cf7 100644 --- a/generics/Store.java +++ b/generics/Store.java @@ -5,7 +5,7 @@ // Building a complex model using generic collections import java.util.*; import java.util.function.*; -import onjava.*; +//import onjava.*; class Product { private final int id; @@ -15,7 +15,7 @@ class Product { id = idNumber; description = descr; this.price = price; - System.out.println(toString()); + System.err.println(toString()); } @Override public String toString() { @@ -74,7 +74,7 @@ public String toString() { return result.toString(); } public static void main(String[] args) { - System.out.println(new Store(5, 4, 3)); + System.err.println(new Store(5, 4, 3)); } } /* Output: (First 8 Lines) diff --git a/generics/SuperTypeWildcards.java b/generics/SuperTypeWildcards.java index f8672a4fc..235bb82df 100644 --- a/generics/SuperTypeWildcards.java +++ b/generics/SuperTypeWildcards.java @@ -8,6 +8,14 @@ public class SuperTypeWildcards { static void writeTo(List apples) { apples.add(new Apple()); apples.add(new Jonathan()); - // apples.add(new Fruit()); // Error +// apples.add(new Fruit()); // Error + + Holder apple1 = new Holder<>(new Apple()); + Holder apple2 = new Holder<>(new Jonathan()); + Holder apple0 = new Holder<>(new Fruit()); + apple1.set(new Jonathan()); +// apple1.set(new Orange()); +// apple0.set(new Fruit()); + } } diff --git a/generics/Suppliers.java b/generics/Suppliers.java new file mode 100644 index 000000000..03b7f4133 --- /dev/null +++ b/generics/Suppliers.java @@ -0,0 +1,39 @@ +// onjava/Suppliers.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// A utility to use with Suppliers +//package onjava; + +import java.util.Collection; +import java.util.function.BiConsumer; +import java.util.function.Supplier; +import java.util.stream.Stream; + +public class Suppliers { + // Create a collection and fill it: + public static > C + create(Supplier factory, Supplier gen, int n) { + return Stream.generate(gen) + .limit(n) + .collect(factory, C::add, C::addAll); + } + // Fill an existing collection: + public static > + C fill(C coll, Supplier gen, int n) { + Stream.generate(gen) + .limit(n) + .forEach(coll::add); + return coll; + } + // Use an unbound method reference to + // produce a more general method: + public static H fill(H holder, + BiConsumer adder, Supplier gen, int n) { + System.err.println("----------- H fill ---------------"); + Stream.generate(gen) + .limit(n) + .forEach(a -> adder.accept(holder, a)); + return holder; + } +} diff --git a/generics/ThrowGenericException.java b/generics/ThrowGenericException.java index 994c7f885..04d73a9ef 100644 --- a/generics/ThrowGenericException.java +++ b/generics/ThrowGenericException.java @@ -2,79 +2,90 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. + import java.util.*; interface Processor { - void process(List resultCollector) throws E; + void process(List resultCollector) throws E; } -class ProcessRunner -extends ArrayList> { - List processAll() throws E { - List resultCollector = new ArrayList<>(); - for(Processor processor : this) - processor.process(resultCollector); - return resultCollector; - } +class ProcessRunner extends ArrayList> { + List processAll() throws E { + List resultCollector = new ArrayList<>(); + for (Processor processor : this) { + processor.process(resultCollector); + } + return resultCollector; + } } -class Failure1 extends Exception {} +class Failure1 extends Exception { +} + +class Processor1 implements Processor { + static int count = 3; + + @Override + public void process(List resultCollector) throws Failure1 { + System.err.println("count:"+count); + if (count-- > 1) { + resultCollector.add("Hep!"); + } else { + resultCollector.add("Ho!"); + } + if (count < 0) { + throw new Failure1(); + } + } +} -class Processor1 -implements Processor { - static int count = 3; - @Override - public void process(List resultCollector) - throws Failure1 { - if(count-- > 1) - resultCollector.add("Hep!"); - else - resultCollector.add("Ho!"); - if(count < 0) - throw new Failure1(); - } +class Failure2 extends Exception { } -class Failure2 extends Exception {} +class Processor2 implements Processor { + static int count = 2; + + @Override + public void process(List resultCollector) throws Failure2 { + System.err.println("Processor2 count:"+count); -class Processor2 -implements Processor { - static int count = 2; - @Override - public void process(List resultCollector) - throws Failure2 { - if(count-- == 0) - resultCollector.add(47); - else { - resultCollector.add(11); + if (count-- == 0) { + resultCollector.add(47); + System.err.println("47"); + } else { + resultCollector.add(11); + System.err.println("11"); + + } + if (count < 0) { + throw new Failure2(); + } } - if(count < 0) - throw new Failure2(); - } } public class ThrowGenericException { - public static void main(String[] args) { - ProcessRunner runner = - new ProcessRunner<>(); - for(int i = 0; i < 3; i++) - runner.add(new Processor1()); - try { - System.out.println(runner.processAll()); - } catch(Failure1 e) { - System.out.println(e); - } + public static void main(String[] args) { + ProcessRunner runner = new ProcessRunner<>(); + for (int i = 0; i < 3; i++) { + runner.add(new Processor1()); + } + try { + System.err.println(runner.processAll()); + } catch (Failure1 e) { + System.err.println(e); + } - ProcessRunner runner2 = - new ProcessRunner<>(); - for(int i = 0; i < 3; i++) - runner2.add(new Processor2()); - try { - System.out.println(runner2.processAll()); - } catch(Failure2 e) { - System.out.println(e); + ProcessRunner runner2 = new ProcessRunner<>(); + for (int i = 0; i < 3; i++) { + runner2.add(new Processor2()); + } + try { + List x = runner2.processAll(); + System.err.println("x:"+x);//processAll()抛出异常,因此没有打印 收集参数 + } catch (Failure2 e) { + System.err.println(e); + } } - } } /* Output: [Hep!, Hep!, Ho!] diff --git a/generics/Tuple.java b/generics/Tuple.java new file mode 100644 index 000000000..6456c69f0 --- /dev/null +++ b/generics/Tuple.java @@ -0,0 +1,24 @@ +// onjava/Tuple.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// Tuple library using type argument inference +//package onjava; + +public class Tuple { + public static Tuple2 tuple(A a, B b) { + return new Tuple2<>(a, b); + } + + public static Tuple3 tuple(A a, B b, C c) { + return new Tuple3<>(a, b, c); + } + + public static Tuple4 tuple(A a, B b, C c, D d) { + return new Tuple4<>(a, b, c, d); + } + + public static Tuple5 tuple(A a, B b, C c, D d, E e) { + return new Tuple5<>(a, b, c, d, e); + } +} diff --git a/generics/Tuple2.java b/generics/Tuple2.java new file mode 100644 index 000000000..1fc723c6b --- /dev/null +++ b/generics/Tuple2.java @@ -0,0 +1,16 @@ +// onjava/Tuple2.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +//package onjava; + +public class Tuple2 { + public final A a1; + public final B a2; + public Tuple2(A a, B b) { a1 = a; a2 = b; } + public String rep() { return a1 + ", " + a2; } + @Override + public String toString() { + return "(" + rep() + ")"; + } +} diff --git a/generics/Tuple3.java b/generics/Tuple3.java new file mode 100644 index 000000000..6ddc9c580 --- /dev/null +++ b/generics/Tuple3.java @@ -0,0 +1,17 @@ +// onjava/Tuple3.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +//package onjava; + +public class Tuple3 extends Tuple2 { + public final C a3; + public Tuple3(A a, B b, C c) { + super(a, b); + a3 = c; + } + @Override + public String rep() { + return super.rep() + ", " + a3; + } +} diff --git a/generics/Tuple4.java b/generics/Tuple4.java new file mode 100644 index 000000000..e61e54167 --- /dev/null +++ b/generics/Tuple4.java @@ -0,0 +1,18 @@ +// onjava/Tuple4.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +//package onjava; + +public class Tuple4 + extends Tuple3 { + public final D a4; + public Tuple4(A a, B b, C c, D d) { + super(a, b, c); + a4 = d; + } + @Override + public String rep() { + return super.rep() + ", " + a4; + } +} diff --git a/generics/Tuple5.java b/generics/Tuple5.java new file mode 100644 index 000000000..a089131bb --- /dev/null +++ b/generics/Tuple5.java @@ -0,0 +1,18 @@ +// onjava/Tuple5.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +//package onjava; + +public class Tuple5 +extends Tuple4 { + public final E a5; + public Tuple5(A a, B b, C c, D d, E e) { + super(a, b, c, d); + a5 = e; + } + @Override + public String rep() { + return super.rep() + ", " + a5; + } +} diff --git a/generics/TupleTest.java b/generics/TupleTest.java index e207da405..3b3e0d578 100644 --- a/generics/TupleTest.java +++ b/generics/TupleTest.java @@ -27,11 +27,11 @@ String, Integer, Double> k() { } public static void main(String[] args) { Tuple2 ttsi = f(); - System.out.println(ttsi); + System.err.println(ttsi); // ttsi.a1 = "there"; // Compile error: final - System.out.println(g()); - System.out.println(h()); - System.out.println(k()); + System.err.println(g()); + System.err.println(h()); + System.err.println(k()); } } /* Output: diff --git a/generics/TupleTest2.java b/generics/TupleTest2.java index 3a0c8d148..a623daa77 100644 --- a/generics/TupleTest2.java +++ b/generics/TupleTest2.java @@ -2,35 +2,35 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -import onjava.*; -import static onjava.Tuple.*; +//import onjava.*; +//import static onjava.Tuple.*; public class TupleTest2 { static Tuple2 f() { - return tuple("hi", 47); + return Tuple.tuple("hi", 47); } - static Tuple2 f2() { return tuple("hi", 47); } + static Tuple2 f2() { return Tuple.tuple("hi", 47); } static Tuple3 g() { - return tuple(new Amphibian(), "hi", 47); + return Tuple.tuple(new Amphibian(), "hi", 47); } static Tuple4 h() { - return tuple( + return Tuple.tuple( new Vehicle(), new Amphibian(), "hi", 47); } static Tuple5 k() { - return tuple(new Vehicle(), new Amphibian(), + return Tuple.tuple(new Vehicle(), new Amphibian(), "hi", 47, 11.1); } public static void main(String[] args) { Tuple2 ttsi = f(); - System.out.println(ttsi); - System.out.println(f2()); - System.out.println(g()); - System.out.println(h()); - System.out.println(k()); + System.err.println(ttsi); + System.err.println(f2()); + System.err.println(g()); + System.err.println(h()); + System.err.println(k()); } } /* Output: diff --git a/generics/WatercolorSets.java b/generics/WatercolorSets.java index 7956778d9..2a22f9b3b 100644 --- a/generics/WatercolorSets.java +++ b/generics/WatercolorSets.java @@ -2,10 +2,11 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -import generics.watercolors.*; +//import generics.watercolors.*; +import watercolors.Watercolors; + import java.util.*; -import static onjava.Sets.*; -import static generics.watercolors.Watercolors.*; +import static watercolors.Watercolors.*; public class WatercolorSets { public static void main(String[] args) { @@ -13,19 +14,19 @@ public static void main(String[] args) { EnumSet.range(BRILLIANT_RED, VIRIDIAN_HUE); Set set2 = EnumSet.range(CERULEAN_BLUE_HUE, BURNT_UMBER); - System.out.println("set1: " + set1); - System.out.println("set2: " + set2); - System.out.println( - "union(set1, set2): " + union(set1, set2)); - Set subset = intersection(set1, set2); - System.out.println( - "intersection(set1, set2): " + subset); - System.out.println("difference(set1, subset): " + - difference(set1, subset)); - System.out.println("difference(set2, subset): " + - difference(set2, subset)); - System.out.println("complement(set1, set2): " + - complement(set1, set2)); + System.err.println("set1: " + set1); + System.err.println("set2: " + set2); + System.err.println( + "union(set1, set2): " + Sets.union(set1, set2)); + Set subset = Sets.intersection(set1, set2); + + System.err.println("intersection(set1, set2)交集: " + subset); + System.err.println("difference(set1, subset): " + + Sets.difference(set1, subset)); + System.err.println("difference(set2, subset): " + + Sets. difference(set2, subset)); + System.err.println("complement(set1, set2): " + + Sets. complement(set1, set2)); } } /* Output: diff --git a/generics/Wildcards.java b/generics/Wildcards.java index 65348ecbb..947b77c41 100644 --- a/generics/Wildcards.java +++ b/generics/Wildcards.java @@ -7,7 +7,7 @@ public class Wildcards { // Raw argument: static void rawArgs(Holder holder, Object arg) { - //- holder.set(arg); +// holder.set(arg); // warning: [unchecked] unchecked call to set(T) // as a member of the raw type Holder // holder.set(arg); @@ -17,7 +17,7 @@ static void rawArgs(Holder holder, Object arg) { // 1 warning // Can't do this; don't have any 'T': - // T t = holder.get(); +// T t = holder.get(); // OK, but type information is lost: Object obj = holder.get(); @@ -53,8 +53,7 @@ static T exact2(Holder holder, T arg) { holder.set(arg); return holder.get(); } - static - T wildSubtype(Holder holder, T arg) { + static T wildSubtype(Holder holder, T arg) { //- holder.set(arg); // error: method set in class Holder // cannot be applied to given types; @@ -75,8 +74,7 @@ T wildSubtype(Holder holder, T arg) { return holder.get(); } - static - void wildSupertype(Holder holder, T arg) { + static void wildSupertype(Holder holder, T arg) { holder.set(arg); //- T t = holder.get(); // error: incompatible types: @@ -97,7 +95,7 @@ void wildSupertype(Holder holder, T arg) { public static void main(String[] args) { Holder raw = new Holder<>(); // Or: - raw = new Holder(); +// raw = new Holder(); Holder qualified = new Holder<>(); Holder unbounded = new Holder<>(); Holder bounded = new Holder<>(); @@ -113,7 +111,7 @@ public static void main(String[] args) { unboundedArg(unbounded, lng); unboundedArg(bounded, lng); - //- Object r1 = exact1(raw); +// Object r1 = exact1(raw); // warning: [unchecked] unchecked method invocation: // method exact1 in class Wildcards is applied // to given types @@ -138,7 +136,7 @@ public static void main(String[] args) { Object r3 = exact1(unbounded); // Must return Object Long r4 = exact1(bounded); - //- Long r5 = exact2(raw, lng); +// Long r5 = exact2(raw, lng); // warning: [unchecked] unchecked method invocation: // method exact2 in class Wildcards is // applied to given types @@ -161,7 +159,7 @@ public static void main(String[] args) { Long r6 = exact2(qualified, lng); - //- Long r7 = exact2(unbounded, lng); +// Long r7 = exact2(unbounded, lng); // error: method exact2 in class Wildcards // cannot be applied to given types; // Long r7 = exact2(unbounded, lng); diff --git a/generics/coffee/Americano.java b/generics/coffee/Americano.java index 96cd4a1fd..92252becb 100644 --- a/generics/coffee/Americano.java +++ b/generics/coffee/Americano.java @@ -2,5 +2,5 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -package generics.coffee; +package coffee; public class Americano extends Coffee {} diff --git a/generics/coffee/Breve.java b/generics/coffee/Breve.java index 329c406b0..d2e95d1b9 100644 --- a/generics/coffee/Breve.java +++ b/generics/coffee/Breve.java @@ -2,5 +2,5 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -package generics.coffee; +package coffee; public class Breve extends Coffee {} diff --git a/generics/coffee/Cappuccino.java b/generics/coffee/Cappuccino.java index 3ce89b50f..c1c7ac270 100644 --- a/generics/coffee/Cappuccino.java +++ b/generics/coffee/Cappuccino.java @@ -2,5 +2,5 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -package generics.coffee; +package coffee; public class Cappuccino extends Coffee {} diff --git a/generics/coffee/Coffee.java b/generics/coffee/Coffee.java index c90d88c19..59b31fbf7 100644 --- a/generics/coffee/Coffee.java +++ b/generics/coffee/Coffee.java @@ -2,7 +2,7 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -package generics.coffee; +package coffee; public class Coffee { private static long counter = 0; diff --git a/generics/coffee/CoffeeSupplier.java b/generics/coffee/CoffeeSupplier.java index fe5dced89..83681183f 100644 --- a/generics/coffee/CoffeeSupplier.java +++ b/generics/coffee/CoffeeSupplier.java @@ -2,8 +2,8 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -// {java generics.coffee.CoffeeSupplier} -package generics.coffee; +// {java CoffeeSupplier} +package coffee; import java.util.*; import java.util.function.*; import java.util.stream.*; @@ -51,11 +51,13 @@ public Iterator iterator() { return new CoffeeIterator(); } public static void main(String[] args) { - Stream.generate(new CoffeeSupplier()) + CoffeeSupplier s = new CoffeeSupplier(); + Stream.generate(s) .limit(5) .forEach(System.out::println); - for(Coffee c : new CoffeeSupplier(5)) - System.out.println(c); + CoffeeSupplier coffees = new CoffeeSupplier(5); + for(Coffee c : coffees) + System.err.println(c); } } /* Output: diff --git a/generics/coffee/Latte.java b/generics/coffee/Latte.java index d735cc876..133509365 100644 --- a/generics/coffee/Latte.java +++ b/generics/coffee/Latte.java @@ -2,5 +2,5 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -package generics.coffee; +package coffee; public class Latte extends Coffee {} diff --git a/generics/coffee/Mocha.java b/generics/coffee/Mocha.java index cc567be1e..912244d4d 100644 --- a/generics/coffee/Mocha.java +++ b/generics/coffee/Mocha.java @@ -2,5 +2,5 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -package generics.coffee; +package coffee; public class Mocha extends Coffee {} diff --git a/generics/watercolors/Watercolors.java b/generics/watercolors/Watercolors.java index 0625e5326..3df9f2025 100644 --- a/generics/watercolors/Watercolors.java +++ b/generics/watercolors/Watercolors.java @@ -2,7 +2,7 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -package generics.watercolors; +package watercolors; public enum Watercolors { ZINC, LEMON_YELLOW, MEDIUM_YELLOW, DEEP_YELLOW, diff --git a/hiding/ChocolateChip.java b/hiding/ChocolateChip.java index 1467fff42..7eb8a5819 100644 --- a/hiding/ChocolateChip.java +++ b/hiding/ChocolateChip.java @@ -7,7 +7,7 @@ public class ChocolateChip extends Cookie { public ChocolateChip() { - System.out.println("ChocolateChip constructor"); + System.err.println("ChocolateChip constructor"); } public void chomp() { //- bite(); // Can't access bite diff --git a/hiding/ChocolateChip2.java b/hiding/ChocolateChip2.java index 03c9d1ab2..5b8266454 100644 --- a/hiding/ChocolateChip2.java +++ b/hiding/ChocolateChip2.java @@ -6,7 +6,7 @@ public class ChocolateChip2 extends Cookie { public ChocolateChip2() { - System.out.println("ChocolateChip2 constructor"); + System.err.println("ChocolateChip2 constructor"); } public void chomp() { bite(); } // Protected method public static void main(String[] args) { diff --git a/hiding/Pie.java b/hiding/Pie.java index 1470fbc33..e5a29d507 100644 --- a/hiding/Pie.java +++ b/hiding/Pie.java @@ -5,5 +5,5 @@ // The other class class Pie { - void f() { System.out.println("Pie.f()"); } + void f() { System.err.println("Pie.f()"); } } diff --git a/hiding/cookie2/Cookie.java b/hiding/cookie2/Cookie.java index aff5bb172..719906373 100644 --- a/hiding/cookie2/Cookie.java +++ b/hiding/cookie2/Cookie.java @@ -6,9 +6,9 @@ public class Cookie { public Cookie() { - System.out.println("Cookie constructor"); + System.err.println("Cookie constructor"); } protected void bite() { - System.out.println("bite"); + System.err.println("bite"); } } diff --git a/hiding/dessert/Cookie.java b/hiding/dessert/Cookie.java index 803e504c2..3537d19de 100644 --- a/hiding/dessert/Cookie.java +++ b/hiding/dessert/Cookie.java @@ -7,7 +7,7 @@ public class Cookie { public Cookie() { - System.out.println("Cookie constructor"); + System.err.println("Cookie constructor"); } - void bite() { System.out.println("bite"); } + void bite() { System.err.println("bite"); } } diff --git a/housekeeping/ArrayClassObj.java b/housekeeping/ArrayClassObj.java index 44e31b59e..5fdcae7c2 100644 --- a/housekeeping/ArrayClassObj.java +++ b/housekeeping/ArrayClassObj.java @@ -9,10 +9,10 @@ public class ArrayClassObj { public static void main(String[] args) { Random rand = new Random(47); Integer[] a = new Integer[rand.nextInt(20)]; - System.out.println("length of a = " + a.length); + System.err.println("length of a = " + a.length); for(int i = 0; i < a.length; i++) a[i] = rand.nextInt(500); // Autoboxing - System.out.println(Arrays.toString(a)); + System.err.println(Arrays.toString(a)); } } /* Output: diff --git a/housekeeping/ArrayInit.java b/housekeeping/ArrayInit.java index 4186bd24e..54863d0f4 100644 --- a/housekeeping/ArrayInit.java +++ b/housekeeping/ArrayInit.java @@ -15,11 +15,16 @@ public static void main(String[] args) { 1, 2, 3, // Autoboxing }; - System.out.println(Arrays.toString(a)); - System.out.println(Arrays.toString(b)); + System.err.println(Arrays.toString(a)); + System.err.println(Arrays.toString(b)); } } /* Output: [1, 2, 3] [1, 2, 3] + +self-note: 在这两种形式中,初始化列表的最后一个逗号是可选的(这一特性使维护长列表变得更容易)。 +尽管第一种形式很有用,但是它更加受限,因为它只能用于数组定义处。 +第二种形式可以用在任何地方,甚至用在方法的内部。[参数是在调用处创建的] + */ diff --git a/housekeeping/ArrayNew.java b/housekeeping/ArrayNew.java index 022cec168..063362edc 100644 --- a/housekeeping/ArrayNew.java +++ b/housekeeping/ArrayNew.java @@ -10,8 +10,8 @@ public static void main(String[] args) { int[] a; Random rand = new Random(47); a = new int[rand.nextInt(20)]; - System.out.println("length of a = " + a.length); - System.out.println(Arrays.toString(a)); + System.err.println("length of a = " + a.length); + System.err.println(Arrays.toString(a)); } } /* Output: diff --git a/housekeeping/ArraysOfPrimitives.java b/housekeeping/ArraysOfPrimitives.java index 165afe896..1c79bfa33 100644 --- a/housekeeping/ArraysOfPrimitives.java +++ b/housekeeping/ArraysOfPrimitives.java @@ -11,7 +11,7 @@ public static void main(String[] args) { for(int i = 0; i < a2.length; i++) a2[i] += 1; for(int i = 0; i < a1.length; i++) - System.out.println("a1[" + i + "] = " + a1[i]); + System.err.println("a1[" + i + "] = " + a1[i]); } } /* Output: diff --git a/housekeeping/AutoboxingVarargs.java b/housekeeping/AutoboxingVarargs.java index c670fa670..4809b0219 100644 --- a/housekeeping/AutoboxingVarargs.java +++ b/housekeeping/AutoboxingVarargs.java @@ -6,8 +6,8 @@ public class AutoboxingVarargs { public static void f(Integer... args) { for(Integer i : args) - System.out.print(i + " "); - System.out.println(); + System.err.print(i + " "); + System.err.println(); } public static void main(String[] args) { f(1, 2); diff --git a/housekeeping/Burrito.java b/housekeeping/Burrito.java index e3fd028bd..01d190c98 100644 --- a/housekeeping/Burrito.java +++ b/housekeeping/Burrito.java @@ -9,17 +9,17 @@ public Burrito(Spiciness degree) { this.degree = degree; } public void describe() { - System.out.print("This burrito is "); + System.err.print("This burrito is "); switch(degree) { - case NOT: System.out.println( + case NOT: System.err.println( "not spicy at all."); break; case MILD: - case MEDIUM: System.out.println("a little hot."); + case MEDIUM: System.err.println("a little hot."); break; case HOT: case FLAMING: - default: System.out.println("maybe too hot."); + default: System.err.println("maybe too hot."); } } public static void main(String[] args) { diff --git a/housekeeping/Demotion.java b/housekeeping/Demotion.java index ad2c4e86b..8c9d7fffe 100644 --- a/housekeeping/Demotion.java +++ b/housekeeping/Demotion.java @@ -6,18 +6,18 @@ public class Demotion { void f1(double x) { - System.out.println("f1(double)"); + System.err.println("f1(double)"); } - void f2(float x) { System.out.println("f2(float)"); } - void f3(long x) { System.out.println("f3(long)"); } - void f4(int x) { System.out.println("f4(int)"); } - void f5(short x) { System.out.println("f5(short)"); } - void f6(byte x) { System.out.println("f6(byte)"); } - void f7(char x) { System.out.println("f7(char)"); } + void f2(float x) { System.err.println("f2(float)"); } + void f3(long x) { System.err.println("f3(long)"); } + void f4(int x) { System.err.println("f4(int)"); } + void f5(short x) { System.err.println("f5(short)"); } + void f6(byte x) { System.err.println("f6(byte)"); } + void f7(char x) { System.err.println("f7(char)"); } void testDouble() { double x = 0; - System.out.println("double argument:"); + System.err.println("double argument:"); f1(x); f2((float)x); f3((long)x); diff --git a/housekeeping/DynamicArray.java b/housekeeping/DynamicArray.java index 726ec034a..52b7b254e 100644 --- a/housekeeping/DynamicArray.java +++ b/housekeeping/DynamicArray.java @@ -13,7 +13,7 @@ public static void main(String[] args) { class Other { public static void main(String[] args) { for(String s : args) - System.out.print(s + " "); + System.err.print(s + " "); } } /* Output: diff --git a/housekeeping/EnumOrder.java b/housekeeping/EnumOrder.java index a3c962847..2c94b55bc 100644 --- a/housekeeping/EnumOrder.java +++ b/housekeeping/EnumOrder.java @@ -6,7 +6,7 @@ public class EnumOrder { public static void main(String[] args) { for(Spiciness s : Spiciness.values()) - System.out.println( + System.err.println( s + ", ordinal " + s.ordinal()); } } @@ -16,4 +16,7 @@ public static void main(String[] args) { MEDIUM, ordinal 2 HOT, ordinal 3 FLAMING, ordinal 4 +self-note: +ordinal() 方法表示某个特定 enum 常量的声明顺序, +static values() 方法按照 enum 常量的声明顺序,生成这些常量值构成的数组 */ diff --git a/housekeeping/ExplicitStatic.java b/housekeeping/ExplicitStatic.java index 7d9cb31ad..085cdcd46 100644 --- a/housekeeping/ExplicitStatic.java +++ b/housekeeping/ExplicitStatic.java @@ -6,10 +6,10 @@ class Cup { Cup(int marker) { - System.out.println("Cup(" + marker + ")"); + System.err.println("Cup(" + marker + ")"); } void f(int marker) { - System.out.println("f(" + marker + ")"); + System.err.println("f(" + marker + ")"); } } @@ -21,14 +21,14 @@ class Cups { cup2 = new Cup(2); } Cups() { - System.out.println("Cups()"); + System.err.println("Cups()"); } } public class ExplicitStatic { public static void main(String[] args) { - System.out.println("Inside main()"); - Cups.cup1.f(99); // [1] + System.err.println("Inside main()"); +// Cups.cup1.f(99); // [1] } // static Cups cups1 = new Cups(); // [2] // static Cups cups2 = new Cups(); // [2] @@ -39,3 +39,7 @@ Inside main() Cup(2) f(99) */ + +/** + * self-note 静态初始化只有在必要时刻才会进行。(如果同时注释 [1] 和 [2] 处,那么 Cups 的静态初始化就不会进行。) + **/ diff --git a/housekeeping/Flower.java b/housekeeping/Flower.java index a62d7cbe5..870869529 100644 --- a/housekeeping/Flower.java +++ b/housekeeping/Flower.java @@ -9,12 +9,12 @@ public class Flower { String s = "initial value"; Flower(int petals) { petalCount = petals; - System.out.println( + System.err.println( "Constructor w/ int arg only, petalCount= " + petalCount); } Flower(String ss) { - System.out.println( + System.err.println( "Constructor w/ String arg only, s = " + ss); s = ss; } @@ -22,15 +22,15 @@ public class Flower { this(petals); //- this(s); // Can't call two! this.s = s; // Another use of "this" - System.out.println("String & int args"); + System.err.println("String & int args"); } Flower() { this("hi", 47); - System.out.println("no-arg constructor"); + System.err.println("no-arg constructor"); } void printPetalCount() { //- this(11); // Not inside non-constructor! - System.out.println( + System.err.println( "petalCount = " + petalCount + " s = "+ s); } public static void main(String[] args) { diff --git a/housekeeping/InitialValues.java b/housekeeping/InitialValues.java index dced4dd2e..38773aa30 100644 --- a/housekeeping/InitialValues.java +++ b/housekeeping/InitialValues.java @@ -15,16 +15,16 @@ public class InitialValues { double d; InitialValues reference; void printInitialValues() { - System.out.println("Data type Initial value"); - System.out.println("boolean " + t); - System.out.println("char [" + c + "]"); - System.out.println("byte " + b); - System.out.println("short " + s); - System.out.println("int " + i); - System.out.println("long " + l); - System.out.println("float " + f); - System.out.println("double " + d); - System.out.println("reference " + reference); + System.err.println("Data type Initial value"); + System.err.println("boolean " + t); + System.err.println("char [" + c + "]"); + System.err.println("byte " + b); + System.err.println("short " + s); + System.err.println("int " + i); + System.err.println("long " + l); + System.err.println("float " + f); + System.err.println("double " + d); + System.err.println("reference " + reference); } public static void main(String[] args) { new InitialValues().printInitialValues(); diff --git a/housekeeping/Leaf.java b/housekeeping/Leaf.java index f9c560b24..df9a1c020 100644 --- a/housekeeping/Leaf.java +++ b/housekeeping/Leaf.java @@ -11,7 +11,7 @@ Leaf increment() { return this; } void print() { - System.out.println("i = " + i); + System.err.println("i = " + i); } public static void main(String[] args) { Leaf x = new Leaf(); diff --git a/housekeeping/Mugs.java b/housekeeping/Mugs.java index e4ebba695..bb627d9c8 100644 --- a/housekeeping/Mugs.java +++ b/housekeeping/Mugs.java @@ -6,7 +6,7 @@ class Mug { Mug(int marker) { - System.out.println("Mug(" + marker + ")"); + System.err.println("Mug(" + marker + ")"); } } @@ -16,20 +16,20 @@ public class Mugs { { // [1] mug1 = new Mug(1); mug2 = new Mug(2); - System.out.println("mug1 & mug2 initialized"); + System.err.println("mug1 & mug2 initialized"); } Mugs() { - System.out.println("Mugs()"); + System.err.println("Mugs()"); } Mugs(int i) { - System.out.println("Mugs(int)"); + System.err.println("Mugs(int)"); } public static void main(String[] args) { - System.out.println("Inside main()"); + System.err.println("Inside main()"); new Mugs(); - System.out.println("new Mugs() completed"); + System.err.println("new Mugs() completed"); new Mugs(1); - System.out.println("new Mugs(1) completed"); + System.err.println("new Mugs(1) completed"); } } /* Output: diff --git a/housekeeping/NewVarArgs.java b/housekeeping/NewVarArgs.java index 291dd1346..c877f7a58 100644 --- a/housekeeping/NewVarArgs.java +++ b/housekeeping/NewVarArgs.java @@ -7,8 +7,8 @@ public class NewVarArgs { static void printArray(Object... args) { for(Object obj : args) - System.out.print(obj + " "); - System.out.println(); + System.err.print(obj + " "); + System.err.println(); } public static void main(String[] args) { // Can take individual elements: diff --git a/housekeeping/OptionalTrailingArguments.java b/housekeeping/OptionalTrailingArguments.java index d7ee9fbbf..212357336 100644 --- a/housekeeping/OptionalTrailingArguments.java +++ b/housekeeping/OptionalTrailingArguments.java @@ -5,10 +5,10 @@ public class OptionalTrailingArguments { static void f(int required, String... trailing) { - System.out.print("required: " + required + " "); + System.err.print("required: " + required + " "); for(String s : trailing) - System.out.print(s + " "); - System.out.println(); + System.err.print(s + " "); + System.err.println(); } public static void main(String[] args) { f(1, "one"); diff --git a/housekeeping/OrderOfInitialization.java b/housekeeping/OrderOfInitialization.java index c715ed7c5..0d830fa94 100644 --- a/housekeeping/OrderOfInitialization.java +++ b/housekeeping/OrderOfInitialization.java @@ -8,7 +8,7 @@ // Window object, you'll see a message: class Window { Window(int marker) { - System.out.println("Window(" + marker + ")"); + System.err.println("Window(" + marker + ")"); } } @@ -16,11 +16,11 @@ class House { Window w1 = new Window(1); // Before constructor House() { // Show that we're in the constructor: - System.out.println("House()"); + System.err.println("House()"); w3 = new Window(33); // Reinitialize w3 } Window w2 = new Window(2); // After constructor - void f() { System.out.println("f()"); } + void f() { System.err.println("f()"); } Window w3 = new Window(3); // At end } diff --git a/housekeeping/Overloading.java b/housekeeping/Overloading.java index 99d21bf80..5e4578b16 100644 --- a/housekeeping/Overloading.java +++ b/housekeeping/Overloading.java @@ -7,20 +7,20 @@ class Tree { int height; Tree() { - System.out.println("Planting a seedling"); + System.err.println("Planting a seedling"); height = 0; } Tree(int initialHeight) { height = initialHeight; - System.out.println("Creating new Tree that is " + + System.err.println("Creating new Tree that is " + height + " feet tall"); } void info() { - System.out.println( + System.err.println( "Tree is " + height + " feet tall"); } void info(String s) { - System.out.println( + System.err.println( s + ": Tree is " + height + " feet tall"); } } diff --git a/housekeeping/OverloadingOrder.java b/housekeeping/OverloadingOrder.java index 42f6466ec..fbda7c624 100644 --- a/housekeeping/OverloadingOrder.java +++ b/housekeeping/OverloadingOrder.java @@ -6,10 +6,10 @@ public class OverloadingOrder { static void f(String s, int i) { - System.out.println("String: " + s + ", int: " + i); + System.err.println("String: " + s + ", int: " + i); } static void f(int i, String s) { - System.out.println("int: " + i + ", String: " + s); + System.err.println("int: " + i + ", String: " + s); } public static void main(String[] args) { f("String first", 11); diff --git a/housekeeping/OverloadingVarargs.java b/housekeeping/OverloadingVarargs.java index c13b7406f..68db5b1ef 100644 --- a/housekeeping/OverloadingVarargs.java +++ b/housekeeping/OverloadingVarargs.java @@ -5,19 +5,19 @@ public class OverloadingVarargs { static void f(Character... args) { - System.out.print("first"); + System.err.print("first"); for(Character c : args) - System.out.print(" " + c); - System.out.println(); + System.err.print(" " + c); + System.err.println(); } static void f(Integer... args) { - System.out.print("second"); + System.err.print("second"); for(Integer i : args) - System.out.print(" " + i); - System.out.println(); + System.err.print(" " + i); + System.err.println(); } static void f(Long... args) { - System.out.println("third"); + System.err.println("third"); } public static void main(String[] args) { f('a', 'b', 'c'); diff --git a/housekeeping/OverloadingVarargs2.java b/housekeeping/OverloadingVarargs2.java index c3a098451..4e96ffe1e 100644 --- a/housekeeping/OverloadingVarargs2.java +++ b/housekeeping/OverloadingVarargs2.java @@ -3,13 +3,13 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {WillNotCompile} - +//self-note: [WillNotCompile] 注释把该文件排除在了本书的 Gradle 构建之外。 public class OverloadingVarargs2 { static void f(float i, Character... args) { - System.out.println("first"); + System.err.println("first"); } static void f(Character... args) { - System.out.print("second"); + System.err.print("second"); } public static void main(String[] args) { f(1, 'a'); diff --git a/housekeeping/OverloadingVarargs3.java b/housekeeping/OverloadingVarargs3.java index 23e757ec5..eb9af4461 100644 --- a/housekeeping/OverloadingVarargs3.java +++ b/housekeeping/OverloadingVarargs3.java @@ -5,10 +5,10 @@ public class OverloadingVarargs3 { static void f(float i, Character... args) { - System.out.println("first"); + System.err.println("first"); } static void f(char c, Character... args) { - System.out.println("second"); + System.err.println("second"); } public static void main(String[] args) { f(1, 'a'); @@ -18,4 +18,6 @@ public static void main(String[] args) { /* Output: first second +self-note : 给这两个方法都添加一个非可变参数,解决了OverloadingVarargs2 中的 "引用不明确"问题, +然而这也是不好的做法,你应该总是在"重载方法的其中一个版本"上使用可变参数列表,或者压根不用它。 */ diff --git a/housekeeping/PassingThis.java b/housekeeping/PassingThis.java index ce725eabf..fd137ecaa 100644 --- a/housekeeping/PassingThis.java +++ b/housekeeping/PassingThis.java @@ -6,7 +6,7 @@ class Person { public void eat(Apple apple) { Apple peeled = apple.getPeeled(); - System.out.println("Yummy"); + System.err.println("Yummy"); } } diff --git a/housekeeping/PrimitiveOverloading.java b/housekeeping/PrimitiveOverloading.java index 1d8c1e2c6..ea02ed980 100644 --- a/housekeeping/PrimitiveOverloading.java +++ b/housekeeping/PrimitiveOverloading.java @@ -5,87 +5,87 @@ // Promotion of primitives and overloading public class PrimitiveOverloading { - void f1(char x) { System.out.print("f1(char) "); } - void f1(byte x) { System.out.print("f1(byte) "); } - void f1(short x) { System.out.print("f1(short) "); } - void f1(int x) { System.out.print("f1(int) "); } - void f1(long x) { System.out.print("f1(long) "); } - void f1(float x) { System.out.print("f1(float) "); } - void f1(double x) { System.out.print("f1(double) "); } + void f1(char x) { System.err.print("f1(char) "); } + void f1(byte x) { System.err.print("f1(byte) "); } + void f1(short x) { System.err.print("f1(short) "); } + void f1(int x) { System.err.print("f1(int) "); } + void f1(long x) { System.err.print("f1(long) "); } + void f1(float x) { System.err.print("f1(float) "); } + void f1(double x) { System.err.print("f1(double) "); } - void f2(byte x) { System.out.print("f2(byte) "); } - void f2(short x) { System.out.print("f2(short) "); } - void f2(int x) { System.out.print("f2(int) "); } - void f2(long x) { System.out.print("f2(long) "); } - void f2(float x) { System.out.print("f2(float) "); } - void f2(double x) { System.out.print("f2(double) "); } + void f2(byte x) { System.err.print("f2(byte) "); } + void f2(short x) { System.err.print("f2(short) "); } + void f2(int x) { System.err.print("f2(int) "); } + void f2(long x) { System.err.print("f2(long) "); } + void f2(float x) { System.err.print("f2(float) "); } + void f2(double x) { System.err.print("f2(double) "); } - void f3(short x) { System.out.print("f3(short) "); } - void f3(int x) { System.out.print("f3(int) "); } - void f3(long x) { System.out.print("f3(long) "); } - void f3(float x) { System.out.print("f3(float) "); } - void f3(double x) { System.out.print("f3(double) "); } + void f3(short x) { System.err.print("f3(short) "); } + void f3(int x) { System.err.print("f3(int) "); } + void f3(long x) { System.err.print("f3(long) "); } + void f3(float x) { System.err.print("f3(float) "); } + void f3(double x) { System.err.print("f3(double) "); } - void f4(int x) { System.out.print("f4(int) "); } - void f4(long x) { System.out.print("f4(long) "); } - void f4(float x) { System.out.print("f4(float) "); } - void f4(double x) { System.out.print("f4(double) "); } + void f4(int x) { System.err.print("f4(int) "); } + void f4(long x) { System.err.print("f4(long) "); } + void f4(float x) { System.err.print("f4(float) "); } + void f4(double x) { System.err.print("f4(double) "); } - void f5(long x) { System.out.print("f5(long) "); } - void f5(float x) { System.out.print("f5(float) "); } - void f5(double x) { System.out.print("f5(double) "); } + void f5(long x) { System.err.print("f5(long) "); } + void f5(float x) { System.err.print("f5(float) "); } + void f5(double x) { System.err.print("f5(double) "); } - void f6(float x) { System.out.print("f6(float) "); } - void f6(double x) { System.out.print("f6(double) "); } + void f6(float x) { System.err.print("f6(float) "); } + void f6(double x) { System.err.print("f6(double) "); } - void f7(double x) { System.out.print("f7(double) "); } + void f7(double x) { System.err.print("f7(double) "); } void testConstVal() { - System.out.print("5: "); + System.err.print("5: "); f1(5);f2(5);f3(5);f4(5);f5(5);f6(5);f7(5); - System.out.println(); + System.err.println(); } void testChar() { char x = 'x'; - System.out.print("char: "); + System.err.print("char: "); f1(x);f2(x);f3(x);f4(x);f5(x);f6(x);f7(x); - System.out.println(); + System.err.println(); } void testByte() { byte x = 0; - System.out.print("byte: "); + System.err.print("byte: "); f1(x);f2(x);f3(x);f4(x);f5(x);f6(x);f7(x); - System.out.println(); + System.err.println(); } void testShort() { short x = 0; - System.out.print("short: "); + System.err.print("short: "); f1(x);f2(x);f3(x);f4(x);f5(x);f6(x);f7(x); - System.out.println(); + System.err.println(); } void testInt() { int x = 0; - System.out.print("int: "); + System.err.print("int: "); f1(x);f2(x);f3(x);f4(x);f5(x);f6(x);f7(x); - System.out.println(); + System.err.println(); } void testLong() { long x = 0; - System.out.print("long: "); + System.err.print("long: "); f1(x);f2(x);f3(x);f4(x);f5(x);f6(x);f7(x); - System.out.println(); + System.err.println(); } void testFloat() { float x = 0; - System.out.print("float: "); + System.err.print("float: "); f1(x);f2(x);f3(x);f4(x);f5(x);f6(x);f7(x); - System.out.println(); + System.err.println(); } void testDouble() { double x = 0; - System.out.print("double: "); + System.err.print("double: "); f1(x);f2(x);f3(x);f4(x);f5(x);f6(x);f7(x); - System.out.println(); + System.err.println(); } public static void main(String[] args) { PrimitiveOverloading p = @@ -117,4 +117,7 @@ public static void main(String[] args) { f5(float) f6(float) f7(double) double: f1(double) f2(double) f3(double) f4(double) f5(double) f6(double) f7(double) + + +self-note: 小参数类型会自动入参 大参数类型的方法 */ diff --git a/housekeeping/SimpleConstructor.java b/housekeeping/SimpleConstructor.java index c6917c33d..f81c9694c 100644 --- a/housekeeping/SimpleConstructor.java +++ b/housekeeping/SimpleConstructor.java @@ -6,7 +6,7 @@ class Rock { Rock() { // This is the constructor - System.out.print("Rock "); + System.err.print("Rock "); } } diff --git a/housekeeping/SimpleConstructor2.java b/housekeeping/SimpleConstructor2.java index 4a191af78..ab7ea9a74 100644 --- a/housekeeping/SimpleConstructor2.java +++ b/housekeeping/SimpleConstructor2.java @@ -6,7 +6,7 @@ class Rock2 { Rock2(int i) { - System.out.print("Rock " + i + " "); + System.err.print("Rock " + i + " "); } } diff --git a/housekeeping/SimpleEnumUse.java b/housekeeping/SimpleEnumUse.java index cc0de33b2..8e2459eb4 100644 --- a/housekeeping/SimpleEnumUse.java +++ b/housekeeping/SimpleEnumUse.java @@ -6,9 +6,11 @@ public class SimpleEnumUse { public static void main(String[] args) { Spiciness howHot = Spiciness.MEDIUM; - System.out.println(howHot); + System.err.println(howHot); } } /* Output: MEDIUM + +self-note ordinal() 方法表示某个特定 enum 常量的声明顺序 */ diff --git a/housekeeping/StaticInitialization.java b/housekeeping/StaticInitialization.java index 0cfe99aea..d8d9264b0 100644 --- a/housekeeping/StaticInitialization.java +++ b/housekeeping/StaticInitialization.java @@ -6,21 +6,21 @@ class Bowl { Bowl(int marker) { - System.out.println("Bowl(" + marker + ")"); + System.err.println("Bowl(" + marker + ")"); } void f1(int marker) { - System.out.println("f1(" + marker + ")"); + System.err.println("f1(" + marker + ")"); } } class Table { static Bowl bowl1 = new Bowl(1); Table() { - System.out.println("Table()"); + System.err.println("Table()"); bowl2.f1(1); } void f2(int marker) { - System.out.println("f2(" + marker + ")"); + System.err.println("f2(" + marker + ")"); } static Bowl bowl2 = new Bowl(2); } @@ -29,25 +29,26 @@ class Cupboard { Bowl bowl3 = new Bowl(3); static Bowl bowl4 = new Bowl(4); Cupboard() { - System.out.println("Cupboard()"); + System.err.println("Cupboard()"); bowl4.f1(2); } void f3(int marker) { - System.out.println("f3(" + marker + ")"); + System.err.println("f3(" + marker + ")"); } static Bowl bowl5 = new Bowl(5); } public class StaticInitialization { + public static void main(String[] args) { - System.out.println("main creating new Cupboard()"); + System.err.println("main creating new Cupboard()"); new Cupboard(); - System.out.println("main creating new Cupboard()"); + System.err.println("main creating new Cupboard()"); new Cupboard(); table.f2(1); cupboard.f3(1); } - static Table table = new Table(); + static Table table = new Table(); // self-note *** table的构造方法被static提前了 static Cupboard cupboard = new Cupboard(); } /* Output: @@ -71,3 +72,34 @@ main creating new Cupboard() f2(1) f3(1) */ + +/** + * self-note + 父类--静态变量 + 父类--静态初始化块 + 子类--静态变量 + 子类--静态初始化块 + ************* main start *************** + 父类--变量 + 父类--初始化块 + 父类--构造器 + 子类--变量 + 子类--初始化块 + 子类--构造器 + ************* 第二次创建不会加载父类 ************* + 父类--变量 + 父类--初始化块 + 父类--构造器 + 子类--变量 + 子类--初始化块 + 子类--构造器 + ************* main end *************** + + 结果分析: + 很显然在加载main方法后,静态变量不管父类还是子类的都执行了,然后才是父类和子类的的普通变量和构造器。这是因为,当要创建子类这个对象时,发现这个类需要一个父类,所以把父类的.class加载进来,然后依次初始化其普通变量和初始化代码块,最后其构造器,然后可以开始子类的工作,把子类的.class加载进来,在做子类的工作。 + + 另外在Java中子类中都会有默认的调用父类的默认构造函数即super(),当仅仅有默认构造函数里 + Java替你做了,我们可以做个实验,如果在父类中注释掉默认构造函数,加一个有参的构造函数时,如果 + 子类中不加super(argument),此时会报语法错误 + 如果我们把Main方法中的内容全注释掉,你会发现只会输出 + **/ diff --git a/housekeeping/TerminationCondition.java b/housekeeping/TerminationCondition.java index dc8d347b8..d2180510c 100644 --- a/housekeeping/TerminationCondition.java +++ b/housekeeping/TerminationCondition.java @@ -18,7 +18,7 @@ void checkIn() { @Override public void finalize() { if(checkedOut) - System.out.println("Error: checked out"); + System.err.println("Error: checked out"); // Normally, you'll also do this: // super.finalize(); // Call the base-class version } diff --git a/housekeeping/VarArgs.java b/housekeeping/VarArgs.java index 73a94c392..4fccb724f 100644 --- a/housekeeping/VarArgs.java +++ b/housekeeping/VarArgs.java @@ -9,8 +9,8 @@ class A {} public class VarArgs { static void printArray(Object[] args) { for(Object obj : args) - System.out.print(obj + " "); - System.out.println(); + System.err.print(obj + " "); + System.err.println(); } public static void main(String[] args) { printArray(new Object[]{ diff --git a/housekeeping/VarargType.java b/housekeeping/VarargType.java index 5b25b0536..9c557d1fc 100644 --- a/housekeeping/VarargType.java +++ b/housekeeping/VarargType.java @@ -5,19 +5,19 @@ public class VarargType { static void f(Character... args) { - System.out.print(args.getClass()); - System.out.println(" length " + args.length); + System.err.print(args.getClass()); + System.err.println(" length " + args.length); } static void g(int... args) { - System.out.print(args.getClass()); - System.out.println(" length " + args.length); + System.err.print(args.getClass()); + System.err.println(" length " + args.length); } public static void main(String[] args) { f('a'); f(); g(1); g(); - System.out.println("int[]: " + + System.err.println("int[]: " + new int[0].getClass()); } } @@ -27,4 +27,6 @@ class [Ljava.lang.Character; length 0 class [I length 1 class [I length 0 int[]: class [I + +self-note:前导的 "[" 代表这是一个后面紧随的类型的数组,"I" 表示基本类型 int; */ diff --git a/innerclasses/AnonymousConstructor.java b/innerclasses/AnonymousConstructor.java index d8e08e7c9..17d92a680 100644 --- a/innerclasses/AnonymousConstructor.java +++ b/innerclasses/AnonymousConstructor.java @@ -6,7 +6,7 @@ abstract class Base { Base(int i) { - System.out.println("Base constructor, i = " + i); + System.err.println("Base constructor, i = " + i); } public abstract void f(); } @@ -14,11 +14,11 @@ abstract class Base { public class AnonymousConstructor { public static Base getBase(int i) { return new Base(i) { - { System.out.println( + { System.err.println( "Inside instance initializer"); } @Override public void f() { - System.out.println("In anonymous f()"); + System.err.println("In anonymous f()"); } }; } diff --git a/innerclasses/BigEgg.java b/innerclasses/BigEgg.java index 7b2c36246..a85d48ae1 100644 --- a/innerclasses/BigEgg.java +++ b/innerclasses/BigEgg.java @@ -8,11 +8,11 @@ class Egg { private Yolk y; protected class Yolk { public Yolk() { - System.out.println("Egg.Yolk()"); + System.err.println("Egg.Yolk()"); } } Egg() { - System.out.println("New Egg()"); + System.err.println("New Egg()"); y = new Yolk(); } } @@ -20,7 +20,7 @@ public Yolk() { public class BigEgg extends Egg { public class Yolk { public Yolk() { - System.out.println("BigEgg.Yolk()"); + System.err.println("BigEgg.Yolk()"); } } public static void main(String[] args) { diff --git a/innerclasses/BigEgg2.java b/innerclasses/BigEgg2.java index 1631008d2..443e0fe7c 100644 --- a/innerclasses/BigEgg2.java +++ b/innerclasses/BigEgg2.java @@ -7,31 +7,34 @@ class Egg2 { protected class Yolk { public Yolk() { - System.out.println("Egg2.Yolk()"); + System.err.println("Egg2.Yolk()"); } public void f() { - System.out.println("Egg2.Yolk.f()"); + System.err.println("Egg2.Yolk.f()"); } } private Yolk y = new Yolk(); - Egg2() { System.out.println("New Egg2()"); } - public void insertYolk(Yolk yy) { y = yy; } + Egg2() { System.err.println("New Egg2()"); } + public void insertYolk(Yolk yy) { + System.err.println("y = yy;");y = yy; } public void g() { y.f(); } } public class BigEgg2 extends Egg2 { public class Yolk extends Egg2.Yolk { public Yolk() { - System.out.println("BigEgg2.Yolk()"); + System.err.println("BigEgg2.Yolk()"); } @Override public void f() { - System.out.println("BigEgg2.Yolk.f()"); + System.err.println("BigEgg2.Yolk.f()"); } } - public BigEgg2() { insertYolk(new Yolk()); } + public BigEgg2() { + System.err.println("insertYolk(new Yolk());");insertYolk(new Yolk()); } public static void main(String[] args) { Egg2 e2 = new BigEgg2(); + System.err.println("before g()-------------"); e2.g(); } } diff --git a/innerclasses/Callbacks.java b/innerclasses/Callbacks.java index d16593322..509095991 100644 --- a/innerclasses/Callbacks.java +++ b/innerclasses/Callbacks.java @@ -16,37 +16,47 @@ class Callee1 implements Incrementable { @Override public void increment() { i++; - System.out.println(i); + System.err.println("callee1: "+i); } } class MyIncrement { public void increment() { - System.out.println("Other operation"); + System.err.println("MyIncrement Other operation"); } static void f(MyIncrement mi) { mi.increment(); } } // If your class must implement increment() in // some other way, you must use an inner class: + +/** + * self-note: + * Callee2 继承自 MyIncrement,后者已经有了一个不同的 increment() 方法, + * 并且与 Incrementable 接口期望的 increment() 方法完全不相关。 + * 所以如果 Callee2 继承了 MyIncrement, + * 就不能为了 Incrementable 的用途而覆盖 increment() 方法,于是只能使用内部类独立地实现 Incrementable, + * 还要注意,当创建了一个内部类时,并没有在外部类的接口中添加东西,也没有修改外部类的接口。 + */ class Callee2 extends MyIncrement { private int i = 0; @Override public void increment() { super.increment(); i++; - System.out.println(i); + System.err.println(i); } private class Closure implements Incrementable { @Override public void increment() { // Specify outer-class method, otherwise // you'll get an infinite recursion: + System.err.print("callbackReference->"); Callee2.this.increment(); } } Incrementable getCallbackReference() { - return new Closure(); + return new Closure();//--------------------返回一个内部类对象,这个内部类对象包含了外部类对象的信息 } } @@ -55,19 +65,23 @@ class Caller { Caller(Incrementable cbh) { callbackReference = cbh; } - void go() { callbackReference.increment(); } + void go() { callbackReference.increment(); } //这里称为 回调; + //回调就是在闭包的基础上实现的,返回的内部类对象可以调用外部类中的方法。 + //使用闭包+回调的原因,不能覆盖原来的increment方法,也没有修改外部类的接口。 } public class Callbacks { public static void main(String[] args) { Callee1 c1 = new Callee1(); - Callee2 c2 = new Callee2(); - MyIncrement.f(c2); Caller caller1 = new Caller(c1); - Caller caller2 = - new Caller(c2.getCallbackReference()); caller1.go(); caller1.go(); + + System.err.println("s-------------------------------------------"); + + Callee2 c2 = new Callee2(); + MyIncrement.f(c2); + Caller caller2 = new Caller(c2.getCallbackReference()); caller2.go(); caller2.go(); } diff --git a/innerclasses/ClassInInterface.java b/innerclasses/ClassInInterface.java index c3cc0589b..86b2fc2ea 100644 --- a/innerclasses/ClassInInterface.java +++ b/innerclasses/ClassInInterface.java @@ -9,7 +9,7 @@ public interface ClassInInterface { class Test implements ClassInInterface { @Override public void howdy() { - System.out.println("Howdy!"); + System.err.println("Howdy!"); } public static void main(String[] args) { new Test().howdy(); diff --git a/innerclasses/DotNew.java b/innerclasses/DotNew.java index 317400e80..2457ea235 100644 --- a/innerclasses/DotNew.java +++ b/innerclasses/DotNew.java @@ -5,9 +5,21 @@ // Creating an inner class directly using .new syntax public class DotNew { - public class Inner {} + public class Inner { + public Inner() { + System.err.println("inner is be done"); + } + } + public Inner getInner(){ + return new Inner(); + } public static void main(String[] args) { DotNew dn = new DotNew(); - DotNew.Inner dni = dn.new Inner(); + //fun1 + DotNew.Inner dni = dn.new Inner();//self-note: 直接获取创建内部对象的方法, .new + //fun2 + DotNew.Inner dni2 = dn.getInner(); + DotNew.Inner dni3 = dn.getInner(); + } } diff --git a/innerclasses/DotThis.java b/innerclasses/DotThis.java index b87cb1f4c..8e450665d 100644 --- a/innerclasses/DotThis.java +++ b/innerclasses/DotThis.java @@ -5,7 +5,7 @@ // Accessing the outer-class object public class DotThis { - void f() { System.out.println("DotThis.f()"); } + void f() { System.err.println("DotThis.f()"); } public class Inner { public DotThis outer() { return DotThis.this; diff --git a/innerclasses/GreenhouseController.java b/innerclasses/GreenhouseController.java index cf3ec6530..8ef73f477 100644 --- a/innerclasses/GreenhouseController.java +++ b/innerclasses/GreenhouseController.java @@ -3,7 +3,10 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Configure and execute the greenhouse system -import innerclasses.controller.*; +import controller.*; + +import java.util.ArrayList; +import java.util.Arrays; public class GreenhouseController { public static void main(String[] args) { @@ -12,6 +15,8 @@ public static void main(String[] args) { // configuration information from a text file: gc.addEvent(gc.new Bell(900)); Event[] eventList = { +// gc.new Bell(900) , + gc.new ThermostatNight(0), gc.new LightOn(200), gc.new LightOff(400), @@ -19,9 +24,11 @@ gc.new WaterOn(600), gc.new WaterOff(800), gc.new ThermostatDay(1400) }; - gc.addEvent(gc.new Restart(2000, eventList)); - gc.addEvent( - new GreenhouseControls.Terminate(5000)); + gc.setEventList(new ArrayList<>(Arrays.asList(eventList))); + +// gc.addEvent(gc.new Restart(2000, eventList)); + /* gc.addEvent( + new GreenhouseControls.Terminate(5000));*/ gc.run(); } } diff --git a/innerclasses/GreenhouseControls.java b/innerclasses/GreenhouseControls.java index 57458d66f..329d46282 100644 --- a/innerclasses/GreenhouseControls.java +++ b/innerclasses/GreenhouseControls.java @@ -6,7 +6,7 @@ // control system, all in a single class. Inner // classes allow you to encapsulate different // functionality for each type of event. -import innerclasses.controller.*; +import controller.*; public class GreenhouseControls extends Controller { private boolean light = false; @@ -115,8 +115,7 @@ public String toString() { } public class Restart extends Event { private Event[] eventList; - public - Restart(long delayTime, Event[] eventList) { + public Restart(long delayTime, Event[] eventList) { super(delayTime); this.eventList = eventList; for(Event e : eventList) @@ -133,7 +132,7 @@ public void action() { } @Override public String toString() { - return "Restarting system"; + return "Restarting system----------------重启"; } } public static class Terminate extends Event { diff --git a/innerclasses/LocalInnerClass.java b/innerclasses/LocalInnerClass.java index 015108545..60b03bea8 100644 --- a/innerclasses/LocalInnerClass.java +++ b/innerclasses/LocalInnerClass.java @@ -15,11 +15,11 @@ Counter getCounter(final String name) { class LocalCounter implements Counter { LocalCounter() { // Local inner class can have a constructor - System.out.println("LocalCounter()"); + System.err.println("LocalCounter()"); } @Override public int next() { - System.out.print(name); // Access local final + System.err.print(name); // Access local final return count++; } } @@ -31,11 +31,11 @@ Counter getCounter2(final String name) { // Anonymous inner class cannot have a named // constructor, only an instance initializer: { - System.out.println("Counter()"); + System.err.println("Counter()"); } @Override public int next() { - System.out.print(name); // Access local final + System.err.print(name); // Access local final return count++; } }; @@ -46,9 +46,9 @@ public static void main(String[] args) { c1 = lic.getCounter("Local inner "), c2 = lic.getCounter2("Anonymous inner "); for(int i = 0; i < 5; i++) - System.out.println(c1.next()); + System.err.println(c1.next()); for(int i = 0; i < 5; i++) - System.out.println(c2.next()); + System.err.println(c2.next()); } } /* Output: diff --git a/innerclasses/Parcel1.java b/innerclasses/Parcel1.java index 94464cbcd..d971bf714 100644 --- a/innerclasses/Parcel1.java +++ b/innerclasses/Parcel1.java @@ -21,7 +21,7 @@ class Destination { public void ship(String dest) { Contents c = new Contents(); Destination d = new Destination(dest); - System.out.println(d.readLabel()); + System.err.println(d.readLabel()); } public static void main(String[] args) { Parcel1 p = new Parcel1(); diff --git a/innerclasses/Parcel10.java b/innerclasses/Parcel10.java index 7150c1929..8d3f986e6 100644 --- a/innerclasses/Parcel10.java +++ b/innerclasses/Parcel10.java @@ -6,15 +6,14 @@ // construction on an anonymous inner class public class Parcel10 { - public Destination - destination(final String dest, final float price) { + public Destination destination(final String dest, final float price) { return new Destination() { private int cost; // Instance initialization for each object: { cost = Math.round(price); if(cost > 100) - System.out.println("Over budget!"); + System.err.println("Over budget!"); } private String label = dest; @Override diff --git a/innerclasses/Parcel2.java b/innerclasses/Parcel2.java index 1eca5cba2..fdba3b4e4 100644 --- a/innerclasses/Parcel2.java +++ b/innerclasses/Parcel2.java @@ -25,7 +25,7 @@ public Contents contents() { public void ship(String dest) { Contents c = contents(); Destination d = to(dest); - System.out.println(d.readLabel()); + System.err.println(d.readLabel()); } public static void main(String[] args) { Parcel2 p = new Parcel2(); diff --git a/innerclasses/Parcel3.java b/innerclasses/Parcel3.java index 2e0733e05..7dc381062 100644 --- a/innerclasses/Parcel3.java +++ b/innerclasses/Parcel3.java @@ -16,8 +16,9 @@ class Destination { } public static void main(String[] args) { Parcel3 p = new Parcel3(); - // Must use instance of outer class - // to create an instance of the inner class: + //self-note: Must use instance of outer class to create an instance of the inner class: + //在拥有外部类对象之前是不可能创建内部类对象的。这是因为内部类对象会暗暗地连接到建它的外部类对象上。 + //但是,如果你创建的是嵌套类(静态内部类),那么它就不需要对外部类对象的引用。 Parcel3.Contents c = p.new Contents(); Parcel3.Destination d = p.new Destination("Tasmania"); diff --git a/innerclasses/Parcel9.java b/innerclasses/Parcel9.java index 775390f13..972b02fbd 100644 --- a/innerclasses/Parcel9.java +++ b/innerclasses/Parcel9.java @@ -17,4 +17,12 @@ public static void main(String[] args) { Parcel9 p = new Parcel9(); Destination d = p.destination("Tasmania"); } + /** + * self-note: + * 如果在定义一个匿名内部类时,它要使用一个外部环境(在本匿名内部类之外定义)对象, + * 那么编译器会要求其(该对象)参数引用是 final 或者是 “effectively final” + * (也就是说,该参数在初始化后不能被重新赋值,所以可以当作 final)的, + * 就像你在 destination() 的参数中看到的那样。 + * 这里省略掉 final 也没问题,但通常加上 final 作为提醒比较好。 + */ } diff --git a/innerclasses/Sequence.java b/innerclasses/Sequence.java index b5a870b98..bdaf76555 100644 --- a/innerclasses/Sequence.java +++ b/innerclasses/Sequence.java @@ -4,6 +4,8 @@ // Visit http://OnJava8.com for more book information. // Holds a sequence of Objects +import java.util.Arrays; + interface Selector { boolean end(); Object current(); @@ -23,7 +25,9 @@ public void add(Object x) { private class SequenceSelector implements Selector { private int i = 0; @Override - public boolean end() { return i == items.length; } + public boolean end() { + System.err.println("TT:"+ Arrays.toString(Sequence.this.items));//self-note: .this返回对整个外部对象的引用 + return i == items.length; } @Override public Object current() { return items[i]; } @Override @@ -38,7 +42,7 @@ public static void main(String[] args) { sequence.add(Integer.toString(i)); Selector selector = sequence.selector(); while(!selector.end()) { - System.out.print(selector.current() + " "); + System.err.print(selector.current() + " "); selector.next(); } } diff --git a/innerclasses/TestBed.java b/innerclasses/TestBed.java index d4bc16dda..c8bcbf99e 100644 --- a/innerclasses/TestBed.java +++ b/innerclasses/TestBed.java @@ -6,7 +6,7 @@ // {java TestBed$Tester} public class TestBed { - public void f() { System.out.println("f()"); } + public void f() { System.err.println("f()"); } public static class Tester { public static void main(String[] args) { TestBed t = new TestBed(); diff --git a/innerclasses/TestParcel.java b/innerclasses/TestParcel.java index f1ec5d47f..3300ae2bd 100644 --- a/innerclasses/TestParcel.java +++ b/innerclasses/TestParcel.java @@ -4,13 +4,13 @@ // Visit http://OnJava8.com for more book information. class Parcel4 { + private int aaa ; private class PContents implements Contents { private int i = 11; @Override public int value() { return i; } } - protected final class - PDestination implements Destination { + protected final class PDestination implements Destination { private String label; private PDestination(String whereTo) { label = whereTo; @@ -32,6 +32,8 @@ public static void main(String[] args) { Contents c = p.contents(); Destination d = p.destination("Tasmania"); // Illegal -- can't access private class: - //- Parcel4.PContents pc = p.new PContents(); + /* Parcel4.PContents pc = p.new PContents(); + p.aaa;*/ + } } diff --git a/innerclasses/controller/Controller.java b/innerclasses/controller/Controller.java index 9a3625b36..7e5226635 100644 --- a/innerclasses/controller/Controller.java +++ b/innerclasses/controller/Controller.java @@ -3,20 +3,28 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // The reusable framework for control systems -package innerclasses.controller; +package controller; import java.util.*; public class Controller { // A class from java.util to hold Event objects: private List eventList = new ArrayList<>(); + + public void setEventList(List eventList) { + this.eventList = eventList; + } + public void addEvent(Event c) { eventList.add(c); } public void run() { + System.err.println("eventList.size(): "+eventList.size()); + while(eventList.size() > 0) +// System.err.println("eventList.size(): "+eventList.size()); // Make a copy so you're not modifying the list // while you're selecting the elements in it: for(Event e : new ArrayList<>(eventList)) if(e.ready()) { - System.out.println(e); + System.err.println(e); e.action(); eventList.remove(e); } diff --git a/innerclasses/controller/Event.java b/innerclasses/controller/Event.java index 5523168f4..d64abc04f 100644 --- a/innerclasses/controller/Event.java +++ b/innerclasses/controller/Event.java @@ -3,7 +3,7 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // The common methods for any control event -package innerclasses.controller; +package controller; import java.time.*; // Java 8 time classes public abstract class Event { diff --git a/interfaces/AbstractAccess.java b/interfaces/AbstractAccess.java index c2e43da3a..10b3c0d9f 100644 --- a/interfaces/AbstractAccess.java +++ b/interfaces/AbstractAccess.java @@ -5,7 +5,7 @@ abstract class AbstractAccess { private void m1() {} - // private abstract void m1a(); // illegal + // private abstract void m1a(); // illegal self-note:被禁止了是有意义的,因为你不可能在 AbstractAccess 的任何子类中合法地定义它。 protected void m2() {} protected abstract void m2a(); void m3() {} @@ -13,3 +13,6 @@ void m3() {} public void m4() {} public abstract void m4a(); } + +//接口只允许 public 方法,如果不加访问修饰符的话,接口的方法不是 friendly 而是 public。 +//然而,抽象类允许每件事:(除了private abstract) diff --git a/interfaces/AdaptedRandomDoubles.java b/interfaces/AdaptedRandomDoubles.java index 6c7866554..bc304814f 100644 --- a/interfaces/AdaptedRandomDoubles.java +++ b/interfaces/AdaptedRandomDoubles.java @@ -6,8 +6,7 @@ import java.nio.*; import java.util.*; -public class AdaptedRandomDoubles -implements RandomDoubles, Readable { +public class AdaptedRandomDoubles implements RandomDoubles, Readable { private int count; public AdaptedRandomDoubles(int count) { this.count = count; @@ -24,7 +23,7 @@ public static void main(String[] args) { Scanner s = new Scanner(new AdaptedRandomDoubles(7)); while(s.hasNextDouble()) - System.out.print(s.nextDouble() + " "); + System.err.print(s.nextDouble() + " "); } } /* Output: @@ -33,3 +32,20 @@ public static void main(String[] args) { 0.5166020801268457 0.2678662084200585 0.2613610344283964 */ +/** + * self-note: RandomDoubles 类没有实现 Readable 接口, + * 使用适配器模式,但这里适配器类可以实现两个接口 + * 通过关键字 interface 提供的多继承,我们可以创建一个既是 RandomDoubles,又是 Readable 的类AdaptedRandomDoubles: + * + * + * + * 类适配器模式主要应用于新需求是一个新的接口。为了适应新的需求,我们必须 + * 1.先实现此接口,2.但我们又要想复用原有的代码。此时要满足这一点,可通过继承原有的类,来复用父类的方法。 + * 综合以上的两个关键点,我们应该定义一个新的类,使其继承原有的类,同时去实现业务所需的新目标接口。 + * + * 类适配器模式需要新定义一个适配器类,它实现了需求对应的接口,并继承现有的业务类, + * 通过在接口方法中显式地调用父类的方法的方式,达到适应新需求同时又复用现有方法代码的目的。 + * + * + * + */ diff --git a/interfaces/Adventure.java b/interfaces/Adventure.java index 1a7135d13..2ca0520e2 100644 --- a/interfaces/Adventure.java +++ b/interfaces/Adventure.java @@ -22,7 +22,9 @@ public void fight() {} class Hero extends ActionCharacter implements CanFight, CanSwim, CanFly { + @Override public void swim() {} + @Override public void fly() {} } diff --git a/interfaces/AnImplementation.java b/interfaces/AnImplementation.java index 3ff13a30c..ccbd5c6d7 100644 --- a/interfaces/AnImplementation.java +++ b/interfaces/AnImplementation.java @@ -5,10 +5,10 @@ public class AnImplementation implements AnInterface { public void firstMethod() { - System.out.println("firstMethod"); + System.err.println("firstMethod"); } public void secondMethod() { - System.out.println("secondMethod"); + System.err.println("secondMethod"); } public static void main(String[] args) { AnInterface i = new AnImplementation(); diff --git a/interfaces/Applicator.java b/interfaces/Applicator.java index a6aa172f9..191e73595 100644 --- a/interfaces/Applicator.java +++ b/interfaces/Applicator.java @@ -37,8 +37,8 @@ public String process(Object input) { public class Applicator { public static void apply(Processor p, Object s) { - System.out.println("Using Processor " + p.name()); - System.out.println(p.process(s)); + System.err.println("Using Processor " + p.name()); + System.err.println(p.process(s)); } public static void main(String[] args) { String s = @@ -55,4 +55,10 @@ public static void main(String[] args) { we are such stuff as dreams are made on Using Processor Splitter [We, are, such, stuff, as, dreams, are, made, on] + + +self-note: 像本例中这样,创建一个能根据传入的参数类型从而具备不同行为的方法称为策略设计模式。 +方法包含算法中不变的部分,策略包含变化的部分。 +策略就是传入的对象,它包含要执行的代码。 +在这里,Processor 对象是策略,main() 方法展示了三种不同的应用于 String s 上的策略。 */ diff --git a/interfaces/Factories.java b/interfaces/Factories.java index 87e282513..94df9efb1 100644 --- a/interfaces/Factories.java +++ b/interfaces/Factories.java @@ -15,10 +15,10 @@ interface ServiceFactory { class Service1 implements Service { Service1() {} // Package access public void method1() { - System.out.println("Service1 method1"); + System.err.println("Service1 method1"); } public void method2() { - System.out.println("Service1 method2"); + System.err.println("Service1 method2"); } } @@ -32,10 +32,10 @@ public Service getService() { class Service2 implements Service { Service2() {} // Package access public void method1() { - System.out.println("Service2 method1"); + System.err.println("Service2 method1"); } public void method2() { - System.out.println("Service2 method2"); + System.err.println("Service2 method2"); } } diff --git a/interfaces/Games.java b/interfaces/Games.java index 867efe0cc..521034d98 100644 --- a/interfaces/Games.java +++ b/interfaces/Games.java @@ -12,7 +12,7 @@ class Checkers implements Game { private static final int MOVES = 3; @Override public boolean move() { - System.out.println("Checkers move " + moves); + System.err.println("Checkers move " + moves); return ++moves != MOVES; } } @@ -27,7 +27,7 @@ class Chess implements Game { private static final int MOVES = 4; @Override public boolean move() { - System.out.println("Chess move " + moves); + System.err.println("Chess move " + moves); return ++moves != MOVES; } } diff --git a/interfaces/Implementation2.java b/interfaces/Implementation2.java index 61c6efa01..001db60a4 100644 --- a/interfaces/Implementation2.java +++ b/interfaces/Implementation2.java @@ -6,10 +6,10 @@ public class Implementation2 implements InterfaceWithDefault { public void firstMethod() { - System.out.println("firstMethod"); + System.err.println("firstMethod"); } public void secondMethod() { - System.out.println("secondMethod"); + System.err.println("secondMethod"); } public static void main(String[] args) { InterfaceWithDefault i = diff --git a/interfaces/ImplementingAnInterface.java b/interfaces/ImplementingAnInterface.java index 6a13ebb63..c9a4a619c 100644 --- a/interfaces/ImplementingAnInterface.java +++ b/interfaces/ImplementingAnInterface.java @@ -9,6 +9,6 @@ interface Concept { // Package access } class Implementation implements Concept { - public void idea1() { System.out.println("idea1"); } - public void idea2() { System.out.println("idea2"); } + public void idea1() { System.err.println("idea1"); } + public void idea2() { System.err.println("idea2"); } } diff --git a/interfaces/Instantiable.java b/interfaces/Instantiable.java index 427b6ca39..03a6795ed 100644 --- a/interfaces/Instantiable.java +++ b/interfaces/Instantiable.java @@ -10,7 +10,7 @@ abstract class Uninstantiable { public class Instantiable extends Uninstantiable { @Override - void f() { System.out.println("f()"); } + void f() { System.err.println("f()"); } @Override int g() { return 22; } public static void main(String[] args) { diff --git a/interfaces/InterfaceWithDefault.java b/interfaces/InterfaceWithDefault.java index a87f02db9..1727904ec 100644 --- a/interfaces/InterfaceWithDefault.java +++ b/interfaces/InterfaceWithDefault.java @@ -7,6 +7,6 @@ interface InterfaceWithDefault { void firstMethod(); void secondMethod(); default void newMethod() { - System.out.println("newMethod"); + System.err.println("newMethod"); } } diff --git a/interfaces/Jim.java b/interfaces/Jim.java index 515db6e52..12b16bb9e 100644 --- a/interfaces/Jim.java +++ b/interfaces/Jim.java @@ -6,19 +6,19 @@ interface Jim1 { default void jim() { - System.out.println("Jim1::jim"); + System.err.println("Jim1::jim"); } } interface Jim2 { default void jim() { - System.out.println("Jim2::jim"); + System.err.println("Jim2::jim"); } } public class Jim implements Jim1, Jim2 { @Override - public void jim() { Jim2.super.jim(); } + public void jim() { Jim2.super.jim(); }//self-note: 为了解决多个implements中各个接口的签名相同而导致的命名冲突(返回类型不是方法签名的一部分,因此不能用来区分方法),的问题 public static void main(String[] args) { new Jim().jim(); } diff --git a/interfaces/MICollision.java b/interfaces/MICollision.java index c96e5696b..e1739a90a 100644 --- a/interfaces/MICollision.java +++ b/interfaces/MICollision.java @@ -6,13 +6,13 @@ interface Bob1 { default void bob() { - System.out.println("Bob1::bob"); + System.err.println("Bob1::bob"); } } interface Bob2 { default void bob() { - System.out.println("Bob2::bob"); + System.err.println("Bob2::bob"); } } @@ -27,13 +27,13 @@ class Bob implements Bob1, Bob2 {} interface Sam1 { default void sam() { - System.out.println("Sam1::sam"); + System.err.println("Sam1::sam"); } } interface Sam2 { default void sam(int i) { - System.out.println(i * 2); + System.err.println(i * 2); } } @@ -42,7 +42,7 @@ class Sam implements Sam1, Sam2 {} interface Max1 { default void max() { - System.out.println("Max1::max"); + System.err.println("Max1::max"); } } diff --git a/interfaces/Machine.java b/interfaces/Machine.java index 2b1144aef..9bf1fc709 100644 --- a/interfaces/Machine.java +++ b/interfaces/Machine.java @@ -3,7 +3,8 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. import java.util.*; -import onjava.Operations; + + class Bing implements Operations { public void execute() { @@ -33,4 +34,7 @@ public static void main(String[] args) { Bing Crack Twist + +self-note: 这是模板方法设计模式的一个版本(在“设计模式”一章中详细描述),runOps() 是一个模板方法。 +runOps() 使用可变参数列表,因而我们可以传入任意多的 Operation 参数并按顺序运行它们: */ diff --git a/interfaces/MultipleInheritance.java b/interfaces/MultipleInheritance.java index 6ce9c91e0..f60316967 100644 --- a/interfaces/MultipleInheritance.java +++ b/interfaces/MultipleInheritance.java @@ -5,17 +5,17 @@ import java.util.*; interface One { - default void first() { System.out.println("first"); } + default void first() { System.err.println("first"); } } interface Two { default void second() { - System.out.println("second"); + System.err.println("second"); } } interface Three { - default void third() { System.out.println("third"); } + default void third() { System.err.println("third"); } } class MI implements One, Two, Three {} diff --git a/interfaces/Operations.java b/interfaces/Operations.java new file mode 100644 index 000000000..151c01ccd --- /dev/null +++ b/interfaces/Operations.java @@ -0,0 +1,15 @@ +// onjava/Operations.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. + +public interface Operations { + void execute(); + static void runOps(Operations... ops) { + for(Operations op : ops) + op.execute(); + } + static void show(String msg) { + System.err.println(msg); + } +} diff --git a/interfaces/RandomDoubles.java b/interfaces/RandomDoubles.java index 99154d953..240e8c82f 100644 --- a/interfaces/RandomDoubles.java +++ b/interfaces/RandomDoubles.java @@ -10,7 +10,7 @@ public interface RandomDoubles { static void main(String[] args) { RandomDoubles rd = new RandomDoubles() {}; for(int i = 0; i < 7; i ++) - System.out.print(rd.next() + " "); + System.err.print(rd.next() + " "); } } /* Output: diff --git a/interfaces/RandomStrings.java b/interfaces/RandomStrings.java index 82f982308..5851883ae 100644 --- a/interfaces/RandomStrings.java +++ b/interfaces/RandomStrings.java @@ -33,7 +33,7 @@ public int read(CharBuffer cb) { public static void main(String[] args) { Scanner s = new Scanner(new RandomStrings(10)); while(s.hasNext()) - System.out.println(s.next()); + System.err.println(s.next()); } } /* Output: diff --git a/interfaces/TestRandVals.java b/interfaces/TestRandVals.java index df3490b26..6ae9ce116 100644 --- a/interfaces/TestRandVals.java +++ b/interfaces/TestRandVals.java @@ -5,10 +5,10 @@ public class TestRandVals { public static void main(String[] args) { - System.out.println(RandVals.RANDOM_INT); - System.out.println(RandVals.RANDOM_LONG); - System.out.println(RandVals.RANDOM_FLOAT); - System.out.println(RandVals.RANDOM_DOUBLE); + System.err.println(RandVals.RANDOM_INT); + System.err.println(RandVals.RANDOM_LONG); + System.err.println(RandVals.RANDOM_FLOAT); + System.err.println(RandVals.RANDOM_DOUBLE); } } /* Output: diff --git a/interfaces/filters/BandPass.java b/interfaces/filters/BandPass.java index 7d09ed285..1c0ea9d00 100644 --- a/interfaces/filters/BandPass.java +++ b/interfaces/filters/BandPass.java @@ -2,7 +2,7 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -package interfaces.filters; +package filters; public class BandPass extends Filter { double lowCutoff, highCutoff; diff --git a/interfaces/filters/Filter.java b/interfaces/filters/Filter.java index 72e29a9e9..fb8e766fe 100644 --- a/interfaces/filters/Filter.java +++ b/interfaces/filters/Filter.java @@ -2,7 +2,7 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -package interfaces.filters; +package filters; public class Filter { public String name() { diff --git a/interfaces/filters/HighPass.java b/interfaces/filters/HighPass.java index 7bf047df5..f7580bb3e 100644 --- a/interfaces/filters/HighPass.java +++ b/interfaces/filters/HighPass.java @@ -2,7 +2,7 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -package interfaces.filters; +package filters; public class HighPass extends Filter { double cutoff; diff --git a/interfaces/filters/LowPass.java b/interfaces/filters/LowPass.java index e9320a82a..24bba532a 100644 --- a/interfaces/filters/LowPass.java +++ b/interfaces/filters/LowPass.java @@ -2,7 +2,7 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -package interfaces.filters; +package filters; public class LowPass extends Filter { double cutoff; diff --git a/interfaces/filters/Waveform.java b/interfaces/filters/Waveform.java index 406446770..e3ced4fb0 100644 --- a/interfaces/filters/Waveform.java +++ b/interfaces/filters/Waveform.java @@ -2,7 +2,7 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -package interfaces.filters; +package filters; public class Waveform { private static long counter; diff --git a/interfaces/interfaceprocessor/Applicator.java b/interfaces/interfaceprocessor/Applicator.java index 77d7a9a66..3b4861161 100644 --- a/interfaces/interfaceprocessor/Applicator.java +++ b/interfaces/interfaceprocessor/Applicator.java @@ -2,11 +2,11 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -package interfaces.interfaceprocessor; +package interfaceprocessor; public class Applicator { public static void apply(Processor p, Object s) { - System.out.println("Using Processor " + p.name()); - System.out.println(p.process(s)); + System.err.println("Using Processor " + p.name()); + System.err.println(p.process(s)); } } diff --git a/interfaces/interfaceprocessor/FilterProcessor.java b/interfaces/interfaceprocessor/FilterProcessor.java index 33689ed46..68073df37 100644 --- a/interfaces/interfaceprocessor/FilterProcessor.java +++ b/interfaces/interfaceprocessor/FilterProcessor.java @@ -3,8 +3,11 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {java interfaces.interfaceprocessor.FilterProcessor} -package interfaces.interfaceprocessor; -import interfaces.filters.*; +//package interfaces.interfaceprocessor; +//import interfaces.filters.*; +//import interfaces; +package interfaceprocessor; +import filters.*; class FilterAdapter implements Processor { Filter filter; @@ -24,10 +27,13 @@ public static void main(String[] args) { Waveform w = new Waveform(); Applicator.apply( new FilterAdapter(new LowPass(1.0)), w); - Applicator.apply( + Applicator.apply( new FilterAdapter(new HighPass(2.0)), w); + Applicator.apply( + new FilterAdapter(new BandPass(3.0, 4.0)), w);//self-note: 对于filter及其派生类来说,没有任何改动,但是能用apply方法了; 完全解耦 + Upcase p = new Upcase(); Applicator.apply( - new FilterAdapter(new BandPass(3.0, 4.0)), w); + p, "sss");//除了开始将Processor改为接口外,也没有别的改动了. } } /* Output: @@ -37,4 +43,23 @@ public static void main(String[] args) { Waveform 0 Using Processor BandPass Waveform 0 + +self-note: 这种使用适配器的方式设计模式中, +FilterAdapter 的构造器接受已有的接口 Filter,继而产生需要的 Processor 接口的对象。 +你可能还注意到 FilterAdapter 中使用了委托。 + + +对象适配器模式 +设计思路 + + 对象适配器模式主要应用于新的需求的一个(抽象)基类。 + 在这里我们不能使用类适配器模式的所用到的继承父类、实现接口的方式去满足目标需求,因为java中不允许多根继承,只能单根继承, + 我们也就无法在继承(目标需求)抽象类的同时再去继承原有的类(复用原代码)。 + 此时定义一个新类(适配者),将一个原有的类(被适配者)作为成员变量放在这个类中,此类还要继承目标抽象类,并实现其中的抽象方法。 + + 对象适配器模式同样需要定义一个适配器类,它继承需求对应的(抽象)类, + 将现有的业务类作为适配器的一个成员变量,并用构造方法传入业务类实例对象的引用,以初始化此成员变量; + 在实现父类的抽象方法中使用委托机制(某个方法将实际处理工作交给其他对象的方法去完成), + 让成员变量(现有业务类对象)调用自己的方法。 + */ diff --git a/interfaces/interfaceprocessor/Processor.java b/interfaces/interfaceprocessor/Processor.java index 6315da300..22737dbe9 100644 --- a/interfaces/interfaceprocessor/Processor.java +++ b/interfaces/interfaceprocessor/Processor.java @@ -2,7 +2,9 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -package interfaces.interfaceprocessor; +package interfaceprocessor; + + public interface Processor { default String name() { diff --git a/interfaces/interfaceprocessor/StringProcessor.java b/interfaces/interfaceprocessor/StringProcessor.java index 37cb49469..41cce9a6e 100644 --- a/interfaces/interfaceprocessor/StringProcessor.java +++ b/interfaces/interfaceprocessor/StringProcessor.java @@ -3,7 +3,9 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {java interfaces.interfaceprocessor.StringProcessor} -package interfaces.interfaceprocessor; +package interfaceprocessor; +import filters.Waveform; + import java.util.*; interface StringProcessor extends Processor { diff --git a/interfaces/music4/Music4.java b/interfaces/music4/Music4.java index 710341494..1901379c0 100644 --- a/interfaces/music4/Music4.java +++ b/interfaces/music4/Music4.java @@ -4,8 +4,10 @@ // Visit http://OnJava8.com for more book information. // Abstract classes and methods // {java interfaces.music4.Music4} -package interfaces.music4; -import polymorphism.music.Note; +package music4; + + +import music5.Note; abstract class Instrument { private int i; // Storage allocated for each @@ -17,57 +19,57 @@ abstract class Instrument { class Wind extends Instrument { @Override public void play(Note n) { - System.out.println("Wind.play() " + n); + System.err.println("Wind.play() " + n); } @Override public String what() { return "Wind"; } @Override public void adjust() { - System.out.println("Adjusting Wind"); + System.err.println("Adjusting Wind"); } } class Percussion extends Instrument { @Override public void play(Note n) { - System.out.println("Percussion.play() " + n); + System.err.println("Percussion.play() " + n); } @Override public String what() { return "Percussion"; } @Override public void adjust() { - System.out.println("Adjusting Percussion"); + System.err.println("Adjusting Percussion"); } } class Stringed extends Instrument { @Override public void play(Note n) { - System.out.println("Stringed.play() " + n); + System.err.println("Stringed.play() " + n); } @Override public String what() { return "Stringed"; } @Override public void adjust() { - System.out.println("Adjusting Stringed"); + System.err.println("Adjusting Stringed"); } } class Brass extends Wind { @Override public void play(Note n) { - System.out.println("Brass.play() " + n); + System.err.println("Brass.play() " + n); } @Override public void adjust() { - System.out.println("Adjusting Brass"); + System.err.println("Adjusting Brass"); } } class Woodwind extends Wind { @Override public void play(Note n) { - System.out.println("Woodwind.play() " + n); + System.err.println("Woodwind.play() " + n); } @Override public String what() { return "Woodwind"; } diff --git a/interfaces/music5/Music5.java b/interfaces/music5/Music5.java index 2326bdbc9..a15026a1f 100644 --- a/interfaces/music5/Music5.java +++ b/interfaces/music5/Music5.java @@ -3,17 +3,17 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {java interfaces.music5.Music5} -package interfaces.music5; -import polymorphism.music.Note; +package music5; + interface Instrument { // Compile-time constant: int VALUE = 5; // static & final default void play(Note n) { // Automatically public - System.out.println(this + ".play() " + n); + System.err.println(this + ".play() " + n); } default void adjust() { - System.out.println("Adjusting " + this); + System.err.println("Adjusting " + this); } } diff --git a/interfaces/music5/Note.java b/interfaces/music5/Note.java new file mode 100644 index 000000000..e254b71a2 --- /dev/null +++ b/interfaces/music5/Note.java @@ -0,0 +1,10 @@ +// polymorphism/music/Note.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// Notes to play on musical instruments +package music5; + +public enum Note { + MIDDLE_C, C_SHARP, B_FLAT; // Etc. +} diff --git a/interfaces/nesting/NestingInterfaces.java b/interfaces/nesting/NestingInterfaces.java index 99b466bb0..84da7c2a7 100644 --- a/interfaces/nesting/NestingInterfaces.java +++ b/interfaces/nesting/NestingInterfaces.java @@ -3,7 +3,7 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {java interfaces.nesting.NestingInterfaces} -package interfaces.nesting; +package nesting; class A { interface B { @@ -76,7 +76,7 @@ public void f() {} //- } class EImp implements E { @Override - public void g() {} + public void g() {} //尤其是当实现某个接口(E)时,并不需要实现嵌套在其内部的接口(E.G)。 } class EGImp implements E.G { @Override @@ -92,14 +92,23 @@ public void f() {} } public static void main(String[] args) { A a = new A(); - // Can't access A.D: - //- A.D ad = a.getD(); - // Doesn't return anything but A.D: - //- A.DImp2 di2 = a.getD(); - // Cannot access a member of the interface: - //- a.getD().f(); - // Only another A can do anything with getD(): - A a2 = new A(); + + //- +// A.D ad = a.getD(); // Can't access A.D: + + //- +// A.DImp2 di2 = a.getD(); // Doesn't return anything but A.D: + + //- +// a.getD().f(); // Cannot access a member of the interface: + + //- + A a2 = new A(); // Only another A can do anything with getD(): a2.receiveD(a.getD()); + + /** + * getD()是一个 public 方法却返回了对 private 接口的引用。能对这个返回值做些什么呢? + * main() 方法里进行了一些使用返回值的尝试但都失败了。返回值必须交给有权使用它的对象,本例中另一个 A 通过 receiveD() 方法接受了它。 + */ } } diff --git a/iostreams/BasicFileOutput.java b/iostreams/BasicFileOutput.java index 1da5c6fdc..f4753d406 100644 --- a/iostreams/BasicFileOutput.java +++ b/iostreams/BasicFileOutput.java @@ -21,6 +21,6 @@ public static void main(String[] args) { throw new RuntimeException(e); } // Show the stored file: - System.out.println(BufferedInputFile.read(file)); + System.err.println(BufferedInputFile.read(file)); } } diff --git a/iostreams/BufferedInputFile.java b/iostreams/BufferedInputFile.java index bfe6396f1..d4d53811d 100644 --- a/iostreams/BufferedInputFile.java +++ b/iostreams/BufferedInputFile.java @@ -17,7 +17,7 @@ public static String read(String filename) { } } public static void main(String[] args) { - System.out.print( + System.err.print( read("BufferedInputFile.java")); } } diff --git a/iostreams/FileOutputShortcut.java b/iostreams/FileOutputShortcut.java index 5a160ec00..e98daada0 100644 --- a/iostreams/FileOutputShortcut.java +++ b/iostreams/FileOutputShortcut.java @@ -19,6 +19,6 @@ public static void main(String[] args) { } catch(IOException e) { throw new RuntimeException(e); } - System.out.println(BufferedInputFile.read(file)); + System.err.println(BufferedInputFile.read(file)); } } diff --git a/iostreams/FormattedMemoryInput.java b/iostreams/FormattedMemoryInput.java index 055dd8826..355e6abe3 100644 --- a/iostreams/FormattedMemoryInput.java +++ b/iostreams/FormattedMemoryInput.java @@ -15,9 +15,9 @@ public static void main(String[] args) { .getBytes())) ) { while(true) - System.out.write((char)in.readByte()); + System.err.write((char)in.readByte()); } catch(EOFException e) { - System.out.println("\nEnd of stream"); + System.err.println("\nEnd of stream"); } catch(IOException e) { throw new RuntimeException(e); } diff --git a/iostreams/MemoryInput.java b/iostreams/MemoryInput.java index 1326965c6..1fb6f6c04 100644 --- a/iostreams/MemoryInput.java +++ b/iostreams/MemoryInput.java @@ -12,6 +12,6 @@ public class MemoryInput { BufferedInputFile.read("MemoryInput.java")); int c; while((c = in.read()) != -1) - System.out.print((char)c); + System.err.print((char)c); } } diff --git a/iostreams/StoringAndRecoveringData.java b/iostreams/StoringAndRecoveringData.java index 761f022eb..66f970da4 100644 --- a/iostreams/StoringAndRecoveringData.java +++ b/iostreams/StoringAndRecoveringData.java @@ -23,12 +23,12 @@ public static void main(String[] args) { new BufferedInputStream( new FileInputStream("Data.txt"))) ) { - System.out.println(in.readDouble()); + System.err.println(in.readDouble()); // Only readUTF() will recover the // Java-UTF String properly: - System.out.println(in.readUTF()); - System.out.println(in.readDouble()); - System.out.println(in.readUTF()); + System.err.println(in.readUTF()); + System.err.println(in.readDouble()); + System.err.println(in.readUTF()); } catch(IOException e) { throw new RuntimeException(e); } diff --git a/iostreams/TestEOF.java b/iostreams/TestEOF.java index 956cb1a03..d4cad8ce0 100644 --- a/iostreams/TestEOF.java +++ b/iostreams/TestEOF.java @@ -14,7 +14,7 @@ public static void main(String[] args) { new FileInputStream("TestEOF.java"))) ) { while(in.available() != 0) - System.out.write(in.readByte()); + System.err.write(in.readByte()); } catch(IOException e) { throw new RuntimeException(e); } diff --git a/iostreams/UsingRandomAccessFile.java b/iostreams/UsingRandomAccessFile.java index dde6d1ee8..fbca989f7 100644 --- a/iostreams/UsingRandomAccessFile.java +++ b/iostreams/UsingRandomAccessFile.java @@ -12,9 +12,9 @@ public static void display() { new RandomAccessFile(file, "r") ) { for(int i = 0; i < 7; i++) - System.out.println( + System.err.println( "Value " + i + ": " + rf.readDouble()); - System.out.println(rf.readUTF()); + System.err.println(rf.readUTF()); } catch(IOException e) { throw new RuntimeException(e); } diff --git a/javadoc/Documentation2.java b/javadoc/Documentation2.java index 237755f4c..3c932400e 100644 --- a/javadoc/Documentation2.java +++ b/javadoc/Documentation2.java @@ -3,7 +3,7 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. /**
- * System.out.println(new Date());
+ * System.err.println(new Date());
  * 
*/ public class Documentation2 {} diff --git a/javadoc/HelloDateDoc.java b/javadoc/HelloDateDoc.java index 54b505a44..f501417d8 100644 --- a/javadoc/HelloDateDoc.java +++ b/javadoc/HelloDateDoc.java @@ -16,8 +16,8 @@ public class HelloDateDoc { * @throws exceptions No exceptions thrown */ public static void main(String[] args) { - System.out.println("Hello, it's: "); - System.out.println(new Date()); + System.err.println("Hello, it's: "); + System.err.println(new Date()); } } /* Output: diff --git a/lowlevel/Atomicity.java b/lowlevel/Atomicity.java index 632631bf4..379ba6181 100644 --- a/lowlevel/Atomicity.java +++ b/lowlevel/Atomicity.java @@ -12,7 +12,7 @@ public static void test(IntTestable it) { while(true) { int val = it.getAsInt(); if(val % 2 != 0) { - System.out.println("failed with: " + val); + System.err.println("failed with: " + val); System.exit(0); } } diff --git a/lowlevel/AttemptLocking.java b/lowlevel/AttemptLocking.java index 9dbe2b28e..fc2e62a3b 100644 --- a/lowlevel/AttemptLocking.java +++ b/lowlevel/AttemptLocking.java @@ -13,7 +13,7 @@ public class AttemptLocking { public void untimed() { boolean captured = lock.tryLock(); try { - System.out.println("tryLock(): " + captured); + System.err.println("tryLock(): " + captured); } finally { if(captured) lock.unlock(); @@ -27,7 +27,7 @@ public void timed() { throw new RuntimeException(e); } try { - System.out.println( + System.err.println( "tryLock(2, TimeUnit.SECONDS): " + captured); } finally { if(captured) @@ -41,7 +41,7 @@ public static void main(String[] args) { // Now create a second task to grab the lock: CompletableFuture.runAsync( () -> { al.lock.lock(); - System.out.println("acquired"); + System.err.println("acquired"); }); new Nap(0.1); // Give the second task a chance al.untimed(); // False -- lock grabbed by task diff --git a/lowlevel/CaptureUncaughtException.java b/lowlevel/CaptureUncaughtException.java index 33261667d..1e2ce2a61 100644 --- a/lowlevel/CaptureUncaughtException.java +++ b/lowlevel/CaptureUncaughtException.java @@ -8,8 +8,8 @@ class ExceptionThread2 implements Runnable { @Override public void run() { Thread t = Thread.currentThread(); - System.out.println("run() by " + t.getName()); - System.out.println( + System.err.println("run() by " + t.getName()); + System.err.println( "eh = " + t.getUncaughtExceptionHandler()); throw new RuntimeException(); } @@ -19,19 +19,19 @@ class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler { @Override public void uncaughtException(Thread t, Throwable e) { - System.out.println("caught " + e); + System.err.println("caught " + e); } } class HandlerThreadFactory implements ThreadFactory { @Override public Thread newThread(Runnable r) { - System.out.println(this + " creating new Thread"); + System.err.println(this + " creating new Thread"); Thread t = new Thread(r); - System.out.println("created " + t); + System.err.println("created " + t); t.setUncaughtExceptionHandler( new MyUncaughtExceptionHandler()); - System.out.println( + System.err.println( "eh = " + t.getUncaughtExceptionHandler()); return t; } diff --git a/lowlevel/DelayQueueDemo.java b/lowlevel/DelayQueueDemo.java index c5575c681..979175458 100644 --- a/lowlevel/DelayQueueDemo.java +++ b/lowlevel/DelayQueueDemo.java @@ -34,7 +34,7 @@ public int compareTo(Delayed arg) { } @Override public void run() { - System.out.print(this + " "); + System.err.print(this + " "); } @Override public String toString() { @@ -49,7 +49,7 @@ public static class EndTask extends DelayedTask { @Override public void run() { sequence.forEach(dt -> - System.out.println(dt.summary())); + System.err.println(dt.summary())); } } } diff --git a/lowlevel/EvenChecker.java b/lowlevel/EvenChecker.java index 5e27a39eb..3239cb0e7 100644 --- a/lowlevel/EvenChecker.java +++ b/lowlevel/EvenChecker.java @@ -19,7 +19,7 @@ public void run() { while(!generator.isCanceled()) { int val = generator.next(); if(val % 2 != 0) { - System.out.println(val + " not even!"); + System.err.println(val + " not even!"); generator.cancel(); // Cancels all EvenCheckers } } diff --git a/lowlevel/NaiveExceptionHandling.java b/lowlevel/NaiveExceptionHandling.java index 3681337ef..1c0b04863 100644 --- a/lowlevel/NaiveExceptionHandling.java +++ b/lowlevel/NaiveExceptionHandling.java @@ -13,7 +13,7 @@ public static void main(String[] args) { es.execute(new ExceptionThread()); } catch(RuntimeException ue) { // This statement will NOT execute! - System.out.println("Exception was handled!"); + System.err.println("Exception was handled!"); } finally { es.shutdown(); } diff --git a/lowlevel/NumberOfProcessors.java b/lowlevel/NumberOfProcessors.java index 44abeb5dd..7e19c8332 100644 --- a/lowlevel/NumberOfProcessors.java +++ b/lowlevel/NumberOfProcessors.java @@ -5,7 +5,7 @@ public class NumberOfProcessors { public static void main(String[] args) { - System.out.println( + System.err.println( Runtime.getRuntime().availableProcessors()); } } diff --git a/lowlevel/PriorityBlockingQueueDemo.java b/lowlevel/PriorityBlockingQueueDemo.java index 099a53497..01a5af2c0 100644 --- a/lowlevel/PriorityBlockingQueueDemo.java +++ b/lowlevel/PriorityBlockingQueueDemo.java @@ -32,9 +32,9 @@ public String toString() { public void displaySequence() { int count = 0; for(Prioritized pt : sequence) { - System.out.printf("(%d:%d)", pt.id, pt.priority); + System.err.printf("(%d:%d)", pt.id, pt.priority); if(++count % 5 == 0) - System.out.println(); + System.err.println(); } } public static class EndSentinel extends Prioritized { @@ -73,7 +73,7 @@ public void run() { while(true) { try { Prioritized pt = q.take(); - System.out.println(pt); + System.err.println(pt); if(pt instanceof Prioritized.EndSentinel) { pt.displaySequence(); break; diff --git a/lowlevel/SerialNumberChecker.java b/lowlevel/SerialNumberChecker.java index 9c2b92ad2..84d8cbc4f 100644 --- a/lowlevel/SerialNumberChecker.java +++ b/lowlevel/SerialNumberChecker.java @@ -17,7 +17,7 @@ public void run() { while(true) { int serial = producer.nextSerialNumber(); if(serials.contains(serial)) { - System.out.println("Duplicate: " + serial); + System.err.println("Duplicate: " + serial); System.exit(0); } serials.add(serial); diff --git a/lowlevel/SyncOnObject.java b/lowlevel/SyncOnObject.java index 846c5573a..b73b3d4cf 100644 --- a/lowlevel/SyncOnObject.java +++ b/lowlevel/SyncOnObject.java @@ -41,7 +41,7 @@ static void test(boolean fNap, boolean gNap) { } public static void main(String[] args) { test(true, false); - System.out.println("****"); + System.err.println("****"); test(false, true); } } diff --git a/lowlevel/SynchronizedComparison.java b/lowlevel/SynchronizedComparison.java index 6fbcd1f3d..a9d22c860 100644 --- a/lowlevel/SynchronizedComparison.java +++ b/lowlevel/SynchronizedComparison.java @@ -52,7 +52,7 @@ public void run() { g.method(); successfulCalls.getAndIncrement(); } - System.out.println( + System.err.println( "-> " + successfulCalls.get()); } } @@ -68,7 +68,7 @@ static void test(Guarded g) { .map(CompletableFuture::runAsync) .collect(Collectors.toList()); callers.forEach(CompletableFuture::join); - System.out.println(g); + System.err.println(g); } public static void main(String[] args) { test(new CriticalSection()); diff --git a/lowlevel/TestAbort.java b/lowlevel/TestAbort.java index a9efe5285..9b93b6ad4 100644 --- a/lowlevel/TestAbort.java +++ b/lowlevel/TestAbort.java @@ -7,7 +7,7 @@ public class TestAbort { public static void main(String[] args) { new TimedAbort(1); - System.out.println("Napping for 4"); + System.err.println("Napping for 4"); new Nap(4); } } diff --git a/lowlevel/ThreadSize.java b/lowlevel/ThreadSize.java index 0f00023d3..ec3b4ee4e 100644 --- a/lowlevel/ThreadSize.java +++ b/lowlevel/ThreadSize.java @@ -21,7 +21,7 @@ public static void main(String[] args) { count++; } } catch(Error e) { - System.out.println( + System.err.println( e.getClass().getSimpleName() + ": " + count); System.exit(0); } finally { diff --git a/lowlevel/WorkStealingPool.java b/lowlevel/WorkStealingPool.java index 984de7067..5da623d2f 100644 --- a/lowlevel/WorkStealingPool.java +++ b/lowlevel/WorkStealingPool.java @@ -8,7 +8,7 @@ class ShowThread implements Runnable { @Override public void run() { - System.out.println( + System.err.println( Thread.currentThread().getName()); } } @@ -16,7 +16,7 @@ public void run() { public class WorkStealingPool { public static void main(String[] args) throws InterruptedException { - System.out.println( + System.err.println( Runtime.getRuntime().availableProcessors()); ExecutorService exec = Executors.newWorkStealingPool(); diff --git a/newio/AvailableCharSets.java b/newio/AvailableCharSets.java index eda3b93c2..072acc5af 100644 --- a/newio/AvailableCharSets.java +++ b/newio/AvailableCharSets.java @@ -11,17 +11,17 @@ public static void main(String[] args) { SortedMap charSets = Charset.availableCharsets(); for(String csName : charSets.keySet()) { - System.out.print(csName); + System.err.print(csName); Iterator aliases = charSets.get(csName) .aliases().iterator(); if(aliases.hasNext()) - System.out.print(": "); + System.err.print(": "); while(aliases.hasNext()) { - System.out.print(aliases.next()); + System.err.print(aliases.next()); if(aliases.hasNext()) - System.out.print(", "); + System.err.print(", "); } - System.out.println(); + System.err.println(); } } } diff --git a/newio/BufferToText.java b/newio/BufferToText.java index 2f38c2c6a..d39533d71 100644 --- a/newio/BufferToText.java +++ b/newio/BufferToText.java @@ -30,12 +30,12 @@ public static void main(String[] args) { } buff.flip(); // Doesn't work: - System.out.println(buff.asCharBuffer()); + System.err.println(buff.asCharBuffer()); // Decode using this system's default Charset: buff.rewind(); String encoding = System.getProperty("file.encoding"); - System.out.println("Decoded using " + + System.err.println("Decoded using " + encoding + ": " + Charset.forName(encoding).decode(buff)); // Encode with something that prints: @@ -59,7 +59,7 @@ public static void main(String[] args) { throw new RuntimeException(e); } buff.flip(); - System.out.println(buff.asCharBuffer()); + System.err.println(buff.asCharBuffer()); // Use a CharBuffer to write through: buff = ByteBuffer.allocate(24); buff.asCharBuffer().put("Some text"); @@ -82,7 +82,7 @@ public static void main(String[] args) { throw new RuntimeException(e); } buff.flip(); - System.out.println(buff.asCharBuffer()); + System.err.println(buff.asCharBuffer()); } } /* Output: diff --git a/newio/ChannelCopy.java b/newio/ChannelCopy.java index 846961310..28f2d0418 100644 --- a/newio/ChannelCopy.java +++ b/newio/ChannelCopy.java @@ -12,7 +12,7 @@ public class ChannelCopy { private static final int BSIZE = 1024; public static void main(String[] args) { if(args.length != 2) { - System.out.println( + System.err.println( "arguments: sourcefile destfile"); System.exit(1); } diff --git a/newio/Endians.java b/newio/Endians.java index 11d660760..edf89aac4 100644 --- a/newio/Endians.java +++ b/newio/Endians.java @@ -10,15 +10,15 @@ public class Endians { public static void main(String[] args) { ByteBuffer bb = ByteBuffer.wrap(new byte[12]); bb.asCharBuffer().put("abcdef"); - System.out.println(Arrays.toString(bb.array())); + System.err.println(Arrays.toString(bb.array())); bb.rewind(); bb.order(ByteOrder.BIG_ENDIAN); bb.asCharBuffer().put("abcdef"); - System.out.println(Arrays.toString(bb.array())); + System.err.println(Arrays.toString(bb.array())); bb.rewind(); bb.order(ByteOrder.LITTLE_ENDIAN); bb.asCharBuffer().put("abcdef"); - System.out.println(Arrays.toString(bb.array())); + System.err.println(Arrays.toString(bb.array())); } } /* Output: diff --git a/newio/FileLocking.java b/newio/FileLocking.java index e8c74d2a9..109895472 100644 --- a/newio/FileLocking.java +++ b/newio/FileLocking.java @@ -14,10 +14,10 @@ public static void main(String[] args) { FileLock fl = fos.getChannel().tryLock() ) { if(fl != null) { - System.out.println("Locked File"); + System.err.println("Locked File"); TimeUnit.MILLISECONDS.sleep(100); fl.release(); - System.out.println("Released Lock"); + System.err.println("Released Lock"); } } catch(IOException | InterruptedException e) { throw new RuntimeException(e); diff --git a/newio/GetChannel.java b/newio/GetChannel.java index 16caa3400..d3e89822f 100644 --- a/newio/GetChannel.java +++ b/newio/GetChannel.java @@ -41,11 +41,11 @@ public static void main(String[] args) { fc.read(buff); buff.flip(); while(buff.hasRemaining()) - System.out.write(buff.get()); + System.err.write(buff.get()); } catch(IOException e) { throw new RuntimeException(e); } - System.out.flush(); + System.err.flush(); } } /* Output: diff --git a/newio/GetData.java b/newio/GetData.java index b2518b101..0a99c2ac5 100644 --- a/newio/GetData.java +++ b/newio/GetData.java @@ -13,35 +13,35 @@ public static void main(String[] args) { int i = 0; while(i++ < bb.limit()) if(bb.get() != 0) - System.out.println("nonzero"); - System.out.println("i = " + i); + System.err.println("nonzero"); + System.err.println("i = " + i); bb.rewind(); // Store and read a char array: bb.asCharBuffer().put("Howdy!"); char c; while((c = bb.getChar()) != 0) - System.out.print(c + " "); - System.out.println(); + System.err.print(c + " "); + System.err.println(); bb.rewind(); // Store and read a short: bb.asShortBuffer().put((short)471142); - System.out.println(bb.getShort()); + System.err.println(bb.getShort()); bb.rewind(); // Store and read an int: bb.asIntBuffer().put(99471142); - System.out.println(bb.getInt()); + System.err.println(bb.getInt()); bb.rewind(); // Store and read a long: bb.asLongBuffer().put(99471142); - System.out.println(bb.getLong()); + System.err.println(bb.getLong()); bb.rewind(); // Store and read a float: bb.asFloatBuffer().put(99471142); - System.out.println(bb.getFloat()); + System.err.println(bb.getFloat()); bb.rewind(); // Store and read a double: bb.asDoubleBuffer().put(99471142); - System.out.println(bb.getDouble()); + System.err.println(bb.getDouble()); bb.rewind(); } } diff --git a/newio/IntBufferDemo.java b/newio/IntBufferDemo.java index 31ffaa8f8..88134272c 100644 --- a/newio/IntBufferDemo.java +++ b/newio/IntBufferDemo.java @@ -13,13 +13,13 @@ public static void main(String[] args) { // Store an array of int: ib.put(new int[]{ 11, 42, 47, 99, 143, 811, 1016 }); // Absolute location read and write: - System.out.println(ib.get(3)); + System.err.println(ib.get(3)); ib.put(3, 1811); // Setting a new limit before rewinding the buffer. ib.flip(); while(ib.hasRemaining()) { int i = ib.get(); - System.out.println(i); + System.err.println(i); } } } diff --git a/newio/LargeMappedFiles.java b/newio/LargeMappedFiles.java index c4976e450..09299b1b0 100644 --- a/newio/LargeMappedFiles.java +++ b/newio/LargeMappedFiles.java @@ -19,9 +19,9 @@ public class LargeMappedFiles { FileChannel.MapMode.READ_WRITE, 0, length); for(int i = 0; i < length; i++) out.put((byte)'x'); - System.out.println("Finished writing"); + System.err.println("Finished writing"); for(int i = length/2; i < length/2 + 6; i++) - System.out.print((char)out.get(i)); + System.err.print((char)out.get(i)); } } } diff --git a/newio/LockingMappedFiles.java b/newio/LockingMappedFiles.java index 6fe8fee52..1ccab3286 100644 --- a/newio/LockingMappedFiles.java +++ b/newio/LockingMappedFiles.java @@ -38,13 +38,13 @@ public void run() { try { // Exclusive lock with no overlap: FileLock fl = fc.lock(start, end, false); - System.out.println( + System.err.println( "Locked: "+ start +" to "+ end); // Perform modification: while(buff.position() < buff.limit() - 1) buff.put((byte)(buff.get() + 1)); fl.release(); - System.out.println( + System.err.println( "Released: " + start + " to " + end); } catch(IOException e) { throw new RuntimeException(e); diff --git a/newio/MappedIO.java b/newio/MappedIO.java index 93b4ddf3a..05bc2e352 100644 --- a/newio/MappedIO.java +++ b/newio/MappedIO.java @@ -17,11 +17,11 @@ private abstract static class Tester { this.name = name; } public void runTest() { - System.out.print(name + ": "); + System.err.print(name + ": "); long start = System.nanoTime(); test(); double duration = System.nanoTime() - start; - System.out.format("%.3f%n", duration/1.0e9); + System.err.format("%.3f%n", duration/1.0e9); } public abstract void test(); } diff --git a/newio/TransferTo.java b/newio/TransferTo.java index f3095b71e..8bca3fe86 100644 --- a/newio/TransferTo.java +++ b/newio/TransferTo.java @@ -10,7 +10,7 @@ public class TransferTo { public static void main(String[] args) { if(args.length != 2) { - System.out.println( + System.err.println( "arguments: sourcefile destfile"); System.exit(1); } diff --git a/newio/UsingBuffers.java b/newio/UsingBuffers.java index 3f3a6bd14..d307dff7f 100644 --- a/newio/UsingBuffers.java +++ b/newio/UsingBuffers.java @@ -21,11 +21,11 @@ public static void main(String[] args) { ByteBuffer.allocate(data.length * 2); CharBuffer cb = bb.asCharBuffer(); cb.put(data); - System.out.println(cb.rewind()); + System.err.println(cb.rewind()); symmetricScramble(cb); - System.out.println(cb.rewind()); + System.err.println(cb.rewind()); symmetricScramble(cb); - System.out.println(cb.rewind()); + System.err.println(cb.rewind()); } } /* Output: diff --git a/newio/ViewBuffers.java b/newio/ViewBuffers.java index d7bb1adfb..a9a7932df 100644 --- a/newio/ViewBuffers.java +++ b/newio/ViewBuffers.java @@ -9,51 +9,51 @@ public static void main(String[] args) { ByteBuffer bb = ByteBuffer.wrap( new byte[]{ 0, 0, 0, 0, 0, 0, 0, 'a' }); bb.rewind(); - System.out.print("Byte Buffer "); + System.err.print("Byte Buffer "); while(bb.hasRemaining()) - System.out.print( + System.err.print( bb.position()+ " -> " + bb.get() + ", "); - System.out.println(); + System.err.println(); CharBuffer cb = ((ByteBuffer)bb.rewind()).asCharBuffer(); - System.out.print("Char Buffer "); + System.err.print("Char Buffer "); while(cb.hasRemaining()) - System.out.print( + System.err.print( cb.position() + " -> " + cb.get() + ", "); - System.out.println(); + System.err.println(); FloatBuffer fb = ((ByteBuffer)bb.rewind()).asFloatBuffer(); - System.out.print("Float Buffer "); + System.err.print("Float Buffer "); while(fb.hasRemaining()) - System.out.print( + System.err.print( fb.position()+ " -> " + fb.get() + ", "); - System.out.println(); + System.err.println(); IntBuffer ib = ((ByteBuffer)bb.rewind()).asIntBuffer(); - System.out.print("Int Buffer "); + System.err.print("Int Buffer "); while(ib.hasRemaining()) - System.out.print( + System.err.print( ib.position()+ " -> " + ib.get() + ", "); - System.out.println(); + System.err.println(); LongBuffer lb = ((ByteBuffer)bb.rewind()).asLongBuffer(); - System.out.print("Long Buffer "); + System.err.print("Long Buffer "); while(lb.hasRemaining()) - System.out.print( + System.err.print( lb.position()+ " -> " + lb.get() + ", "); - System.out.println(); + System.err.println(); ShortBuffer sb = ((ByteBuffer)bb.rewind()).asShortBuffer(); - System.out.print("Short Buffer "); + System.err.print("Short Buffer "); while(sb.hasRemaining()) - System.out.print( + System.err.print( sb.position()+ " -> " + sb.get() + ", "); - System.out.println(); + System.err.println(); DoubleBuffer db = ((ByteBuffer)bb.rewind()).asDoubleBuffer(); - System.out.print("Double Buffer "); + System.err.print("Double Buffer "); while(db.hasRemaining()) - System.out.print( + System.err.print( db.position()+ " -> " + db.get() + ", "); } } diff --git a/objects/HelloDate.java b/objects/HelloDate.java index 1f613e8e1..8eb6ff7e3 100644 --- a/objects/HelloDate.java +++ b/objects/HelloDate.java @@ -6,7 +6,7 @@ public class HelloDate { public static void main(String[] args) { - System.out.println("Hello, it's: "); - System.out.println(new Date()); + System.err.println("Hello, it's: "); + System.err.println(new Date()); } } diff --git a/objects/ShowProperties.java b/objects/ShowProperties.java index ac2bf41ee..dbdfbf65c 100644 --- a/objects/ShowProperties.java +++ b/objects/ShowProperties.java @@ -6,8 +6,8 @@ public class ShowProperties { public static void main(String[] args) { System.getProperties().list(System.out); - System.out.println(System.getProperty("user.name")); - System.out.println( + System.err.println(System.getProperty("user.name")); + System.err.println( System.getProperty("java.library.path")); } } diff --git a/onjava/ArrayShow.java b/onjava/ArrayShow.java index 6edd148fa..b327894ad 100644 --- a/onjava/ArrayShow.java +++ b/onjava/ArrayShow.java @@ -7,67 +7,67 @@ public interface ArrayShow { static void show(Object[] a) { - System.out.println(Arrays.toString(a)); + System.err.println(Arrays.toString(a)); } static void show(boolean[] a) { - System.out.println(Arrays.toString(a)); + System.err.println(Arrays.toString(a)); } static void show(byte[] a) { - System.out.println(Arrays.toString(a)); + System.err.println(Arrays.toString(a)); } static void show(char[] a) { - System.out.println(Arrays.toString(a)); + System.err.println(Arrays.toString(a)); } static void show(short[] a) { - System.out.println(Arrays.toString(a)); + System.err.println(Arrays.toString(a)); } static void show(int[] a) { - System.out.println(Arrays.toString(a)); + System.err.println(Arrays.toString(a)); } static void show(long[] a) { - System.out.println(Arrays.toString(a)); + System.err.println(Arrays.toString(a)); } static void show(float[] a) { - System.out.println(Arrays.toString(a)); + System.err.println(Arrays.toString(a)); } static void show(double[] a) { - System.out.println(Arrays.toString(a)); + System.err.println(Arrays.toString(a)); } // Start with a description: static void show(String info, Object[] a) { - System.out.print(info + ": "); + System.err.print(info + ": "); show(a); } static void show(String info, boolean[] a) { - System.out.print(info + ": "); + System.err.print(info + ": "); show(a); } static void show(String info, byte[] a) { - System.out.print(info + ": "); + System.err.print(info + ": "); show(a); } static void show(String info, char[] a) { - System.out.print(info + ": "); + System.err.print(info + ": "); show(a); } static void show(String info, short[] a) { - System.out.print(info + ": "); + System.err.print(info + ": "); show(a); } static void show(String info, int[] a) { - System.out.print(info + ": "); + System.err.print(info + ": "); show(a); } static void show(String info, long[] a) { - System.out.print(info + ": "); + System.err.print(info + ": "); show(a); } static void show(String info, float[] a) { - System.out.print(info + ": "); + System.err.print(info + ": "); show(a); } static void show(String info, double[] a) { - System.out.print(info + ": "); + System.err.print(info + ": "); show(a); } } diff --git a/onjava/CollectionMethodDifferences.java b/onjava/CollectionMethodDifferences.java index 375d4e419..5d8ebd7b2 100644 --- a/onjava/CollectionMethodDifferences.java +++ b/onjava/CollectionMethodDifferences.java @@ -3,7 +3,7 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {java onjava.CollectionMethodDifferences} -package onjava; +//package onjava; import java.lang.reflect.*; import java.util.*; import java.util.stream.*; @@ -15,40 +15,40 @@ static Set methodSet(Class type) { .collect(Collectors.toCollection(TreeSet::new)); } static void interfaces(Class type) { - System.out.print("Interfaces in " + + System.err.print("Interfaces in " + type.getSimpleName() + ": "); - System.out.println( + System.err.println( Arrays.stream(type.getInterfaces()) .map(Class::getSimpleName) .collect(Collectors.toList())); } static Set object = methodSet(Object.class); static { object.add("clone"); } - static void - difference(Class superset, Class subset) { - System.out.print(superset.getSimpleName() + + static void difference(Class superset, Class subset) { + System.err.print(superset.getSimpleName() + " extends " + subset.getSimpleName() + ", adds: "); Set comp = Sets.difference( methodSet(superset), methodSet(subset)); comp.removeAll(object); // Ignore 'Object' methods - System.out.println(comp); + System.err.println(comp); interfaces(superset); } public static void main(String[] args) { - System.out.println("Collection: " + + System.err.println("Collection: " + methodSet(Collection.class)); interfaces(Collection.class); difference(Set.class, Collection.class); difference(HashSet.class, Set.class); difference(LinkedHashSet.class, HashSet.class); + System.err.println("*******************************************"); difference(TreeSet.class, Set.class); difference(List.class, Collection.class); difference(ArrayList.class, List.class); difference(LinkedList.class, List.class); difference(Queue.class, Collection.class); difference(PriorityQueue.class, Queue.class); - System.out.println("Map: " + methodSet(Map.class)); + System.err.println("Map: " + methodSet(Map.class)); difference(HashMap.class, Map.class); difference(LinkedHashMap.class, HashMap.class); difference(SortedMap.class, Map.class); diff --git a/onjava/CountMap.java b/onjava/CountMap.java index e3759053c..854ac0bef 100644 --- a/onjava/CountMap.java +++ b/onjava/CountMap.java @@ -60,12 +60,12 @@ public Set> entrySet() { public static void main(String[] args) { final int size = 6; CountMap cm = new CountMap(60); - System.out.println(cm); - System.out.println(cm.get(500)); + System.err.println(cm); + System.err.println(cm.get(500)); cm.values().stream() .limit(size) .forEach(System.out::println); - System.out.println(); + System.err.println(); new Random(47).ints(size, 0, 1000) .mapToObj(cm::get) .forEach(System.out::println); diff --git a/onjava/CountingIntegerList.java b/onjava/CountingIntegerList.java index 7d5d4f79b..5c879d432 100644 --- a/onjava/CountingIntegerList.java +++ b/onjava/CountingIntegerList.java @@ -23,8 +23,8 @@ public Integer get(int index) { public static void main(String[] args) { List cil = new CountingIntegerList(30); - System.out.println(cil); - System.out.println(cil.get(500)); + System.err.println(cil); + System.err.println(cil.get(500)); } } /* Output: diff --git a/onjava/Countries.java b/onjava/Countries.java index ec42b5922..ce4f1e4b6 100644 --- a/onjava/Countries.java +++ b/onjava/Countries.java @@ -310,19 +310,19 @@ public static List names(int size) { return new ArrayList<>(select(size).keySet()); } public static void main(String[] args) { - System.out.println(capitals(10)); - System.out.println(names(10)); - System.out.println(new HashMap<>(capitals(3))); - System.out.println( + System.err.println(capitals(10)); + System.err.println(names(10)); + System.err.println(new HashMap<>(capitals(3))); + System.err.println( new LinkedHashMap<>(capitals(3))); - System.out.println(new TreeMap<>(capitals(3))); - System.out.println(new Hashtable<>(capitals(3))); - System.out.println(new HashSet<>(names(6))); - System.out.println(new LinkedHashSet<>(names(6))); - System.out.println(new TreeSet<>(names(6))); - System.out.println(new ArrayList<>(names(6))); - System.out.println(new LinkedList<>(names(6))); - System.out.println(capitals().get("BRAZIL")); + System.err.println(new TreeMap<>(capitals(3))); + System.err.println(new Hashtable<>(capitals(3))); + System.err.println(new HashSet<>(names(6))); + System.err.println(new LinkedHashSet<>(names(6))); + System.err.println(new TreeSet<>(names(6))); + System.err.println(new ArrayList<>(names(6))); + System.err.println(new LinkedList<>(names(6))); + System.err.println(capitals().get("BRAZIL")); } } /* Output: diff --git a/onjava/HTMLColors.java b/onjava/HTMLColors.java index bdc3458f0..fa63eabf9 100644 --- a/onjava/HTMLColors.java +++ b/onjava/HTMLColors.java @@ -188,7 +188,7 @@ public static Integer rgb(String colorName) { .collect(Collectors.toList()); public static void show(Map.Entry e) { - System.out.format( + System.err.format( "0x%06X: %s%n", e.getKey(), e.getValue()); } public static void @@ -213,7 +213,7 @@ public static void show(Collection lst) { void showrgb(Collection lst, int count) { lst.stream() .limit(count) - .forEach(n -> System.out.format("0x%06X%n", n)); + .forEach(n -> System.err.format("0x%06X%n", n)); } public static void showrgb(Collection lst) { showrgb(lst, lst.size()); @@ -223,14 +223,14 @@ void showInv(Map m, int count) { m.entrySet().stream() .limit(count) .forEach(e -> - System.out.format( + System.err.format( "%-20s 0x%06X%n", e.getKey(), e.getValue())); } public static void showInv(Map m) { showInv(m, m.size()); } public static void border() { - System.out.println( + System.err.println( "******************************"); } } diff --git a/onjava/Nap.java b/onjava/Nap.java index 2b89745b1..4e3541bb1 100644 --- a/onjava/Nap.java +++ b/onjava/Nap.java @@ -15,6 +15,6 @@ public Nap(double t) { // Seconds } public Nap(double t, String msg) { this(t); - System.out.println(msg); + System.err.println(msg); } } diff --git a/onjava/Operations.java b/onjava/Operations.java index 33b644c65..fd1cc47ac 100644 --- a/onjava/Operations.java +++ b/onjava/Operations.java @@ -2,7 +2,7 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -package onjava; + import java.util.*; public interface Operations { @@ -12,6 +12,6 @@ static void runOps(Operations... ops) { op.execute(); } static void show(String msg) { - System.out.println(msg); + System.err.println(msg); } } diff --git a/onjava/RmDir.java b/onjava/RmDir.java index be7ea4940..4d0ee5e1a 100644 --- a/onjava/RmDir.java +++ b/onjava/RmDir.java @@ -2,27 +2,21 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -package onjava; +//package onjava; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; import java.io.IOException; public class RmDir { - public static void rmdir(Path dir) - throws IOException { - Files.walkFileTree(dir, - new SimpleFileVisitor() { + public static void rmdir(Path dir) throws IOException { + Files.walkFileTree(dir, new SimpleFileVisitor() { @Override - public FileVisitResult - visitFile(Path file, BasicFileAttributes attrs) - throws IOException { + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } @Override - public FileVisitResult - postVisitDirectory(Path dir, IOException exc) - throws IOException { + public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { Files.delete(dir); return FileVisitResult.CONTINUE; } diff --git a/onjava/Sets.java b/onjava/Sets.java index 62258f155..7c3941924 100644 --- a/onjava/Sets.java +++ b/onjava/Sets.java @@ -2,7 +2,7 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -package onjava; +//package onjava; import java.util.*; public class Sets { @@ -11,22 +11,19 @@ public static Set union(Set a, Set b) { result.addAll(b); return result; } - public static - Set intersection(Set a, Set b) { + public static Set intersection(Set a, Set b) { Set result = new HashSet<>(a); result.retainAll(b); return result; } // Subtract subset from superset: - public static Set - difference(Set superset, Set subset) { + public static Set difference(Set superset, Set subset) { Set result = new HashSet<>(superset); result.removeAll(subset); return result; } // Reflexive--everything not in the intersection: - public static - Set complement(Set a, Set b) { + public static Set complement(Set a, Set b) { return difference(union(a, b), intersection(a, b)); } } diff --git a/onjava/Stack.java b/onjava/Stack.java index a51081768..51faffb0c 100644 --- a/onjava/Stack.java +++ b/onjava/Stack.java @@ -3,7 +3,7 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // A Stack class built with an ArrayDeque -package onjava; +//package onjava; import java.util.Deque; import java.util.ArrayDeque; diff --git a/onjava/Suppliers.java b/onjava/Suppliers.java index 226a70cb5..787ac736e 100644 --- a/onjava/Suppliers.java +++ b/onjava/Suppliers.java @@ -3,7 +3,7 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // A utility to use with Suppliers -package onjava; +//package onjava; import java.util.*; import java.util.function.*; import java.util.stream.*; @@ -17,8 +17,7 @@ public class Suppliers { .collect(factory, C::add, C::addAll); } // Fill an existing collection: - public static > - C fill(C coll, Supplier gen, int n) { + public static > C fill(C coll, Supplier gen, int n) { Stream.generate(gen) .limit(n) .forEach(coll::add); diff --git a/onjava/TimedAbort.java b/onjava/TimedAbort.java index 3715cf2ee..cd1fba7b9 100644 --- a/onjava/TimedAbort.java +++ b/onjava/TimedAbort.java @@ -19,7 +19,7 @@ public TimedAbort(double t, String msg) { } catch(InterruptedException e) { throw new RuntimeException(e); } - System.out.println(msg); + System.err.println(msg); System.exit(0); }); } diff --git a/onjava/Tuple.java b/onjava/Tuple.java index 73cfaa3ce..6456c69f0 100644 --- a/onjava/Tuple.java +++ b/onjava/Tuple.java @@ -3,22 +3,22 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Tuple library using type argument inference -package onjava; +//package onjava; public class Tuple { - public static Tuple2 tuple(A a, B b) { - return new Tuple2<>(a, b); - } - public static Tuple3 - tuple(A a, B b, C c) { - return new Tuple3<>(a, b, c); - } - public static Tuple4 - tuple(A a, B b, C c, D d) { - return new Tuple4<>(a, b, c, d); - } - public static - Tuple5 tuple(A a, B b, C c, D d, E e) { - return new Tuple5<>(a, b, c, d, e); - } + public static Tuple2 tuple(A a, B b) { + return new Tuple2<>(a, b); + } + + public static Tuple3 tuple(A a, B b, C c) { + return new Tuple3<>(a, b, c); + } + + public static Tuple4 tuple(A a, B b, C c, D d) { + return new Tuple4<>(a, b, c, d); + } + + public static Tuple5 tuple(A a, B b, C c, D d, E e) { + return new Tuple5<>(a, b, c, d, e); + } } diff --git a/onjava/Tuple2.java b/onjava/Tuple2.java index 7ca8d1994..1fc723c6b 100644 --- a/onjava/Tuple2.java +++ b/onjava/Tuple2.java @@ -2,7 +2,7 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -package onjava; +//package onjava; public class Tuple2 { public final A a1; diff --git a/onjava/Tuple3.java b/onjava/Tuple3.java index 26780642c..6ddc9c580 100644 --- a/onjava/Tuple3.java +++ b/onjava/Tuple3.java @@ -2,7 +2,7 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -package onjava; +//package onjava; public class Tuple3 extends Tuple2 { public final C a3; diff --git a/onjava/Tuple4.java b/onjava/Tuple4.java index 5ab51dc98..e61e54167 100644 --- a/onjava/Tuple4.java +++ b/onjava/Tuple4.java @@ -2,7 +2,7 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -package onjava; +//package onjava; public class Tuple4 extends Tuple3 { diff --git a/onjava/Tuple5.java b/onjava/Tuple5.java index 1df88bfdc..a089131bb 100644 --- a/onjava/Tuple5.java +++ b/onjava/Tuple5.java @@ -2,7 +2,7 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -package onjava; +//package onjava; public class Tuple5 extends Tuple4 { diff --git a/onjava/TypeCounter.java b/onjava/TypeCounter.java index d8b262b72..7a6b3cdc8 100644 --- a/onjava/TypeCounter.java +++ b/onjava/TypeCounter.java @@ -3,12 +3,11 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Counts instances of a type family -package onjava; +//package onjava; import java.util.*; import java.util.stream.*; -public class -TypeCounter extends HashMap, Integer> { +public class TypeCounter extends HashMap, Integer> { private Class baseType; public TypeCounter(Class baseType) { this.baseType = baseType; diff --git a/onjava/atunit/AtUnit.java b/onjava/atunit/AtUnit.java index b1688cbda..2edfd92cb 100644 --- a/onjava/atunit/AtUnit.java +++ b/onjava/atunit/AtUnit.java @@ -23,14 +23,14 @@ public class AtUnit implements ProcessFiles.Strategy { .setDefaultAssertionStatus(true); // Enable assert new ProcessFiles(new AtUnit(), "class").start(args); if(failures == 0) - System.out.println("OK (" + testsRun + " tests)"); + System.err.println("OK (" + testsRun + " tests)"); else { - System.out.println("(" + testsRun + " tests)"); - System.out.println( + System.err.println("(" + testsRun + " tests)"); + System.err.println( "\n>>> " + failures + " FAILURE" + (failures > 1 ? "S" : "") + " <<<"); for(String failed : failedTests) - System.out.println(" " + failed); + System.err.println(" " + failed); } } @Override @@ -63,17 +63,17 @@ public void process(File cFile) { if(!Modifier.isPublic(testClass .getDeclaredConstructor() .getModifiers())) { - System.out.println("Error: " + testClass + + System.err.println("Error: " + testClass + " no-arg constructor must be public"); System.exit(1); } } catch(NoSuchMethodException e) { // Synthesized no-arg constructor; OK } - System.out.println(testClass.getName()); + System.err.println(testClass.getName()); } for(Method m : testMethods) { - System.out.print(" . " + m.getName() + " "); + System.err.print(" . " + m.getName() + " "); try { Object testObject = createTestObject(creator); boolean success = false; @@ -86,9 +86,9 @@ public void process(File cFile) { } } catch(InvocationTargetException e) { // Actual exception is inside e: - System.out.println(e.getCause()); + System.err.println(e.getCause()); } - System.out.println(success ? "" : "(failed)"); + System.err.println(success ? "" : "(failed)"); testsRun++; if(!success) { failures++; diff --git a/operators/Assignment.java b/operators/Assignment.java index 7a573a392..7b6e32166 100644 --- a/operators/Assignment.java +++ b/operators/Assignment.java @@ -14,13 +14,13 @@ public static void main(String[] args) { Tank t2 = new Tank(); t1.level = 9; t2.level = 47; - System.out.println("1: t1.level: " + t1.level + + System.err.println("1: t1.level: " + t1.level + ", t2.level: " + t2.level); t1 = t2; - System.out.println("2: t1.level: " + t1.level + + System.err.println("2: t1.level: " + t1.level + ", t2.level: " + t2.level); t1.level = 27; - System.out.println("3: t1.level: " + t1.level + + System.err.println("3: t1.level: " + t1.level + ", t2.level: " + t2.level); } } diff --git a/operators/AutoInc.java b/operators/AutoInc.java index 835875de6..dfc07c3c1 100644 --- a/operators/AutoInc.java +++ b/operators/AutoInc.java @@ -7,13 +7,13 @@ public class AutoInc { public static void main(String[] args) { int i = 1; - System.out.println("i: " + i); - System.out.println("++i: " + ++i); // Pre-increment - System.out.println("i++: " + i++); // Post-increment - System.out.println("i: " + i); - System.out.println("--i: " + --i); // Pre-decrement - System.out.println("i--: " + i--); // Post-decrement - System.out.println("i: " + i); + System.err.println("i: " + i); + System.err.println("++i: " + ++i); // Pre-increment + System.err.println("i++: " + i++); // Post-increment + System.err.println("i: " + i); + System.err.println("--i: " + --i); // Pre-decrement + System.err.println("i--: " + i--); // Post-decrement + System.err.println("i: " + i); } } /* Output: diff --git a/operators/BitManipulation.java b/operators/BitManipulation.java index dc30c4428..6b93e5db9 100644 --- a/operators/BitManipulation.java +++ b/operators/BitManipulation.java @@ -51,12 +51,12 @@ public static void main(String[] args) { printBinaryLong("(~l) >>> 5", (~l) >>> 5); } static void printBinaryInt(String s, int i) { - System.out.println( + System.err.println( s + ", int: " + i + ", binary:\n " + Integer.toBinaryString(i)); } static void printBinaryLong(String s, long l) { - System.out.println( + System.err.println( s + ", long: " + l + ", binary:\n " + Long.toBinaryString(l)); } diff --git a/operators/Bool.java b/operators/Bool.java index e9984adb7..bb0b2d2e5 100644 --- a/operators/Bool.java +++ b/operators/Bool.java @@ -10,21 +10,21 @@ public static void main(String[] args) { Random rand = new Random(47); int i = rand.nextInt(100); int j = rand.nextInt(100); - System.out.println("i = " + i); - System.out.println("j = " + j); - System.out.println("i > j is " + (i > j)); - System.out.println("i < j is " + (i < j)); - System.out.println("i >= j is " + (i >= j)); - System.out.println("i <= j is " + (i <= j)); - System.out.println("i == j is " + (i == j)); - System.out.println("i != j is " + (i != j)); + System.err.println("i = " + i); + System.err.println("j = " + j); + System.err.println("i > j is " + (i > j)); + System.err.println("i < j is " + (i < j)); + System.err.println("i >= j is " + (i >= j)); + System.err.println("i <= j is " + (i <= j)); + System.err.println("i == j is " + (i == j)); + System.err.println("i != j is " + (i != j)); // Treating an int as a boolean is not legal Java: - //- System.out.println("i && j is " + (i && j)); - //- System.out.println("i || j is " + (i || j)); - //- System.out.println("!i is " + !i); - System.out.println("(i < 10) && (j < 10) is " + //- System.err.println("i && j is " + (i && j)); + //- System.err.println("i || j is " + (i || j)); + //- System.err.println("!i is " + !i); + System.err.println("(i < 10) && (j < 10) is " + ((i < 10) && (j < 10)) ); - System.out.println("(i < 10) || (j < 10) is " + System.err.println("(i < 10) || (j < 10) is " + ((i < 10) || (j < 10)) ); } } diff --git a/operators/CastingNumbers.java b/operators/CastingNumbers.java index a6c04c6ea..23061c5ef 100644 --- a/operators/CastingNumbers.java +++ b/operators/CastingNumbers.java @@ -9,10 +9,10 @@ public class CastingNumbers { public static void main(String[] args) { double above = 0.7, below = 0.4; float fabove = 0.7f, fbelow = 0.4f; - System.out.println("(int)above: " + (int)above); - System.out.println("(int)below: " + (int)below); - System.out.println("(int)fabove: " + (int)fabove); - System.out.println("(int)fbelow: " + (int)fbelow); + System.err.println("(int)above: " + (int)above); + System.err.println("(int)below: " + (int)below); + System.err.println("(int)fabove: " + (int)fabove); + System.err.println("(int)fbelow: " + (int)fbelow); } } /* Output: diff --git a/operators/EqualsMethod.java b/operators/EqualsMethod.java index f55b1b579..e0171a8ea 100644 --- a/operators/EqualsMethod.java +++ b/operators/EqualsMethod.java @@ -7,7 +7,7 @@ public class EqualsMethod { public static void main(String[] args) { Integer n1 = 47; Integer n2 = 47; - System.out.println(n1.equals(n2)); + System.err.println(n1.equals(n2)); } } /* Output: diff --git a/operators/EqualsMethod2.java b/operators/EqualsMethod2.java index 213930602..1f39c10a2 100644 --- a/operators/EqualsMethod2.java +++ b/operators/EqualsMethod2.java @@ -13,7 +13,7 @@ public static void main(String[] args) { Value v1 = new Value(); Value v2 = new Value(); v1.i = v2.i = 100; - System.out.println(v1.equals(v2)); + System.err.println(v1.equals(v2)); } } /* Output: diff --git a/operators/Equivalence.java b/operators/Equivalence.java index cef07d646..159a7febf 100644 --- a/operators/Equivalence.java +++ b/operators/Equivalence.java @@ -7,8 +7,8 @@ public class Equivalence { public static void main(String[] args) { Integer n1 = 47; Integer n2 = 47; - System.out.println(n1 == n2); - System.out.println(n1 != n2); + System.err.println(n1 == n2); + System.err.println(n1 != n2); } } /* Output: diff --git a/operators/Exponents.java b/operators/Exponents.java index 924340dfb..8ead7c51f 100644 --- a/operators/Exponents.java +++ b/operators/Exponents.java @@ -9,10 +9,10 @@ public static void main(String[] args) { // Uppercase and lowercase 'e' are the same: float expFloat = 1.39e-43f; expFloat = 1.39E-43f; - System.out.println(expFloat); + System.err.println(expFloat); double expDouble = 47e47d; // 'd' is optional double expDouble2 = 47e47; // Automatically double - System.out.println(expDouble); + System.err.println(expDouble); } } /* Output: diff --git a/operators/Literals.java b/operators/Literals.java index ad00e0b8f..0121895fe 100644 --- a/operators/Literals.java +++ b/operators/Literals.java @@ -6,38 +6,38 @@ public class Literals { public static void main(String[] args) { int i1 = 0x2f; // Hexadecimal (lowercase) - System.out.println( + System.err.println( "i1: " + Integer.toBinaryString(i1)); int i2 = 0X2F; // Hexadecimal (uppercase) - System.out.println( + System.err.println( "i2: " + Integer.toBinaryString(i2)); int i3 = 0177; // Octal (leading zero) - System.out.println( + System.err.println( "i3: " + Integer.toBinaryString(i3)); char c = 0xffff; // max char hex value - System.out.println( + System.err.println( "c: " + Integer.toBinaryString(c)); byte b = 0x7f; // max byte hex value 10101111; - System.out.println( + System.err.println( "b: " + Integer.toBinaryString(b)); short s = 0x7fff; // max short hex value - System.out.println( + System.err.println( "s: " + Integer.toBinaryString(s)); long n1 = 200L; // long suffix long n2 = 200l; // long suffix (can be confusing) long n3 = 200; // Java 7 Binary Literals: byte blb = (byte)0b00110101; - System.out.println( + System.err.println( "blb: " + Integer.toBinaryString(blb)); short bls = (short)0B0010111110101111; - System.out.println( + System.err.println( "bls: " + Integer.toBinaryString(bls)); int bli = 0b00101111101011111010111110101111; - System.out.println( + System.err.println( "bli: " + Integer.toBinaryString(bli)); long bll = 0b00101111101011111010111110101111; - System.out.println( + System.err.println( "bll: " + Long.toBinaryString(bll)); float f1 = 1; float f2 = 1F; // float suffix diff --git a/operators/MathOps.java b/operators/MathOps.java index a9b089382..dcb0a0e16 100644 --- a/operators/MathOps.java +++ b/operators/MathOps.java @@ -12,45 +12,45 @@ public static void main(String[] args) { int i, j, k; // Choose value from 1 to 100: j = rand.nextInt(100) + 1; - System.out.println("j : " + j); + System.err.println("j : " + j); k = rand.nextInt(100) + 1; - System.out.println("k : " + k); + System.err.println("k : " + k); i = j + k; - System.out.println("j + k : " + i); + System.err.println("j + k : " + i); i = j - k; - System.out.println("j - k : " + i); + System.err.println("j - k : " + i); i = k / j; - System.out.println("k / j : " + i); + System.err.println("k / j : " + i); i = k * j; - System.out.println("k * j : " + i); + System.err.println("k * j : " + i); i = k % j; - System.out.println("k % j : " + i); + System.err.println("k % j : " + i); j %= k; - System.out.println("j %= k : " + j); + System.err.println("j %= k : " + j); // Floating-point number tests: float u, v, w; // Applies to doubles, too v = rand.nextFloat(); - System.out.println("v : " + v); + System.err.println("v : " + v); w = rand.nextFloat(); - System.out.println("w : " + w); + System.err.println("w : " + w); u = v + w; - System.out.println("v + w : " + u); + System.err.println("v + w : " + u); u = v - w; - System.out.println("v - w : " + u); + System.err.println("v - w : " + u); u = v * w; - System.out.println("v * w : " + u); + System.err.println("v * w : " + u); u = v / w; - System.out.println("v / w : " + u); + System.err.println("v / w : " + u); // The following also works for char, // byte, short, int, long, and double: u += v; - System.out.println("u += v : " + u); + System.err.println("u += v : " + u); u -= v; - System.out.println("u -= v : " + u); + System.err.println("u -= v : " + u); u *= v; - System.out.println("u *= v : " + u); + System.err.println("u *= v : " + u); u /= v; - System.out.println("u /= v : " + u); + System.err.println("u /= v : " + u); } } /* Output: diff --git a/operators/Overflow.java b/operators/Overflow.java index 851c1456b..3ddb4a09e 100644 --- a/operators/Overflow.java +++ b/operators/Overflow.java @@ -7,9 +7,9 @@ public class Overflow { public static void main(String[] args) { int big = Integer.MAX_VALUE; - System.out.println("big = " + big); + System.err.println("big = " + big); int bigger = big * 4; - System.out.println("bigger = " + bigger); + System.err.println("bigger = " + bigger); } } /* Output: diff --git a/operators/PassObject.java b/operators/PassObject.java index af53ab566..f31d7020b 100644 --- a/operators/PassObject.java +++ b/operators/PassObject.java @@ -16,9 +16,9 @@ static void f(Letter y) { public static void main(String[] args) { Letter x = new Letter(); x.c = 'a'; - System.out.println("1: x.c: " + x.c); + System.err.println("1: x.c: " + x.c); f(x); - System.out.println("2: x.c: " + x.c); + System.err.println("2: x.c: " + x.c); } } /* Output: diff --git a/operators/Precedence.java b/operators/Precedence.java index f0f8140cd..7905bb1db 100644 --- a/operators/Precedence.java +++ b/operators/Precedence.java @@ -8,8 +8,8 @@ public static void main(String[] args) { int x = 1, y = 2, z = 3; int a = x + y - 2/2 + z; // [1] int b = x + (y - 2)/(2 + z); // [2] - System.out.println("a = " + a); - System.out.println("b = " + b); + System.err.println("a = " + a); + System.err.println("b = " + b); } } /* Output: diff --git a/operators/RoundingNumbers.java b/operators/RoundingNumbers.java index e46a20561..89cfd05a3 100644 --- a/operators/RoundingNumbers.java +++ b/operators/RoundingNumbers.java @@ -8,13 +8,13 @@ public class RoundingNumbers { public static void main(String[] args) { double above = 0.7, below = 0.4; float fabove = 0.7f, fbelow = 0.4f; - System.out.println( + System.err.println( "Math.round(above): " + Math.round(above)); - System.out.println( + System.err.println( "Math.round(below): " + Math.round(below)); - System.out.println( + System.err.println( "Math.round(fabove): " + Math.round(fabove)); - System.out.println( + System.err.println( "Math.round(fbelow): " + Math.round(fbelow)); } } diff --git a/operators/ShortCircuit.java b/operators/ShortCircuit.java index 8fc96711e..cb253f7a7 100644 --- a/operators/ShortCircuit.java +++ b/operators/ShortCircuit.java @@ -6,23 +6,23 @@ public class ShortCircuit { static boolean test1(int val) { - System.out.println("test1(" + val + ")"); - System.out.println("result: " + (val < 1)); + System.err.println("test1(" + val + ")"); + System.err.println("result: " + (val < 1)); return val < 1; } static boolean test2(int val) { - System.out.println("test2(" + val + ")"); - System.out.println("result: " + (val < 2)); + System.err.println("test2(" + val + ")"); + System.err.println("result: " + (val < 2)); return val < 2; } static boolean test3(int val) { - System.out.println("test3(" + val + ")"); - System.out.println("result: " + (val < 3)); + System.err.println("test3(" + val + ")"); + System.err.println("result: " + (val < 3)); return val < 3; } public static void main(String[] args) { boolean b = test1(0) && test2(2) && test3(2); - System.out.println("expression is " + b); + System.err.println("expression is " + b); } } /* Output: diff --git a/operators/StringOperators.java b/operators/StringOperators.java index b1eb211fb..66b391b2a 100644 --- a/operators/StringOperators.java +++ b/operators/StringOperators.java @@ -7,13 +7,13 @@ public class StringOperators { public static void main(String[] args) { int x = 0, y = 1, z = 2; String s = "x, y, z "; - System.out.println(s + x + y + z); + System.err.println(s + x + y + z); // Converts x to a String: - System.out.println(x + " " + s); + System.err.println(x + " " + s); s += "(summed) = "; // Concatenation operator - System.out.println(s + (x + y + z)); + System.err.println(s + (x + y + z)); // Shorthand for Integer.toString(): - System.out.println("" + x); + System.err.println("" + x); } } /* Output: diff --git a/operators/TernaryIfElse.java b/operators/TernaryIfElse.java index d11d4e24c..b180292bb 100644 --- a/operators/TernaryIfElse.java +++ b/operators/TernaryIfElse.java @@ -14,10 +14,10 @@ static int standardIfElse(int i) { return i * 10; } public static void main(String[] args) { - System.out.println(ternary(9)); - System.out.println(ternary(10)); - System.out.println(standardIfElse(9)); - System.out.println(standardIfElse(10)); + System.err.println(ternary(9)); + System.err.println(ternary(10)); + System.err.println(standardIfElse(9)); + System.err.println(standardIfElse(10)); } } /* Output: diff --git a/operators/URShift.java b/operators/URShift.java index 8d24f94b5..275f90666 100644 --- a/operators/URShift.java +++ b/operators/URShift.java @@ -7,24 +7,24 @@ public class URShift { public static void main(String[] args) { int i = -1; - System.out.println(Integer.toBinaryString(i)); + System.err.println(Integer.toBinaryString(i)); i >>>= 10; - System.out.println(Integer.toBinaryString(i)); + System.err.println(Integer.toBinaryString(i)); long l = -1; - System.out.println(Long.toBinaryString(l)); + System.err.println(Long.toBinaryString(l)); l >>>= 10; - System.out.println(Long.toBinaryString(l)); + System.err.println(Long.toBinaryString(l)); short s = -1; - System.out.println(Integer.toBinaryString(s)); + System.err.println(Integer.toBinaryString(s)); s >>>= 10; - System.out.println(Integer.toBinaryString(s)); + System.err.println(Integer.toBinaryString(s)); byte b = -1; - System.out.println(Integer.toBinaryString(b)); + System.err.println(Integer.toBinaryString(b)); b >>>= 10; - System.out.println(Integer.toBinaryString(b)); + System.err.println(Integer.toBinaryString(b)); b = -1; - System.out.println(Integer.toBinaryString(b)); - System.out.println(Integer.toBinaryString(b>>>10)); + System.err.println(Integer.toBinaryString(b)); + System.err.println(Integer.toBinaryString(b>>>10)); } } /* Output: diff --git a/operators/Underscores.java b/operators/Underscores.java index 4d78cd503..6104c2650 100644 --- a/operators/Underscores.java +++ b/operators/Underscores.java @@ -6,12 +6,12 @@ public class Underscores { public static void main(String[] args) { double d = 341_435_936.445_667; - System.out.println(d); + System.err.println(d); int bin = 0b0010_1111_1010_1111_1010_1111_1010_1111; - System.out.println(Integer.toBinaryString(bin)); - System.out.printf("%x%n", bin); // [1] + System.err.println(Integer.toBinaryString(bin)); + System.err.printf("%x%n", bin); // [1] long hex = 0x7f_e9_b7_aa; - System.out.printf("%x%n", hex); + System.err.printf("%x%n", hex); } } /* Output: diff --git a/patterns/CommandPattern.java b/patterns/CommandPattern.java index f84533aa9..c9cecccf2 100644 --- a/patterns/CommandPattern.java +++ b/patterns/CommandPattern.java @@ -7,9 +7,9 @@ public class CommandPattern { public static void main(String[] args) { List macro = Arrays.asList( - () -> System.out.print("Hello "), - () -> System.out.print("World! "), - () -> System.out.print("I'm the command pattern!") + () -> System.err.print("Hello "), + () -> System.err.print("World! "), + () -> System.err.print("I'm the command pattern!") ); macro.forEach(Runnable::run); } diff --git a/patterns/PaperScissorsRock.java b/patterns/PaperScissorsRock.java index e7a7c44e8..d9d5bc78e 100644 --- a/patterns/PaperScissorsRock.java +++ b/patterns/PaperScissorsRock.java @@ -98,7 +98,7 @@ public static Tuple2 newPair() { class Compete { public static Outcome match(Tuple2 p) { - System.out.print(p.a1 + " -> " + p.a2 + " : "); + System.err.print(p.a1 + " -> " + p.a2 + " : "); return p.a1.compete(p.a2); } } diff --git a/patterns/ProxyDemo.java b/patterns/ProxyDemo.java index 58b0e3a8f..99fb58b86 100644 --- a/patterns/ProxyDemo.java +++ b/patterns/ProxyDemo.java @@ -26,13 +26,13 @@ class Proxy implements ProxyBase { class Implementation implements ProxyBase { public void f() { - System.out.println("Implementation.f()"); + System.err.println("Implementation.f()"); } public void g() { - System.out.println("Implementation.g()"); + System.err.println("Implementation.g()"); } public void h() { - System.out.println("Implementation.h()"); + System.err.println("Implementation.h()"); } } diff --git a/patterns/ShapeFactory2.java b/patterns/ShapeFactory2.java index 238811052..cc0fce358 100644 --- a/patterns/ShapeFactory2.java +++ b/patterns/ShapeFactory2.java @@ -11,7 +11,7 @@ public class ShapeFactory2 implements FactoryMethod { Map factories = new HashMap<>(); static Constructor load(String id) { - System.out.println("loading " + id); + System.err.println("loading " + id); try { return Class.forName("patterns.shapes." + id) .getConstructor(); diff --git a/patterns/SingletonPattern.java b/patterns/SingletonPattern.java index c2ca1a5f5..256880702 100644 --- a/patterns/SingletonPattern.java +++ b/patterns/SingletonPattern.java @@ -40,10 +40,10 @@ public static Resource getResource() { public class SingletonPattern { public static void main(String[] args) { Resource r = Singleton.getResource(); - System.out.println(r.getValue()); + System.err.println(r.getValue()); Resource s2 = Singleton.getResource(); s2.setValue(9); - System.out.println(r.getValue()); + System.err.println(r.getValue()); try { // Can't do this: compile-time error. // Singleton s3 = (Singleton)s2.clone(); diff --git a/patterns/StateDemo.java b/patterns/StateDemo.java index 9efab5b4e..491e0897b 100644 --- a/patterns/StateDemo.java +++ b/patterns/StateDemo.java @@ -32,15 +32,15 @@ public void changeImp(StateBase newImp) { class Implementation1 implements StateBase { @Override public void f() { - System.out.println("Implementation1.f()"); + System.err.println("Implementation1.f()"); } @Override public void g() { - System.out.println("Implementation1.g()"); + System.err.println("Implementation1.g()"); } @Override public void h() { - System.out.println("Implementation1.h()"); + System.err.println("Implementation1.h()"); } @Override public void changeImp(StateBase newImp) {} @@ -49,15 +49,15 @@ public void changeImp(StateBase newImp) {} class Implementation2 implements StateBase { @Override public void f() { - System.out.println("Implementation2.f()"); + System.err.println("Implementation2.f()"); } @Override public void g() { - System.out.println("Implementation2.g()"); + System.err.println("Implementation2.g()"); } @Override public void h() { - System.out.println("Implementation2.h()"); + System.err.println("Implementation2.h()"); } @Override public void changeImp(StateBase newImp) {} diff --git a/patterns/TemplateMethod.java b/patterns/TemplateMethod.java index eff6d2790..dde195608 100644 --- a/patterns/TemplateMethod.java +++ b/patterns/TemplateMethod.java @@ -22,11 +22,11 @@ private void templateMethod() { class MyApp extends ApplicationFramework { @Override void customize1() { - System.out.print("Hello "); + System.err.print("Hello "); } @Override void customize2() { - System.out.println("World!"); + System.err.println("World!"); } } diff --git a/patterns/abstractfactory/GameEnvironment.java b/patterns/abstractfactory/GameEnvironment.java index 8c0abf7b3..fc238a830 100644 --- a/patterns/abstractfactory/GameEnvironment.java +++ b/patterns/abstractfactory/GameEnvironment.java @@ -18,7 +18,7 @@ interface Player { class Kitty implements Player { @Override public void interactWith(Obstacle ob) { - System.out.print("Kitty has encountered a "); + System.err.print("Kitty has encountered a "); ob.action(); } } @@ -26,7 +26,7 @@ public void interactWith(Obstacle ob) { class KungFuGuy implements Player { @Override public void interactWith(Obstacle ob) { - System.out.print("KungFuGuy now battles a "); + System.err.print("KungFuGuy now battles a "); ob.action(); } } @@ -34,14 +34,14 @@ public void interactWith(Obstacle ob) { class Puzzle implements Obstacle { @Override public void action() { - System.out.println("Puzzle"); + System.err.println("Puzzle"); } } class NastyWeapon implements Obstacle { @Override public void action() { - System.out.println("NastyWeapon"); + System.err.println("NastyWeapon"); } } diff --git a/patterns/chain/ChainOfResponsibility.java b/patterns/chain/ChainOfResponsibility.java index b733e71cc..bdcadf306 100644 --- a/patterns/chain/ChainOfResponsibility.java +++ b/patterns/chain/ChainOfResponsibility.java @@ -29,7 +29,7 @@ interface Algorithm { class FindMinima { public static Result leastSquares(List line) { - System.out.println("LeastSquares.algorithm"); + System.err.println("LeastSquares.algorithm"); boolean weSucceed = false; if(weSucceed) // Actual test/calculation here return new Result(Arrays.asList(1.1, 2.2)); @@ -37,7 +37,7 @@ public static Result leastSquares(List line) { return new Fail(); } public static Result perturbation(List line) { - System.out.println("Perturbation.algorithm"); + System.err.println("Perturbation.algorithm"); boolean weSucceed = false; if(weSucceed) // Actual test/calculation here return new Result(Arrays.asList(3.3, 4.4)); @@ -45,7 +45,7 @@ public static Result perturbation(List line) { return new Fail(); } public static Result bisection(List line) { - System.out.println("Bisection.algorithm"); + System.err.println("Bisection.algorithm"); boolean weSucceed = true; if(weSucceed) // Actual test/calculation here return new Result(Arrays.asList(5.5, 6.6)); @@ -77,9 +77,9 @@ public static void main(String[] args) { 3.0, 4.0, 5.0, 4.0); Result result = solver.minima(line); if(result.success) - System.out.println(result.line); + System.err.println(result.line); else - System.out.println("No algorithm found"); + System.err.println("No algorithm found"); } } /* Output: diff --git a/patterns/observer/ObservedFlower.java b/patterns/observer/ObservedFlower.java index 009da63e3..bb54482c9 100644 --- a/patterns/observer/ObservedFlower.java +++ b/patterns/observer/ObservedFlower.java @@ -53,12 +53,12 @@ class Bee { Bee(String nm) { name = nm; } // Observe openings: public Observer openObserver() { - return (ob, a) -> System.out.println( + return (ob, a) -> System.err.println( "Bee " + name + "'s breakfast time!"); } // Observe closings: public Observer closeObserver() { - return (ob, a) -> System.out.println( + return (ob, a) -> System.err.println( "Bee " + name + "'s bed time!"); } } @@ -68,12 +68,12 @@ class Hummingbird { private String name; Hummingbird(String nm) { name = nm; } public Observer openObserver() { - return (ob, a) -> System.out.println( + return (ob, a) -> System.err.println( "Hummingbird " + name + "'s breakfast time!"); } public Observer closeObserver() { - return (ob, a) -> System.out.println( + return (ob, a) -> System.err.println( "Hummingbird " + name + "'s bed time!"); } } diff --git a/patterns/recyclea/RecycleA.java b/patterns/recyclea/RecycleA.java index a73f39e7f..f04163fa8 100644 --- a/patterns/recyclea/RecycleA.java +++ b/patterns/recyclea/RecycleA.java @@ -20,14 +20,14 @@ static void sumValue(List bin) { bin.forEach( t -> { // Polymorphism in action: val += t.weight * t.value(); - System.out.println( + System.err.println( "weight of " + // Using RTTI to get type // information about the class: t.getClass().getSimpleName() + " = " + t.weight); }); - System.out.println("Total value = " + val); + System.err.println("Total value = " + val); } } diff --git a/patterns/shapes/Shape.java b/patterns/shapes/Shape.java index 12fdf3e77..09147687f 100644 --- a/patterns/shapes/Shape.java +++ b/patterns/shapes/Shape.java @@ -13,9 +13,9 @@ public String toString() { getClass().getSimpleName() + "[" + id + "]"; } public void draw() { - System.out.println(this + " draw"); + System.err.println(this + " draw"); } public void erase() { - System.out.println(this + " erase"); + System.err.println(this + " erase"); } } diff --git a/patterns/state/StateMachineDemo.java b/patterns/state/StateMachineDemo.java index 29f8a8761..aa7fbbe69 100644 --- a/patterns/state/StateMachineDemo.java +++ b/patterns/state/StateMachineDemo.java @@ -26,7 +26,7 @@ protected final void runAll() { class Wash implements State { @Override public void run() { - System.out.println("Washing"); + System.err.println("Washing"); new Nap(0.5); } } @@ -34,7 +34,7 @@ public void run() { class Spin implements State { @Override public void run() { - System.out.println("Spinning"); + System.err.println("Spinning"); new Nap(0.5); } } @@ -42,7 +42,7 @@ public void run() { class Rinse implements State { @Override public void run() { - System.out.println("Rinsing"); + System.err.println("Rinsing"); new Nap(0.5); } } diff --git a/patterns/strategy/StrategyPattern.java b/patterns/strategy/StrategyPattern.java index 52561b4b1..dbe9eb81a 100644 --- a/patterns/strategy/StrategyPattern.java +++ b/patterns/strategy/StrategyPattern.java @@ -53,9 +53,9 @@ public static void main(String[] args) { List line = Arrays.asList( 1.0, 2.0, 1.0, 2.0, -1.0, 3.0, 4.0, 5.0, 4.0 ); - System.out.println(solver.minima(line)); + System.err.println(solver.minima(line)); solver.changeAlgorithm(new Bisection()); - System.out.println(solver.minima(line)); + System.err.println(solver.minima(line)); } } /* Output: diff --git a/patterns/strategy/StrategyPattern2.java b/patterns/strategy/StrategyPattern2.java index 09465f3a5..cbca5544a 100644 --- a/patterns/strategy/StrategyPattern2.java +++ b/patterns/strategy/StrategyPattern2.java @@ -32,9 +32,9 @@ public static void main(String[] args) { List line = Arrays.asList( 1.0, 2.0, 1.0, 2.0, -1.0, 3.0, 4.0, 5.0, 4.0 ); - System.out.println(solver.minima(line)); + System.err.println(solver.minima(line)); solver.bisection(); - System.out.println(solver.minima(line)); + System.err.println(solver.minima(line)); } } /* Output: diff --git a/patterns/trash/Trash.java b/patterns/trash/Trash.java index 7d01de8c8..6a56d79a8 100644 --- a/patterns/trash/Trash.java +++ b/patterns/trash/Trash.java @@ -20,13 +20,13 @@ void sumValue(List bin) { val = 0.0f; bin.forEach( t -> { val += t.weight() * t.value(); - System.out.println("weight of " + + System.err.println("weight of " + // RTTI gets type information // about the class: t.getClass().getName() + " = " + t.weight()); }); - System.out.println("Total value = " + val); + System.err.println("Total value = " + val); } @Override public String toString() { @@ -80,7 +80,7 @@ public static T factory(Info info) { // The necessary Class was not in the list. Try to // load it, but it must be in your class path! try { - System.out.println("Loading " + info.id); + System.err.println("Loading " + info.id); trashTypes.add(Class.forName(info.id)); } catch(Exception e) { throw new TrashClassNotFoundException(e); diff --git a/patterns/trashvisitor/TrashVisitor.java b/patterns/trashvisitor/TrashVisitor.java index 8f9566236..8c1ed887d 100644 --- a/patterns/trashvisitor/TrashVisitor.java +++ b/patterns/trashvisitor/TrashVisitor.java @@ -15,7 +15,7 @@ class PriceVisitor implements Visitor { private double gSum; // Glass private double cSum; // Cardboard public static void show(String s) { - System.out.println(s); + System.err.println(s); } @Override public void visit(Aluminum al) { @@ -57,7 +57,7 @@ class WeightVisitor implements Visitor { private double gSum; // Glass private double cSum; // Cardboard public static void show(String s) { - System.out.println(s); + System.err.println(s); } @Override public void visit(Aluminum al) { diff --git a/patterns/visitor/BeeAndFlowers.java b/patterns/visitor/BeeAndFlowers.java index aa86ebfc5..8683e01e6 100644 --- a/patterns/visitor/BeeAndFlowers.java +++ b/patterns/visitor/BeeAndFlowers.java @@ -58,15 +58,15 @@ public void visit(Chrysanthemum c) { class Bee implements Visitor { @Override public void visit(Gladiolus g) { - System.out.println("Bee and Gladiolus"); + System.err.println("Bee and Gladiolus"); } @Override public void visit(Renuculus r) { - System.out.println("Bee and Renuculus"); + System.err.println("Bee and Renuculus"); } @Override public void visit(Chrysanthemum c) { - System.out.println("Bee and Chrysanthemum"); + System.err.println("Bee and Chrysanthemum"); } } @@ -91,7 +91,7 @@ public static void main(String[] args) { StringVal sval = new StringVal(); flowers.forEach(f -> { f.accept(sval); - System.out.println(sval); + System.err.println(sval); }); // Perform "Bee" operation on all Flowers: Bee bee = new Bee(); diff --git a/polymorphism/CovariantReturn.java b/polymorphism/CovariantReturn.java index e88fe5908..9e7591b2b 100644 --- a/polymorphism/CovariantReturn.java +++ b/polymorphism/CovariantReturn.java @@ -26,10 +26,10 @@ public class CovariantReturn { public static void main(String[] args) { Mill m = new Mill(); Grain g = m.process(); - System.out.println(g); + System.err.println(g); m = new WheatMill(); g = m.process(); - System.out.println(g); + System.err.println(g); } } /* Output: diff --git a/polymorphism/FieldAccess.java b/polymorphism/FieldAccess.java index 95e47c5e2..4ece99e1b 100644 --- a/polymorphism/FieldAccess.java +++ b/polymorphism/FieldAccess.java @@ -19,10 +19,10 @@ class Sub extends Super { public class FieldAccess { public static void main(String[] args) { Super sup = new Sub(); // Upcast - System.out.println("sup.field = " + sup.field + + System.err.println("sup.field = " + sup.field + ", sup.getField() = " + sup.getField()); Sub sub = new Sub(); - System.out.println("sub.field = " + + System.err.println("sub.field = " + sub.field + ", sub.getField() = " + sub.getField() + ", sub.getSuperField() = " + diff --git a/polymorphism/Frog.java b/polymorphism/Frog.java index 9226910d5..4c384839c 100644 --- a/polymorphism/Frog.java +++ b/polymorphism/Frog.java @@ -4,16 +4,15 @@ // Visit http://OnJava8.com for more book information. // Cleanup and inheritance // {java polymorphism.Frog} -package polymorphism; class Characteristic { private String s; Characteristic(String s) { this.s = s; - System.out.println("Creating Characteristic " + s); + System.err.println("Creating Characteristic " + s); } protected void dispose() { - System.out.println("disposing Characteristic " + s); + System.err.println("disposing Characteristic " + s); } } @@ -21,10 +20,10 @@ class Description { private String s; Description(String s) { this.s = s; - System.out.println("Creating Description " + s); + System.err.println("Creating Description " + s); } protected void dispose() { - System.out.println("disposing Description " + s); + System.err.println("disposing Description " + s); } } @@ -34,10 +33,10 @@ class LivingCreature { private Description t = new Description("Basic Living Creature"); LivingCreature() { - System.out.println("LivingCreature()"); + System.err.println("LivingCreature()"); } protected void dispose() { - System.out.println("LivingCreature dispose"); + System.err.println("LivingCreature dispose"); t.dispose(); p.dispose(); } @@ -48,10 +47,10 @@ class Animal extends LivingCreature { new Characteristic("has heart"); private Description t = new Description("Animal not Vegetable"); - Animal() { System.out.println("Animal()"); } + Animal() { System.err.println("Animal()"); } @Override protected void dispose() { - System.out.println("Animal dispose"); + System.err.println("Animal dispose"); t.dispose(); p.dispose(); super.dispose(); @@ -64,11 +63,11 @@ class Amphibian extends Animal { private Description t = new Description("Both water and land"); Amphibian() { - System.out.println("Amphibian()"); + System.err.println("Amphibian()"); } @Override protected void dispose() { - System.out.println("Amphibian dispose"); + System.err.println("Amphibian dispose"); t.dispose(); p.dispose(); super.dispose(); @@ -79,17 +78,17 @@ public class Frog extends Amphibian { private Characteristic p = new Characteristic("Croaks"); private Description t = new Description("Eats Bugs"); - public Frog() { System.out.println("Frog()"); } + public Frog() { System.err.println("Frog()"); } @Override protected void dispose() { - System.out.println("Frog dispose"); + System.err.println("Frog dispose"); t.dispose(); p.dispose(); super.dispose(); } public static void main(String[] args) { Frog frog = new Frog(); - System.out.println("Bye!"); + System.err.println("Bye!"); frog.dispose(); } } @@ -120,3 +119,12 @@ public static void main(String[] args) { disposing Description Basic Living Creature disposing Characteristic is alive */ +/** + * self-note: + * + * 对象销毁的顺序应该与初始化的顺序相反,以防一个对象依赖另一个对象。 + * 属性销毁的顺序与声明的顺序相反(因为属性是按照声明顺序初始化的)。 + * 首先进行派生类的清理工作,然后才是基类的清理。 + * 这是因为派生类的清理可能调用基类的一些方法,所以基类组件这时得存活,不能过早地被销毁。 + * 尽管通常不必进行清理工作,但万一需要时,就得谨慎小心地执行。 + */ diff --git a/polymorphism/PolyConstructors.java b/polymorphism/PolyConstructors.java index 3a99f08b2..fe257c5d2 100644 --- a/polymorphism/PolyConstructors.java +++ b/polymorphism/PolyConstructors.java @@ -6,11 +6,11 @@ // don't produce what you might expect class Glyph { - void draw() { System.out.println("Glyph.draw()"); } + void draw() { System.err.println("Glyph.draw()"); } Glyph() { - System.out.println("Glyph() before draw()"); + System.err.println("Glyph() before draw()"); draw(); - System.out.println("Glyph() after draw()"); + System.err.println("Glyph() after draw()"); } } @@ -18,12 +18,12 @@ class RoundGlyph extends Glyph { private int radius = 1; RoundGlyph(int r) { radius = r; - System.out.println( + System.err.println( "RoundGlyph.RoundGlyph(), radius = " + radius); } @Override void draw() { - System.out.println( + System.err.println( "RoundGlyph.draw(), radius = " + radius); } } @@ -38,4 +38,38 @@ public static void main(String[] args) { RoundGlyph.draw(), radius = 0 Glyph() after draw() RoundGlyph.RoundGlyph(), radius = 5 + +self-note: +父类--静态变量 +父类--静态初始化块 +子类--静态变量 +子类--静态初始化块 +************* main start *************** +父类--变量 +父类--初始化块 +父类--构造器 当 Glyph 构造器调用了 draw() 时,radius 的值不是默认初始值 1 而是 0。 +子类--变量 +子类--初始化块 +子类--构造器 +************* 第二次创建不会加载父类 ************* +父类--变量 +父类--初始化块 +父类--构造器 +子类--变量 +子类--初始化块 +子类--构造器 +************* main end *************** + + +初始化的实际过程是: + + 1.在所有事发生前,分配给对象的存储空间会被初始化为二进制 0。 + 2.如前所述调用基类构造器。此时调用重写后的 draw() 方法(是的,在调用 RoundGraph 构造器之前调用), + 由步骤 1 可知,radius 的值为 0。 + 3.按声明顺序初始化成员。 + 4.最终调用派生类的构造器。 + + 编写构造器有一条良好规范: 在基类的构造器中能安全调用的只有基类的 final 方法(这也适用于可被看作是 final 的 private 方法)。 + 这些方法不能被重写,因此不会产生意想不到的结果。 + ( 你可能无法永远遵循这条规范,但应该朝着它努力。) */ diff --git a/polymorphism/PrivateOverride.java b/polymorphism/PrivateOverride.java index 9873e03da..7916e0aa9 100644 --- a/polymorphism/PrivateOverride.java +++ b/polymorphism/PrivateOverride.java @@ -8,7 +8,7 @@ public class PrivateOverride { private void f() { - System.out.println("private f()"); + System.err.println("private f()"); } public static void main(String[] args) { PrivateOverride po = new Derived(); @@ -17,7 +17,7 @@ public static void main(String[] args) { } class Derived extends PrivateOverride { - public void f() { System.out.println("public f()"); } + public void f() { System.err.println("public f()"); } } /* Output: private f() diff --git a/polymorphism/PrivateOverride2.java b/polymorphism/PrivateOverride2.java index 664672bc4..d75b0a0b9 100644 --- a/polymorphism/PrivateOverride2.java +++ b/polymorphism/PrivateOverride2.java @@ -8,7 +8,7 @@ public class PrivateOverride2 { private void f() { - System.out.println("private f()"); + System.err.println("private f()"); } public static void main(String[] args) { PrivateOverride2 po = new Derived2(); @@ -18,5 +18,5 @@ public static void main(String[] args) { class Derived2 extends PrivateOverride2 { @Override - public void f() { System.out.println("public f()"); } + public void f() { System.err.println("public f()"); } } diff --git a/polymorphism/RTTI.java b/polymorphism/RTTI.java index 39c9029b9..0f725363e 100644 --- a/polymorphism/RTTI.java +++ b/polymorphism/RTTI.java @@ -31,7 +31,7 @@ public static void main(String[] args) { // Compile time: method not found in Useful: //- x[1].u(); ((MoreUseful)x[1]).u(); // Downcast/RTTI - ((MoreUseful)x[0]).u(); // Exception thrown +// ((MoreUseful)x[0]).u(); // Exception thrown } } /* Output: @@ -39,5 +39,5 @@ public static void main(String[] args) { Exception in thread "main" java.lang.ClassCastException: Useful cannot be cast to MoreUseful - at RTTI.main(RTTI.java:31) + at RTTI.main(RTTI.java:34) */ diff --git a/polymorphism/ReferenceCounting.java b/polymorphism/ReferenceCounting.java index b378117f1..ff7aad338 100644 --- a/polymorphism/ReferenceCounting.java +++ b/polymorphism/ReferenceCounting.java @@ -9,12 +9,12 @@ class Shared { private static long counter = 0; private final long id = counter++; Shared() { - System.out.println("Creating " + this); + System.err.println("Creating " + this); } public void addRef() { refcount++; } protected void dispose() { if(--refcount == 0) - System.out.println("Disposing " + this); + System.err.println("Disposing " + this); } @Override public String toString() { @@ -24,15 +24,20 @@ public String toString() { class Composing { private Shared shared; + /** + * self-note: 一旦某个成员对象(shared)被其它一个或多个对象共享时,问题就变得复杂了,不能只是简单地调用 dispose()。 + * 这里,也许就必须使用引用计数来跟踪仍然访问着共享对象的对象数量 + * 使用这种技巧需要加倍细心,但是如果正在共享的对象需要被清理,你没有太多选择。 + */ private static long counter = 0; private final long id = counter++; Composing(Shared shared) { - System.out.println("Creating " + this); + System.err.println("Creating " + this); this.shared = shared; this.shared.addRef(); } protected void dispose() { - System.out.println("disposing " + this); + System.err.println("disposing " + this); shared.dispose(); } @Override diff --git a/polymorphism/Sandwich.java b/polymorphism/Sandwich.java index 97f80d53e..49ae73559 100644 --- a/polymorphism/Sandwich.java +++ b/polymorphism/Sandwich.java @@ -7,28 +7,28 @@ package polymorphism; class Meal { - Meal() { System.out.println("Meal()"); } + Meal() { System.err.println("Meal()"); } } class Bread { - Bread() { System.out.println("Bread()"); } + Bread() { System.err.println("Bread()"); } } class Cheese { - Cheese() { System.out.println("Cheese()"); } + Cheese() { System.err.println("Cheese()"); } } class Lettuce { - Lettuce() { System.out.println("Lettuce()"); } + Lettuce() { System.err.println("Lettuce()"); } } class Lunch extends Meal { - Lunch() { System.out.println("Lunch()"); } + Lunch() { System.err.println("Lunch()"); } } class PortableLunch extends Lunch { PortableLunch() { - System.out.println("PortableLunch()"); + System.err.println("PortableLunch()"); } } @@ -37,7 +37,7 @@ public class Sandwich extends PortableLunch { private Cheese c = new Cheese(); private Lettuce l = new Lettuce(); public Sandwich() { - System.out.println("Sandwich()"); + System.err.println("Sandwich()"); } public static void main(String[] args) { new Sandwich(); diff --git a/polymorphism/Shapes.java b/polymorphism/Shapes.java index 4d051e707..f41ea9a1a 100644 --- a/polymorphism/Shapes.java +++ b/polymorphism/Shapes.java @@ -3,7 +3,8 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Polymorphism in Java -import polymorphism.shape.*; + +import shape.*; public class Shapes { public static void main(String[] args) { @@ -23,4 +24,9 @@ public static void main(String[] args) { Square.draw() Triangle.draw() Circle.draw() + + +self-note: Java 中除了 static 和 final 方法(private 方法也是隐式的 final)外,其他所有方法都是后期绑定。 +这意味着通常情况下,我们不需要判断后期绑定是否会发生——它自动发生。 + */ diff --git a/polymorphism/StaticPolymorphism.java b/polymorphism/StaticPolymorphism.java index 1ebe733b2..be9fc52ca 100644 --- a/polymorphism/StaticPolymorphism.java +++ b/polymorphism/StaticPolymorphism.java @@ -26,11 +26,13 @@ public String dynamicGet() { public class StaticPolymorphism { public static void main(String[] args) { StaticSuper sup = new StaticSub(); // Upcast - System.out.println(StaticSuper.staticGet()); - System.out.println(sup.dynamicGet()); + System.err.println(StaticSuper.staticGet());//self-note: 如果一个方法是静态(static)的,它的行为就不具有多态性:只与类关联 + System.err.println(sup.dynamicGet()); } } /* Output: Base staticGet() Derived dynamicGet() + + */ diff --git a/polymorphism/SubClass.java b/polymorphism/SubClass.java new file mode 100644 index 000000000..e822127ba --- /dev/null +++ b/polymorphism/SubClass.java @@ -0,0 +1,60 @@ +class Parent { + // 静态变量 + public static String p_StaticField = "父类--静态变量"; +// 变量(其实这用对象更好能体同这一点,如专门写一个类的实例) + + //如果这个变量放在初始化块的后面,是会报错的,因为你根本没有被初始化 + public String p_Field = "父类--变量"; + + // 静态初始化块 + static { + System.out.println(p_StaticField); + System.out.println("父类--静态初始化块"); + } + + // 初始化块 + { + System.out.println(p_Field); + System.out.println("父类--初始化块"); + } + + // 构造器 + public Parent() { + System.out.println("父类--构造器"); + } +} + +public class SubClass extends Parent { + // 静态变量 + public static String s_StaticField = "子类--静态变量"; + // 变量 + public String s_Field = "子类--变量"; + + // 静态初始化块 + static { + System.out.println(s_StaticField); + System.out.println("子类--静态初始化块"); + } + + // 初始化块 + { + System.out.println(s_Field); + System.out.println("子类--初始化块"); + } + + // 构造器 + public SubClass() { +//super(); + System.out.println("子类--构造器"); + } + + // 程序入口 + public static void main(String[] args) { + System.out.println("************* main start ***************"); + new SubClass(); + System.out.println("************* 第二次创建不会加载父类 *************"); + new SubClass(); + System.out.println("************* main end ***************"); + + } +} diff --git a/polymorphism/Transmogrify.java b/polymorphism/Transmogrify.java index 09877d530..2100534bd 100644 --- a/polymorphism/Transmogrify.java +++ b/polymorphism/Transmogrify.java @@ -12,14 +12,14 @@ public void act() {} class HappyActor extends Actor { @Override public void act() { - System.out.println("HappyActor"); + System.err.println("HappyActor"); } } class SadActor extends Actor { @Override public void act() { - System.out.println("SadActor"); + System.err.println("SadActor"); } } diff --git a/polymorphism/music/Instrument.java b/polymorphism/music/Instrument.java index fb6c77e37..3b5c06930 100644 --- a/polymorphism/music/Instrument.java +++ b/polymorphism/music/Instrument.java @@ -2,10 +2,10 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -package polymorphism.music; +package music; class Instrument { - public void play(Note n) { - System.out.println("Instrument.play()"); + public void play(polymorphism.music.Note n) { + System.err.println("Instrument.play()"); } } diff --git a/polymorphism/music/Music.java b/polymorphism/music/Music.java index 8e903ec0a..f08f312bd 100644 --- a/polymorphism/music/Music.java +++ b/polymorphism/music/Music.java @@ -4,12 +4,13 @@ // Visit http://OnJava8.com for more book information. // Inheritance & upcasting // {java polymorphism.music.Music} -package polymorphism.music; +package music; + public class Music { public static void tune(Instrument i) { // ... - i.play(Note.MIDDLE_C); + i.play(polymorphism.music.Note.MIDDLE_C); } public static void main(String[] args) { Wind flute = new Wind(); diff --git a/polymorphism/music/Music2.java b/polymorphism/music/Music2.java index a5bff54be..c2679638c 100644 --- a/polymorphism/music/Music2.java +++ b/polymorphism/music/Music2.java @@ -4,31 +4,32 @@ // Visit http://OnJava8.com for more book information. // Overloading instead of upcasting // {java polymorphism.music.Music2} -package polymorphism.music; +package music; + class Stringed extends Instrument { @Override - public void play(Note n) { - System.out.println("Stringed.play() " + n); + public void play(polymorphism.music.Note n) { + System.err.println("Stringed.play() " + n); } } class Brass extends Instrument { @Override - public void play(Note n) { - System.out.println("Brass.play() " + n); + public void play(polymorphism.music.Note n) { + System.err.println("Brass.play() " + n); } } public class Music2 { public static void tune(Wind i) { - i.play(Note.MIDDLE_C); + i.play(polymorphism.music.Note.MIDDLE_C); } public static void tune(Stringed i) { - i.play(Note.MIDDLE_C); + i.play(polymorphism.music.Note.MIDDLE_C); } public static void tune(Brass i) { - i.play(Note.MIDDLE_C); + i.play(polymorphism.music.Note.MIDDLE_C); } public static void main(String[] args) { Wind flute = new Wind(); diff --git a/polymorphism/music/Wind.java b/polymorphism/music/Wind.java index c38ac4970..2696db5b8 100644 --- a/polymorphism/music/Wind.java +++ b/polymorphism/music/Wind.java @@ -2,14 +2,15 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -package polymorphism.music; +package music; + // Wind objects are instruments // because they have the same interface: public class Wind extends Instrument { // Redefine interface method: @Override - public void play(Note n) { - System.out.println("Wind.play() " + n); + public void play(polymorphism.music.Note n) { + System.err.println("Wind.play() " + n); } } diff --git a/polymorphism/music3/Music3.java b/polymorphism/music3/Music3.java index da3eb3647..c0af57a2f 100644 --- a/polymorphism/music3/Music3.java +++ b/polymorphism/music3/Music3.java @@ -4,73 +4,73 @@ // Visit http://OnJava8.com for more book information. // An extensible program // {java polymorphism.music3.Music3} -package polymorphism.music3; +package music3; import polymorphism.music.Note; class Instrument { void play(Note n) { - System.out.println("Instrument.play() " + n); + System.err.println("Instrument.play() " + n); } String what() { return "Instrument"; } void adjust() { - System.out.println("Adjusting Instrument"); + System.err.println("Adjusting Instrument"); } } class Wind extends Instrument { @Override void play(Note n) { - System.out.println("Wind.play() " + n); + System.err.println("Wind.play() " + n); } @Override String what() { return "Wind"; } @Override void adjust() { - System.out.println("Adjusting Wind"); + System.err.println("Adjusting Wind"); } } class Percussion extends Instrument { @Override void play(Note n) { - System.out.println("Percussion.play() " + n); + System.err.println("Percussion.play() " + n); } @Override String what() { return "Percussion"; } @Override void adjust() { - System.out.println("Adjusting Percussion"); + System.err.println("Adjusting Percussion"); } } class Stringed extends Instrument { @Override void play(Note n) { - System.out.println("Stringed.play() " + n); + System.err.println("Stringed.play() " + n); } @Override String what() { return "Stringed"; } @Override void adjust() { - System.out.println("Adjusting Stringed"); + System.err.println("Adjusting Stringed"); } } class Brass extends Wind { @Override void play(Note n) { - System.out.println("Brass.play() " + n); + System.err.println("Brass.play() " + n); } @Override void adjust() { - System.out.println("Adjusting Brass"); + System.err.println("Adjusting Brass"); } } class Woodwind extends Wind { @Override void play(Note n) { - System.out.println("Woodwind.play() " + n); + System.err.println("Woodwind.play() " + n); } @Override String what() { return "Woodwind"; } diff --git a/polymorphism/shape/Circle.java b/polymorphism/shape/Circle.java index fc8579506..7c05ecc36 100644 --- a/polymorphism/shape/Circle.java +++ b/polymorphism/shape/Circle.java @@ -2,15 +2,15 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -package polymorphism.shape; +package shape; public class Circle extends Shape { @Override public void draw() { - System.out.println("Circle.draw()"); + System.err.println("Circle.draw()"); } @Override public void erase() { - System.out.println("Circle.erase()"); + System.err.println("Circle.erase()"); } } diff --git a/polymorphism/shape/RandomShapes.java b/polymorphism/shape/RandomShapes.java index c1419f4e1..f1dffe645 100644 --- a/polymorphism/shape/RandomShapes.java +++ b/polymorphism/shape/RandomShapes.java @@ -3,21 +3,21 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // A "factory" that randomly creates shapes -package polymorphism.shape; +package shape; import java.util.*; public class RandomShapes { private Random rand = new Random(47); - public Shape get() { + public shape.Shape get() { switch(rand.nextInt(3)) { default: - case 0: return new Circle(); - case 1: return new Square(); - case 2: return new Triangle(); + case 0: return new shape.Circle(); + case 1: return new shape.Square(); + case 2: return new shape.Triangle(); } } - public Shape[] array(int sz) { - Shape[] shapes = new Shape[sz]; + public Shape[] array(int sz) { + Shape[] shapes = new Shape[sz]; // Fill up the array with shapes: for(int i = 0; i < shapes.length; i++) shapes[i] = get(); diff --git a/polymorphism/shape/Shape.java b/polymorphism/shape/Shape.java index 4be93c866..a3f2de001 100644 --- a/polymorphism/shape/Shape.java +++ b/polymorphism/shape/Shape.java @@ -2,7 +2,7 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -package polymorphism.shape; +package shape; public class Shape { public void draw() {} diff --git a/polymorphism/shape/Square.java b/polymorphism/shape/Square.java index 4938335b3..f1bae2388 100644 --- a/polymorphism/shape/Square.java +++ b/polymorphism/shape/Square.java @@ -2,15 +2,15 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -package polymorphism.shape; +package shape; public class Square extends Shape { @Override public void draw() { - System.out.println("Square.draw()"); + System.err.println("Square.draw()"); } @Override public void erase() { - System.out.println("Square.erase()"); + System.err.println("Square.erase()"); } } diff --git a/polymorphism/shape/Triangle.java b/polymorphism/shape/Triangle.java index db7394a3c..e87d8ba4e 100644 --- a/polymorphism/shape/Triangle.java +++ b/polymorphism/shape/Triangle.java @@ -2,15 +2,15 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -package polymorphism.shape; +package shape; public class Triangle extends Shape { @Override public void draw() { - System.out.println("Triangle.draw()"); + System.err.println("Triangle.draw()"); } @Override public void erase() { - System.out.println("Triangle.erase()"); + System.err.println("Triangle.erase()"); } } diff --git a/references/AddingClone.java b/references/AddingClone.java index 4f03cf06d..436ff59ce 100644 --- a/references/AddingClone.java +++ b/references/AddingClone.java @@ -37,7 +37,7 @@ public static void main(String[] args) { Int2 x = new Int2(10); Int2 x2 = x.clone(); x2.increment(); - System.out.println( + System.err.println( "x = " + x + ", x2 = " + x2); // Anything inherited is also cloneable: Int3 x3 = new Int3(7); @@ -46,7 +46,7 @@ public static void main(String[] args) { .mapToObj(Int2::new) .collect(Collectors .toCollection(ArrayList::new)); - System.out.println("v: " + v); + System.err.println("v: " + v); ArrayList v2 = (ArrayList)v.clone(); // Now clone each element: @@ -54,9 +54,9 @@ public static void main(String[] args) { .forEach(i -> v2.set(i, v.get(i).clone())); // Increment all v2's elements: v2.forEach(Int2::increment); - System.out.println("v2: " + v2); + System.err.println("v2: " + v2); // See if it changed v's elements: - System.out.println("v: " + v); + System.err.println("v: " + v); } } /* Output: diff --git a/references/Alias1.java b/references/Alias1.java index 1af594ec4..c3520b810 100644 --- a/references/Alias1.java +++ b/references/Alias1.java @@ -10,12 +10,12 @@ public class Alias1 { public static void main(String[] args) { Alias1 x = new Alias1(7); Alias1 y = x; // Assign the reference (1) - System.out.println("x: " + x.i); - System.out.println("y: " + y.i); - System.out.println("Incrementing x"); + System.err.println("x: " + x.i); + System.err.println("y: " + y.i); + System.err.println("Incrementing x"); x.i++; // [2] - System.out.println("x: " + x.i); - System.out.println("y: " + y.i); + System.err.println("x: " + x.i); + System.err.println("y: " + y.i); } } /* Output: diff --git a/references/Alias2.java b/references/Alias2.java index aa37e1a23..f7d5ff174 100644 --- a/references/Alias2.java +++ b/references/Alias2.java @@ -12,10 +12,10 @@ public static void f(Alias2 reference) { } public static void main(String[] args) { Alias2 x = new Alias2(7); - System.out.println("x: " + x.i); - System.out.println("Calling f(x)"); + System.err.println("x: " + x.i); + System.err.println("Calling f(x)"); f(x); - System.out.println("x: " + x.i); + System.err.println("x: " + x.i); } } /* Output: diff --git a/references/CheckCloneable.java b/references/CheckCloneable.java index 137937a94..ebcee0c94 100644 --- a/references/CheckCloneable.java +++ b/references/CheckCloneable.java @@ -61,18 +61,18 @@ public class CheckCloneable { public static Ordinary tryToClone(Ordinary ord) { String id = ord.getClass().getName(); - System.out.println("Attempting " + id); + System.err.println("Attempting " + id); Ordinary x = null; if(ord instanceof Cloneable) { try { x = (Ordinary)((IsCloneable)ord).clone(); - System.out.println("Cloned " + id); + System.err.println("Cloned " + id); } catch(CloneNotSupportedException e) { - System.out.println( + System.err.println( "Could not clone " + id); } } else { - System.out.println("Doesn't implement Cloneable"); + System.err.println("Doesn't implement Cloneable"); } return x; } diff --git a/references/CloneArrayList.java b/references/CloneArrayList.java index 601673c2c..5b7c3afa9 100644 --- a/references/CloneArrayList.java +++ b/references/CloneArrayList.java @@ -23,13 +23,13 @@ public static void main(String[] args) { .mapToObj(Int::new) .collect(Collectors .toCollection(ArrayList::new)); - System.out.println("v: " + v); + System.err.println("v: " + v); @SuppressWarnings("unchecked") ArrayList v2 = (ArrayList)v.clone(); // Increment all v2's elements: v2.forEach(Int::increment); // See if it changed v's elements: - System.out.println("v: " + v); + System.err.println("v: " + v); } } /* Output: diff --git a/references/Compete.java b/references/Compete.java index 9e77f3a7f..ab9e7b06d 100644 --- a/references/Compete.java +++ b/references/Compete.java @@ -69,7 +69,7 @@ public class Compete { c[i] = (Thing2)in.readObject(); } } - System.out.println( + System.err.println( "Duplication via serialization: " + timer.duration() + " Milliseconds"); @@ -78,7 +78,7 @@ public class Compete { Thing4[] d = new Thing4[SIZE]; for(int i = 0; i < SIZE; i++) d[i] = b[i].clone(); - System.out.println( + System.err.println( "Duplication via cloning: " + timer.duration() + " Milliseconds"); } diff --git a/references/CopyConstructor.java b/references/CopyConstructor.java index 2617f48b0..45de89281 100644 --- a/references/CopyConstructor.java +++ b/references/CopyConstructor.java @@ -113,12 +113,12 @@ public class CopyConstructor { public static void ripen(Tomato t) { // Use the "copy constructor": t = new Tomato(t); // [1] - System.out.println("In ripen, t is a " + + System.err.println("In ripen, t is a " + t.getClass().getName()); } public static void slice(Fruit f) { f = new Fruit(f); // [2] Hmmm... will this work? - System.out.println("In slice, f is a " + + System.err.println("In slice, f is a " + f.getClass().getName()); } @SuppressWarnings("unchecked") @@ -130,7 +130,7 @@ public static void ripen2(Tomato t) { c.getConstructor(new Class[] { c }); Object obj = ct.newInstance(new Object[] { t }); - System.out.println("In ripen2, t is a " + + System.err.println("In ripen2, t is a " + obj.getClass().getName()); } catch(NoSuchMethodException | SecurityException | @@ -138,7 +138,7 @@ public static void ripen2(Tomato t) { IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { - System.out.println(e); + System.err.println(e); } } @SuppressWarnings("unchecked") @@ -149,7 +149,7 @@ public static void slice2(Fruit f) { c.getConstructor(new Class[] { c }); Object obj = ct.newInstance(new Object[] { f }); - System.out.println("In slice2, f is a " + + System.err.println("In slice2, f is a " + obj.getClass().getName()); } catch(NoSuchMethodException | SecurityException | @@ -157,7 +157,7 @@ public static void slice2(Fruit f) { IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { - System.out.println(e); + System.err.println(e); } } public static void main(String[] args) { diff --git a/references/Immutable1.java b/references/Immutable1.java index 55ac1f6aa..66ebb3abd 100644 --- a/references/Immutable1.java +++ b/references/Immutable1.java @@ -16,14 +16,14 @@ public Immutable1 multiply(int multiplier) { } public static void f(Immutable1 i1) { Immutable1 quad = i1.multiply(4); - System.out.println("i1 = " + i1.read()); - System.out.println("quad = " + quad.read()); + System.err.println("i1 = " + i1.read()); + System.err.println("quad = " + quad.read()); } public static void main(String[] args) { Immutable1 x = new Immutable1(47); - System.out.println("x = " + x.read()); + System.err.println("x = " + x.read()); f(x); - System.out.println("x = " + x.read()); + System.err.println("x = " + x.read()); } } /* Output: diff --git a/references/Immutable2.java b/references/Immutable2.java index a565f86a6..8a1e4f7c4 100644 --- a/references/Immutable2.java +++ b/references/Immutable2.java @@ -59,9 +59,9 @@ public static void main(String[] args) { Immutable2 i2 = new Immutable2(47); Immutable2 r1 = modify1(i2); Immutable2 r2 = modify2(i2); - System.out.println("i2 = " + i2.read()); - System.out.println("r1 = " + r1.read()); - System.out.println("r2 = " + r2.read()); + System.err.println("i2 = " + i2.read()); + System.err.println("r1 = " + r1.read()); + System.err.println("r2 = " + r2.read()); } } /* Output: diff --git a/references/ImmutableInteger.java b/references/ImmutableInteger.java index 906aa7ef0..5bf2a4a5f 100644 --- a/references/ImmutableInteger.java +++ b/references/ImmutableInteger.java @@ -12,7 +12,7 @@ public static void main(String[] args) { List v = IntStream.range(0, 10) .mapToObj(Integer::new) .collect(Collectors.toList()); - System.out.println(v); + System.err.println(v); // But how do you change the int // inside the Integer? } diff --git a/references/ImmutableStrings.java b/references/ImmutableStrings.java index ad954e3f3..a474faa1a 100644 --- a/references/ImmutableStrings.java +++ b/references/ImmutableStrings.java @@ -9,14 +9,14 @@ public static void main(String[] args) { String foo = "foo"; String s = "abc" + foo + "def" + Integer.toString(47); - System.out.println(s); + System.err.println(s); // The "equivalent" using StringBuilder: StringBuilder sb = new StringBuilder("abc"); // Creates String sb.append(foo); sb.append("def"); // Creates String sb.append(Integer.toString(47)); - System.out.println(sb); + System.err.println(sb); } } /* Output: diff --git a/references/LocalCopy.java b/references/LocalCopy.java index 9c01c09e8..9f7eeb418 100644 --- a/references/LocalCopy.java +++ b/references/LocalCopy.java @@ -39,11 +39,11 @@ public static void main(String[] args) { Duplo a = new Duplo(11); Duplo b = g(a); // Reference equivalence, not object equivalence: - System.out.println("a == b: " + (a == b) + + System.err.println("a == b: " + (a == b) + "\na = " + a + "\nb = " + b); Duplo c = new Duplo(47); Duplo d = f(c); - System.out.println("c == d: " + (c == d) + + System.err.println("c == d: " + (c == d) + "\nc = " + c + "\nd = " + d); } } diff --git a/references/MutableInteger.java b/references/MutableInteger.java index dfe0cc7b7..146d367c7 100644 --- a/references/MutableInteger.java +++ b/references/MutableInteger.java @@ -23,9 +23,9 @@ public static void main(String[] args) { List v = IntStream.range(0, 10) .mapToObj(IntValue::new) .collect(Collectors.toList()); - System.out.println(v); + System.err.println(v); v.forEach(IntValue::increment); - System.out.println(v); + System.err.println(v); } } /* Output: diff --git a/references/PassReferences.java b/references/PassReferences.java index 2a1630087..57c12664c 100644 --- a/references/PassReferences.java +++ b/references/PassReferences.java @@ -5,11 +5,11 @@ public class PassReferences { public static void f(PassReferences h) { - System.out.println("h inside f(): " + h); + System.err.println("h inside f(): " + h); } public static void main(String[] args) { PassReferences p = new PassReferences(); - System.out.println("p inside main(): " + p); + System.err.println("p inside main(): " + p); f(p); } } diff --git a/references/SimplerMutableInteger.java b/references/SimplerMutableInteger.java index 191068ca6..9a9e6f57e 100644 --- a/references/SimplerMutableInteger.java +++ b/references/SimplerMutableInteger.java @@ -17,11 +17,11 @@ public static void main(String[] args) { .mapToObj(IntValue2::new) .collect(Collectors.toList()); v.forEach(iv2 -> - System.out.print(iv2.n + " ")); - System.out.println(); + System.err.print(iv2.n + " ")); + System.err.println(); v.forEach(iv2 -> iv2.n += 1); v.forEach(iv2 -> - System.out.print(iv2.n + " ")); + System.err.print(iv2.n + " ")); } } /* Output: diff --git a/references/Snake.java b/references/Snake.java index 004f7e765..b51f572b9 100644 --- a/references/Snake.java +++ b/references/Snake.java @@ -36,11 +36,11 @@ public Snake clone() { } public static void main(String[] args) { Snake s = new Snake(5, 'a'); - System.out.println("s = " + s); + System.err.println("s = " + s); Snake s2 = s.clone(); - System.out.println("s2 = " + s2); + System.err.println("s2 = " + s2); s.increment(); - System.out.println( + System.err.println( "after s.increment, s2 = " + s2); } } diff --git a/references/Stringer.java b/references/Stringer.java index 72663bb57..b7b531b63 100644 --- a/references/Stringer.java +++ b/references/Stringer.java @@ -9,10 +9,10 @@ public static String upcase(String s) { } public static void main(String[] args) { String q = new String("howdy"); - System.out.println(q); // howdy + System.err.println(q); // howdy String qq = upcase(q); - System.out.println(qq); // HOWDY - System.out.println(q); // howdy + System.err.println(qq); // HOWDY + System.err.println(q); // howdy } } /* Output: diff --git a/reuse/Bath.java b/reuse/Bath.java index 38e5e8195..5aa2f2c66 100644 --- a/reuse/Bath.java +++ b/reuse/Bath.java @@ -7,7 +7,7 @@ class Soap { private String s; Soap() { - System.out.println("Soap()"); + System.err.println("Soap()"); s = "Constructed"; } @Override @@ -23,7 +23,7 @@ public class Bath { private int i; private float toy; public Bath() { - System.out.println("Inside Bath()"); + System.err.println("Inside Bath()"); s3 = "Joy"; toy = 3.14f; castille = new Soap(); @@ -45,7 +45,7 @@ public String toString() { } public static void main(String[] args) { Bath b = new Bath(); - System.out.println(b); + System.err.println(b); } } /* Output: diff --git a/reuse/Beetle.java b/reuse/Beetle.java index 0a41bc176..e96812587 100644 --- a/reuse/Beetle.java +++ b/reuse/Beetle.java @@ -8,28 +8,40 @@ class Insect { private int i = 9; protected int j; Insect() { - System.out.println("i = " + i + ", j = " + j); + System.err.println("i = " + i + ", j = " + j); j = 39; } private static int x1 = printInit("static Insect.x1 initialized"); static int printInit(String s) { - System.out.println(s); + System.err.println(s); return 47; } } +class Insect2 { + protected int j; -public class Beetle extends Insect { - private int k = printInit("Beetle.k initialized"); - public Beetle() { - System.out.println("k = " + k); - System.out.println("j = " + j); + static{ + System.err.println("基类都会被加载!!!"); } - private static int x2 = - printInit("static Beetle.x2 initialized"); + static int printInit(String s) { + System.err.println(s); + return 47; + } +} +public class Beetle extends Insect2 { +// private int k = printInit("Beetle.k initialized"); +// public Beetle() { +// System.err.println("k = " + k); +// System.err.println("j = " + j); +// } +// private static int x2 = +// printInit("static Beetle.x2 initialized"); public static void main(String[] args) { - System.out.println("Beetle constructor"); - Beetle b = new Beetle(); + System.err.println("Beetle constructor"); +// Beetle b = new Beetle(); +// self-note: 不论是否创建了基类的对象,基类Insect2都会被加载。 +// 如果基类还存在自身的基类,那么基类的基类也将被加载。除此之外要用到(Insect)才会加载 } } /* Output: diff --git a/reuse/CADSystem.java b/reuse/CADSystem.java index 55fbe0d85..4ceaefd39 100644 --- a/reuse/CADSystem.java +++ b/reuse/CADSystem.java @@ -8,21 +8,21 @@ class Shape { Shape(int i) { - System.out.println("Shape constructor"); + System.err.println("Shape constructor"); } void dispose() { - System.out.println("Shape dispose"); + System.err.println("Shape dispose"); } } class Circle extends Shape { Circle(int i) { super(i); - System.out.println("Drawing Circle"); + System.err.println("Drawing Circle"); } @Override void dispose() { - System.out.println("Erasing Circle"); + System.err.println("Erasing Circle"); super.dispose(); } } @@ -30,11 +30,11 @@ void dispose() { class Triangle extends Shape { Triangle(int i) { super(i); - System.out.println("Drawing Triangle"); + System.err.println("Drawing Triangle"); } @Override void dispose() { - System.out.println("Erasing Triangle"); + System.err.println("Erasing Triangle"); super.dispose(); } } @@ -45,12 +45,12 @@ class Line extends Shape { super(start); this.start = start; this.end = end; - System.out.println( + System.err.println( "Drawing Line: " + start + ", " + end); } @Override void dispose() { - System.out.println( + System.err.println( "Erasing Line: " + start + ", " + end); super.dispose(); } @@ -66,13 +66,24 @@ public CADSystem(int i) { lines[j] = new Line(j, j*j); c = new Circle(1); t = new Triangle(1); - System.out.println("Combined constructor"); + System.err.println("Combined constructor"); } @Override + /** + * self-note + * 在很多情况下,清理问题不是问题;你只需要让垃圾收集器来完成这项工作。 + * 但是,当你必须执行显式清理时,就需要多做努力,更加细心,因为在垃圾收集方面没有什么可以依赖的。 + * 可能永远不会调用垃圾收集器。如果调用,它可以按照它想要的任何顺序回收对象。 + * 除了内存回收外,你不能依赖垃圾收集来做任何事情。 + * 如果希望进行清理,可以使用自己的清理方法,不要使用 finalize()。 + */ public void dispose() { - System.out.println("CADSystem.dispose()"); + System.err.println("CADSystem.dispose()"); // The order of cleanup is the reverse // of the order of initialization: + // 必须注意基类和成员对象清理方法的调用顺序,以防一个子对象依赖于另一个子对象 + // 即 按"与创建的相反顺序"执行特定于类的所有清理工作。(一般来说,这要求基类元素仍然是可访问的。) + // 然后 调用基类清理方法 t.dispose(); c.dispose(); for(int i = lines.length - 1; i >= 0; i--) diff --git a/reuse/Cartoon.java b/reuse/Cartoon.java index 48741bafb..c8402ef0e 100644 --- a/reuse/Cartoon.java +++ b/reuse/Cartoon.java @@ -6,20 +6,20 @@ class Art { Art() { - System.out.println("Art constructor"); + System.err.println("Art constructor"); } } class Drawing extends Art { Drawing() { - System.out.println("Drawing constructor"); + System.err.println("Drawing constructor"); } } public class Cartoon extends Drawing { - public Cartoon() { - System.out.println("Cartoon constructor"); - } +// public Cartoon() { +// System.err.println("Cartoon constructor"); +// } public static void main(String[] args) { Cartoon x = new Cartoon(); } @@ -28,4 +28,9 @@ public static void main(String[] args) { Art constructor Drawing constructor Cartoon constructor + + +self-note : 即使不为 Cartoon 创建构造函数, +编译器也会为你合成一个无参数构造函数,调用基类构造函数。 +尝试删除 Cartoon 构造函数来查看这个。 */ diff --git a/reuse/Chess.java b/reuse/Chess.java index 30f2685bc..c1bffc597 100644 --- a/reuse/Chess.java +++ b/reuse/Chess.java @@ -6,21 +6,22 @@ class Game { Game(int i) { - System.out.println("Game constructor"); + System.err.println("Game constructor"); } } class BoardGame extends Game { BoardGame(int i) { super(i); - System.out.println("BoardGame constructor"); + System.err.println("BoardGame constructor"); } } public class Chess extends BoardGame { Chess() { - super(11); - System.out.println("Chess constructor"); + super(11);// self-note:如果没有无参数的基类构造函数,或者必须调用具有参数的基类构造函数, + // 则必须使用 super 关键字和适当的参数列表显式地编写对基类构造函数的调用。 + System.err.println("Chess constructor"); } public static void main(String[] args) { Chess x = new Chess(); diff --git a/reuse/Detergent.java b/reuse/Detergent.java index 99f4e7cc3..1773e54b7 100644 --- a/reuse/Detergent.java +++ b/reuse/Detergent.java @@ -15,7 +15,7 @@ class Cleanser { public static void main(String[] args) { Cleanser x = new Cleanser(); x.dilute(); x.apply(); x.scrub(); - System.out.println(x); + System.err.println(x); } } @@ -35,8 +35,8 @@ public static void main(String[] args) { x.apply(); x.scrub(); x.foam(); - System.out.println(x); - System.out.println("Testing base class:"); + System.err.println(x); + System.err.println("Testing base class:"); Cleanser.main(args); } } @@ -45,4 +45,10 @@ Cleanser dilute() apply() Detergent.scrub() scrub() foam() Testing base class: Cleanser dilute() apply() scrub() + + +self-note : 如在 scrub() 中所见,可以使用基类中定义的方法并修改它。 +在这里,你可以在新类中调用基类的该方法。但是在 scrub() 内部,不能简单地调用 scrub(),因为这会产生递归调用。 +为了解决这个问题,Java的 super 关键字引用了当前类继承的“超类”(基类)。 +因此表达式 super.scrub() 调用方法 scrub() 的基类版本。 */ diff --git a/reuse/FinalData.java b/reuse/FinalData.java index 4376f5c3f..408f4a2a1 100644 --- a/reuse/FinalData.java +++ b/reuse/FinalData.java @@ -42,11 +42,11 @@ public static void main(String[] args) { //- fd1.v2 = new Value(0); // Error: Can't //- fd1.VAL_3 = new Value(1); // change reference //- fd1.a = new int[3]; - System.out.println(fd1); - System.out.println("Creating new FinalData"); + System.err.println(fd1); + System.err.println("Creating new FinalData"); FinalData fd2 = new FinalData("fd2"); - System.out.println(fd1); - System.out.println(fd2); + System.err.println(fd1); + System.err.println(fd2); } } /* Output: diff --git a/reuse/FinalOverridingIllusion.java b/reuse/FinalOverridingIllusion.java index e5c19ece5..f7c7891b2 100644 --- a/reuse/FinalOverridingIllusion.java +++ b/reuse/FinalOverridingIllusion.java @@ -6,31 +6,31 @@ // a private or private final method class WithFinals { - // Identical to "private" alone: + // Identical to "private" alone: 这里 有没有final是一样的 private final void f() { - System.out.println("WithFinals.f()"); + System.err.println("WithFinals.f()"); } - // Also automatically "final": + // Also automatically "final": self-note:私有方法自动处于final状态 private void g() { - System.out.println("WithFinals.g()"); + System.err.println("WithFinals.g()"); } } class OverridingPrivate extends WithFinals { private final void f() { - System.out.println("OverridingPrivate.f()"); + System.err.println("OverridingPrivate.f()"); } private void g() { - System.out.println("OverridingPrivate.g()"); + System.err.println("OverridingPrivate.g()"); } } class OverridingPrivate2 extends OverridingPrivate { public final void f() { - System.out.println("OverridingPrivate2.f()"); - } + System.err.println("OverridingPrivate2.f()"); + }//final给方法上锁,防止子类覆写 public void g() { - System.out.println("OverridingPrivate2.g()"); + System.err.println("OverridingPrivate2.g()"); } } @@ -40,10 +40,10 @@ public static void main(String[] args) { op2.f(); op2.g(); // You can upcast: - OverridingPrivate op = op2; + OverridingPrivate op = op2; //self-note: 向上转型会导致调用同名方法不明确而无法调用 // But you can't call the methods: - //- op.f(); - //- op.g(); +// op.f(); 如果一个方法是 private 的,它就不是基类接口的一部分。它只是隐藏在类内部的代码,且恰好有相同的命名而已。 +// op.g(); // Same here: WithFinals wf = op2; //- wf.f(); diff --git a/reuse/Hide.java b/reuse/Hide.java index f718e4b08..0968ee2d8 100644 --- a/reuse/Hide.java +++ b/reuse/Hide.java @@ -7,11 +7,11 @@ class Homer { char doh(char c) { - System.out.println("doh(char)"); + System.err.println("doh(char)"); return 'd'; } float doh(float f) { - System.out.println("doh(float)"); + System.err.println("doh(float)"); return 1.0f; } } @@ -20,7 +20,7 @@ class Milhouse {} class Bart extends Homer { void doh(Milhouse m) { - System.out.println("doh(Milhouse)"); + System.err.println("doh(Milhouse)"); } } diff --git a/reuse/Lisa.java b/reuse/Lisa.java index 85ec5cc90..626d3692b 100644 --- a/reuse/Lisa.java +++ b/reuse/Lisa.java @@ -6,6 +6,6 @@ class Lisa extends Homer { @Override void doh(Milhouse m) { - System.out.println("doh(Milhouse)"); + System.err.println("doh(Milhouse)"); } } diff --git a/reuse/Orc.java b/reuse/Orc.java index c3ba40a8e..ea9988e13 100644 --- a/reuse/Orc.java +++ b/reuse/Orc.java @@ -30,12 +30,14 @@ public String toString() { } public static void main(String[] args) { Orc orc = new Orc("Limburger", 12); - System.out.println(orc); + System.err.println(orc); orc.change("Bob", 19); - System.out.println(orc); + System.err.println(orc); } } /* Output: Orc 12: I'm a Villain and my name is Limburger Orc 19: I'm a Villain and my name is Bob +self-note: 尽管可以创建 protected 属性,但是最好的方式是将属性声明为 private 以一直保留更改底层实现的权利。 +然后通过 protected 控制类的继承者(Orc类)访问权限。 */ diff --git a/reuse/PlaceSetting.java b/reuse/PlaceSetting.java index b57d6383a..c98c6eef4 100644 --- a/reuse/PlaceSetting.java +++ b/reuse/PlaceSetting.java @@ -6,48 +6,48 @@ class Plate { Plate(int i) { - System.out.println("Plate constructor"); + System.err.println("Plate constructor"); } } class DinnerPlate extends Plate { DinnerPlate(int i) { super(i); - System.out.println("DinnerPlate constructor"); + System.err.println("DinnerPlate constructor"); } } class Utensil { Utensil(int i) { - System.out.println("Utensil constructor"); + System.err.println("Utensil constructor"); } } class Spoon extends Utensil { Spoon(int i) { super(i); - System.out.println("Spoon constructor"); + System.err.println("Spoon constructor"); } } class Fork extends Utensil { Fork(int i) { super(i); - System.out.println("Fork constructor"); + System.err.println("Fork constructor"); } } class Knife extends Utensil { Knife(int i) { super(i); - System.out.println("Knife constructor"); + System.err.println("Knife constructor"); } } // A cultural way of doing something: class Custom { Custom(int i) { - System.out.println("Custom constructor"); + System.err.println("Custom constructor"); } } @@ -62,7 +62,7 @@ public PlaceSetting(int i) { frk = new Fork(i + 3); kn = new Knife(i + 4); pl = new DinnerPlate(i + 5); - System.out.println("PlaceSetting constructor"); + System.err.println("PlaceSetting constructor"); } public static void main(String[] args) { PlaceSetting x = new PlaceSetting(9); diff --git a/reuse/SpaceShipDelegation.java b/reuse/SpaceShipDelegation.java index c31316b29..c65b41be3 100644 --- a/reuse/SpaceShipDelegation.java +++ b/reuse/SpaceShipDelegation.java @@ -13,7 +13,7 @@ public SpaceShipDelegation(String name) { // Delegated methods: public void back(int velocity) { controls.back(velocity); - } + }// 委托 方法被转发到底层 control 对象, public void down(int velocity) { controls.down(velocity); } @@ -37,4 +37,8 @@ public static void main(String[] args) { new SpaceShipDelegation("NSEA Protector"); protector.forward(100); } + + // self-note : 不直接支持的第三种重用关系称为"委托"。这介于继承和组合之间, + // 因为你将一个成员对象放在正在构建的类中(比如组合),但同时又在新类中公开来自成员对象的所有方法(比如继承)。 + // 你对这种重用关系拥有更多的控制,因为你可以选择只在成员对象中提供方法的"子集"。 } diff --git a/reuse/SprinklerSystem.java b/reuse/SprinklerSystem.java index e0ccbe661..7ffab5118 100644 --- a/reuse/SprinklerSystem.java +++ b/reuse/SprinklerSystem.java @@ -7,7 +7,7 @@ class WaterSource { private String s; WaterSource() { - System.out.println("WaterSource()"); + System.err.println("WaterSource()"); s = "Constructed"; } @Override @@ -31,7 +31,7 @@ public String toString() { } public static void main(String[] args) { SprinklerSystem sprinklers = new SprinklerSystem(); - System.out.println(sprinklers); + System.err.println(sprinklers); } } /* Output: diff --git a/selftypeinfo/typeinfo/AnonymousImplementation.java b/selftypeinfo/typeinfo/AnonymousImplementation.java new file mode 100644 index 000000000..7624fc897 --- /dev/null +++ b/selftypeinfo/typeinfo/AnonymousImplementation.java @@ -0,0 +1,50 @@ +// typeinfo/AnonymousImplementation.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// Anonymous inner classes can't hide from reflection +import typeinfo.interfacea.*; + +class AnonymousA { + public static A makeA() { + return new A() { + public void f() { + System.err.println("public C.f()"); + } + public void g() { + System.err.println("public C.g()"); + } + void u() { + System.err.println("package C.u()"); + } + protected void v() { + System.err.println("protected C.v()"); + } + private void w() { + System.err.println("private C.w()"); + } + }; + } +} + +public class AnonymousImplementation { + public static void + main(String[] args) throws Exception { + A a = AnonymousA.makeA(); + a.f(); + System.err.println(a.getClass().getName()); + // Reflection still gets into the anonymous class: + HiddenImplementation.callHiddenMethod(a, "g"); + HiddenImplementation.callHiddenMethod(a, "u"); + HiddenImplementation.callHiddenMethod(a, "v"); + HiddenImplementation.callHiddenMethod(a, "w"); + } +} +/* Output: +public C.f() +AnonymousA$1 +public C.g() +package C.u() +protected C.v() +private C.w() +*/ diff --git a/selftypeinfo/typeinfo/BoundedClassReferences.java b/selftypeinfo/typeinfo/BoundedClassReferences.java new file mode 100644 index 000000000..ed0945e60 --- /dev/null +++ b/selftypeinfo/typeinfo/BoundedClassReferences.java @@ -0,0 +1,13 @@ +// typeinfo/BoundedClassReferences.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. + +public class BoundedClassReferences { + public static void main(String[] args) { + Class bounded = int.class; + bounded = double.class; + bounded = Number.class; + // Or anything else derived from Number. + } +} diff --git a/selftypeinfo/typeinfo/ClassCasts.java b/selftypeinfo/typeinfo/ClassCasts.java new file mode 100644 index 000000000..fd0e17cf6 --- /dev/null +++ b/selftypeinfo/typeinfo/ClassCasts.java @@ -0,0 +1,16 @@ +// typeinfo/ClassCasts.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. + +class Building {} +class House extends Building {} + +public class ClassCasts { + public static void main(String[] args) { + Building b = new House(); + Class houseType = House.class; + House h = houseType.cast(b); + h = (House)b; // ... or just do this. + } +} diff --git a/selftypeinfo/typeinfo/ClassInitialization.java b/selftypeinfo/typeinfo/ClassInitialization.java new file mode 100644 index 000000000..1dfe6c573 --- /dev/null +++ b/selftypeinfo/typeinfo/ClassInitialization.java @@ -0,0 +1,59 @@ +// typeinfo/ClassInitialization.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +import java.util.*; + +class Initable { + static final int STATIC_FINAL = 47; + static final int STATIC_FINAL2 = + ClassInitialization.rand.nextInt(1000); + static { + System.err.println("Initializing Initable"); + } +} + +class Initable2 { + static int staticNonFinal = 147; + static { + System.err.println("Initializing Initable2"); + } +} + +class Initable3 { + static int staticNonFinal = 74; + static { + System.err.println("Initializing Initable3"); + } +} + +public class ClassInitialization { + public static Random rand = new Random(47); + public static void main(String[] args) throws Exception { + Class initable = Initable.class; + System.err.println("After creating Initable ref"); + // Does not trigger initialization: + System.err.println(Initable.STATIC_FINAL); + System.err.println(); + System.err.println(); + + // Does trigger initialization: + System.err.println(Initable.STATIC_FINAL2); + // Does trigger initialization: + System.err.println(Initable2.staticNonFinal); + Class initable3 = Class.forName("Initable3"); + System.err.println("After creating Initable3 ref"); + System.err.println(Initable3.staticNonFinal); + } +} +/* Output: +After creating Initable ref +47 +Initializing Initable +258 +Initializing Initable2 +147 +Initializing Initable3 +After creating Initable3 ref +74 +*/ diff --git a/selftypeinfo/typeinfo/DynamicSupplier.java b/selftypeinfo/typeinfo/DynamicSupplier.java new file mode 100644 index 000000000..60a8fc221 --- /dev/null +++ b/selftypeinfo/typeinfo/DynamicSupplier.java @@ -0,0 +1,42 @@ +// typeinfo/DynamicSupplier.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +import java.util.function.*; +import java.util.stream.*; + +class CountedInteger { + private static long counter; + private final long id = counter++; + @Override + public String toString() { return Long.toString(id); } +} + +public class DynamicSupplier implements Supplier { + private Class type; + public DynamicSupplier(Class type) { + this.type = type; + } + @Override + public T get() { + try { + return type.newInstance(); + } catch(Exception e) { + throw new RuntimeException(e); + } + } + public static void main(String[] args) { + Stream.generate( + new DynamicSupplier<>(CountedInteger.class)) + .skip(10) + .limit(5) + .forEach(System.out::println); + } +} +/* Output: +10 +11 +12 +13 +14 +*/ diff --git a/selftypeinfo/typeinfo/FamilyVsExactType.java b/selftypeinfo/typeinfo/FamilyVsExactType.java new file mode 100644 index 000000000..1944da116 --- /dev/null +++ b/selftypeinfo/typeinfo/FamilyVsExactType.java @@ -0,0 +1,62 @@ +// typeinfo/FamilyVsExactType.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// The difference between instanceof and class +// {java typeinfo.FamilyVsExactType} +package typeinfo; + +class Base {} +class Derived extends Base {} + +public class FamilyVsExactType { + static void test(Object x) { + System.err.println( + "Testing x of type " + x.getClass()); + System.err.println( + "x instanceof Base " + (x instanceof Base)); + System.err.println( + "x instanceof Derived " + (x instanceof Derived)); + System.err.println( + "Base.isInstance(x) " + Base.class.isInstance(x)); + System.err.println( + "Derived.isInstance(x) " + Derived.class.isInstance(x)); + System.err.println( + "x.getClass() == Base.class " + + (x.getClass() == Base.class)); + System.err.println( + "x.getClass() == Derived.class " + + (x.getClass() == Derived.class)); + System.err.println( + "x.getClass().equals(Base.class)) "+ + (x.getClass().equals(Base.class))); + System.err.println( + "x.getClass().equals(Derived.class)) " + + (x.getClass().equals(Derived.class))); + } + public static void main(String[] args) { + test(new Base()); + System.err.println("-------------------"); + test(new Derived()); + } +} +/* Output: +Testing x of type class typeinfo.Base +x instanceof Base true +x instanceof Derived false +Base.isInstance(x) true +Derived.isInstance(x) false +x.getClass() == Base.class true +x.getClass() == Derived.class false +x.getClass().equals(Base.class)) true +x.getClass().equals(Derived.class)) false +Testing x of type class typeinfo.Derived +x instanceof Base true +x instanceof Derived true +Base.isInstance(x) true +Derived.isInstance(x) true +x.getClass() == Base.class false +x.getClass() == Derived.class true +x.getClass().equals(Base.class)) false +x.getClass().equals(Derived.class)) true +*/ diff --git a/selftypeinfo/typeinfo/GenericClassReferences.java b/selftypeinfo/typeinfo/GenericClassReferences.java new file mode 100644 index 000000000..81ba7f7d0 --- /dev/null +++ b/selftypeinfo/typeinfo/GenericClassReferences.java @@ -0,0 +1,14 @@ +// typeinfo/GenericClassReferences.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. + +public class GenericClassReferences { + public static void main(String[] args) { + Class intClass = int.class; + Class genericIntClass = int.class; + genericIntClass = Integer.class; // Same thing + intClass = double.class; + // genericIntClass = double.class; // Illegal + } +} diff --git a/selftypeinfo/typeinfo/HiddenImplementation.java b/selftypeinfo/typeinfo/HiddenImplementation.java new file mode 100644 index 000000000..186b227cb --- /dev/null +++ b/selftypeinfo/typeinfo/HiddenImplementation.java @@ -0,0 +1,44 @@ +// typeinfo/HiddenImplementation.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// Sneaking around package hiding +import typeinfo.interfacea.*; +import typeinfo.packageaccess.*; +import java.lang.reflect.*; + +public class HiddenImplementation { + public static void + main(String[] args) throws Exception { + A a = HiddenC.makeA(); + a.f(); + System.err.println(a.getClass().getName()); + // Compile error: cannot find symbol 'C': + /* if(a instanceof C) { + C c = (C)a; + c.g(); + } */ + // Oops! Reflection still allows us to call g(): + callHiddenMethod(a, "g"); + // And even less accessible methods! + callHiddenMethod(a, "u"); + callHiddenMethod(a, "v"); + callHiddenMethod(a, "w"); + } + static void + callHiddenMethod(Object a, String methodName) + throws Exception { + Method g = + a.getClass().getDeclaredMethod(methodName); + g.setAccessible(true); + g.invoke(a); + } +} +/* Output: +public C.f() +typeinfo.packageaccess.C +public C.g() +package C.u() +protected C.v() +private C.w() +*/ diff --git a/selftypeinfo/typeinfo/InnerImplementation.java b/selftypeinfo/typeinfo/InnerImplementation.java new file mode 100644 index 000000000..4ba75d711 --- /dev/null +++ b/selftypeinfo/typeinfo/InnerImplementation.java @@ -0,0 +1,49 @@ +// typeinfo/InnerImplementation.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// Private inner classes can't hide from reflection +import typeinfo.interfacea.*; + +class InnerA { + private static class C implements A { + public void f() { + System.err.println("public C.f()"); + } + public void g() { + System.err.println("public C.g()"); + } + void u() { + System.err.println("package C.u()"); + } + protected void v() { + System.err.println("protected C.v()"); + } + private void w() { + System.err.println("private C.w()"); + } + } + public static A makeA() { return new C(); } +} + +public class InnerImplementation { + public static void + main(String[] args) throws Exception { + A a = InnerA.makeA(); + a.f(); + System.err.println(a.getClass().getName()); + // Reflection still gets into the private class: + HiddenImplementation.callHiddenMethod(a, "g"); + HiddenImplementation.callHiddenMethod(a, "u"); + HiddenImplementation.callHiddenMethod(a, "v"); + HiddenImplementation.callHiddenMethod(a, "w"); + } +} +/* Output: +public C.f() +InnerA$C +public C.g() +package C.u() +protected C.v() +private C.w() +*/ diff --git a/selftypeinfo/typeinfo/InterfaceViolation.java b/selftypeinfo/typeinfo/InterfaceViolation.java new file mode 100644 index 000000000..42a1af340 --- /dev/null +++ b/selftypeinfo/typeinfo/InterfaceViolation.java @@ -0,0 +1,27 @@ +// typeinfo/InterfaceViolation.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// Sneaking around an interface +import typeinfo.interfacea.*; + +class B implements A { + public void f() {} + public void g() {} +} + +public class InterfaceViolation { + public static void main(String[] args) { + A a = new B(); + a.f(); + // a.g(); // Compile error + System.err.println(a.getClass().getName()); + if(a instanceof B) { + B b = (B)a; + b.g(); + } + } +} +/* Output: +B +*/ diff --git a/selftypeinfo/typeinfo/ModifyingPrivateFields.java b/selftypeinfo/typeinfo/ModifyingPrivateFields.java new file mode 100644 index 000000000..9315d5c35 --- /dev/null +++ b/selftypeinfo/typeinfo/ModifyingPrivateFields.java @@ -0,0 +1,49 @@ +// typeinfo/ModifyingPrivateFields.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +import java.lang.reflect.*; + +class WithPrivateFinalField { + private int i = 1; + private final String s = "I'm totally safe"; + private String s2 = "Am I safe?"; + @Override + public String toString() { + return "i = " + i + ", " + s + ", " + s2; + } +} + +public class ModifyingPrivateFields { + public static void + main(String[] args) throws Exception { + WithPrivateFinalField pf = + new WithPrivateFinalField(); + System.err.println(pf); + Field f = pf.getClass().getDeclaredField("i"); + f.setAccessible(true); + System.err.println( + "f.getInt(pf): " + f.getInt(pf)); + f.setInt(pf, 47); + System.err.println(pf); + f = pf.getClass().getDeclaredField("s"); + f.setAccessible(true); + System.err.println("f.get(pf): " + f.get(pf)); + f.set(pf, "No, you're not!"); + System.err.println(pf); + f = pf.getClass().getDeclaredField("s2"); + f.setAccessible(true); + System.err.println("f.get(pf): " + f.get(pf)); + f.set(pf, "No, you're not!"); + System.err.println(pf); + } +} +/* Output: +i = 1, I'm totally safe, Am I safe? +f.getInt(pf): 1 +i = 47, I'm totally safe, Am I safe? +f.get(pf): I'm totally safe +i = 47, I'm totally safe, Am I safe? +f.get(pf): Am I safe? +i = 47, I'm totally safe, No, you're not! +*/ diff --git a/selftypeinfo/typeinfo/Null.java b/selftypeinfo/typeinfo/Null.java new file mode 100644 index 000000000..3c9d0a571 --- /dev/null +++ b/selftypeinfo/typeinfo/Null.java @@ -0,0 +1,6 @@ +package typeinfo;// onjava/Null.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. + +public interface Null {} diff --git a/selftypeinfo/typeinfo/NullRobot.java b/selftypeinfo/typeinfo/NullRobot.java new file mode 100644 index 000000000..c7eb02d4f --- /dev/null +++ b/selftypeinfo/typeinfo/NullRobot.java @@ -0,0 +1,60 @@ +package typeinfo;// typeinfo/NullRobot.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// Using a dynamic proxy to create an Optional +import java.lang.reflect.*; +import java.util.*; +import java.util.stream.*; + + + +class NullRobotProxyHandler implements InvocationHandler { + private String nullName; + private Robot proxied = new NRobot(); + NullRobotProxyHandler(Class type) { + nullName = type.getSimpleName() + " NullRobot"; + } + private class NRobot implements Null, Robot { + @Override + public String name() { return nullName; } + @Override + public String model() { return nullName; } + @Override + public List operations() { + return Collections.emptyList(); + } + } + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + return method.invoke(proxied, args); + } +} + +public class NullRobot { + public static Robot newNullRobot(Class type) { + return (Robot)Proxy.newProxyInstance( + NullRobot.class.getClassLoader(), + new Class[]{ Null.class, Robot.class }, + new NullRobotProxyHandler(type)); + } + public static void main(String[] args) { + Stream.of( + new SnowRemovalRobot("SnowBee"), + newNullRobot(SnowRemovalRobot.class) + ).forEach(Robot::test); + } +} +/* Output: +Robot name: SnowBee +Robot model: SnowBot Series 11 +SnowBee can shovel snow +SnowBee shoveling snow +SnowBee can chip ice +SnowBee chipping ice +SnowBee can clear the roof +SnowBee clearing roof +[Null Robot] +Robot name: SnowRemovalRobot NullRobot +Robot model: SnowRemovalRobot NullRobot +*/ diff --git a/selftypeinfo/typeinfo/Operation.java b/selftypeinfo/typeinfo/Operation.java new file mode 100644 index 000000000..a6529de3f --- /dev/null +++ b/selftypeinfo/typeinfo/Operation.java @@ -0,0 +1,15 @@ +package typeinfo;// typeinfo/Operation.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +import java.util.function.*; + +public class Operation { + public final Supplier description; + public final Runnable command; + public + Operation(Supplier descr, Runnable cmd) { + description = descr; + command = cmd; + } +} diff --git a/selftypeinfo/typeinfo/Pair.java b/selftypeinfo/typeinfo/Pair.java new file mode 100644 index 000000000..29b27e6d2 --- /dev/null +++ b/selftypeinfo/typeinfo/Pair.java @@ -0,0 +1,19 @@ +// onjava/Pair.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +package typeinfo; + +public class Pair { + public final K key; + public final V value; + public Pair(K k, V v) { + key = k; + value = v; + } + public K key() { return key; } + public V value() { return value; } + public static Pair make(K k, V v) { + return new Pair(k, v); + } +} diff --git a/selftypeinfo/typeinfo/Person.java b/selftypeinfo/typeinfo/Person.java new file mode 100644 index 000000000..67a963e13 --- /dev/null +++ b/selftypeinfo/typeinfo/Person.java @@ -0,0 +1,58 @@ +package typeinfo;// typeinfo/Person.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// Using Optional with regular classes + + + +import java.util.*; + +class Person { + public final Optional first; + public final Optional last; + public final Optional address; + // etc. + public final boolean empty; + + Person(String first, String last, String address) { + this.first = Optional.ofNullable(first); + this.last = Optional.ofNullable(last); + this.address = Optional.ofNullable(address); + empty = !this.first.isPresent() && !this.last.isPresent() && !this.address.isPresent(); + } + + Person(String first, String last) { + this(first, last, null); + } + + Person(String last) { + this(null, last, null); + } + + Person() { + this(null, null, null); + } + + @Override + public String toString() { + if (empty) + return ""; + return (first.orElse("") + + " " + last.orElse("") + + " " + address.orElse("")).trim(); + } + + public static void main(String[] args) { + System.err.println(new Person()); + System.err.println(new Person("Smith")); + System.err.println(new Person("Bob", "Smith")); + System.err.println(new Person("Bob", "Smith", "11 Degree Lane, Frostbite Falls, MN")); + } +} +/* Output: + +Smith +Bob Smith +Bob Smith 11 Degree Lane, Frostbite Falls, MN +*/ diff --git a/selftypeinfo/typeinfo/PetCount.java b/selftypeinfo/typeinfo/PetCount.java new file mode 100644 index 000000000..d1f8d5ad3 --- /dev/null +++ b/selftypeinfo/typeinfo/PetCount.java @@ -0,0 +1,64 @@ +package typeinfo;// typeinfo/PetCount.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// Using instanceof +import typeinfo.pets.*; +import java.util.*; + +public class PetCount { + static class Counter extends HashMap { + public void count(String type) { + Integer quantity = get(type); + if(quantity == null) + put(type, 1); + else + put(type, quantity + 1); + } + } + public static void countPets(PetCreator creator) { + Counter counter = new Counter(); + for(Pet pet : Pets.array(20)) { + // List each individual pet: + System.err.print( + pet.getClass().getSimpleName() + " "); + if(pet instanceof Pet) + counter.count("Pet"); + if(pet instanceof Dog) + counter.count("Dog"); + if(pet instanceof Mutt) + counter.count("Mutt"); + if(pet instanceof Pug) + counter.count("Pug"); + if(pet instanceof Cat) + counter.count("Cat"); + if(pet instanceof EgyptianMau) + counter.count("EgyptianMau"); + if(pet instanceof Manx) + counter.count("Manx"); + if(pet instanceof Cymric) + counter.count("Cymric"); + if(pet instanceof Rodent) + counter.count("Rodent"); + if(pet instanceof Rat) + counter.count("Rat"); + if(pet instanceof Mouse) + counter.count("Mouse"); + if(pet instanceof Hamster) + counter.count("Hamster"); + } + // Show the counts: + System.err.println(); + System.err.println(counter); + } + public static void main(String[] args) { + countPets(new ForNameCreator()); + } +} +/* Output: +Rat Manx Cymric Mutt Pug Cymric Pug Manx Cymric Rat +EgyptianMau Hamster EgyptianMau Mutt Mutt Cymric Mouse +Pug Mouse Cymric +{EgyptianMau=2, Pug=3, Rat=2, Cymric=5, Mouse=2, Cat=9, +Manx=7, Rodent=5, Mutt=3, Dog=6, Pet=20, Hamster=1} +*/ diff --git a/selftypeinfo/typeinfo/PetCount2.java b/selftypeinfo/typeinfo/PetCount2.java new file mode 100644 index 000000000..d409659a4 --- /dev/null +++ b/selftypeinfo/typeinfo/PetCount2.java @@ -0,0 +1,19 @@ +// typeinfo/PetCount2.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +import typeinfo.PetCount; +import typeinfo.pets.*; + +public class PetCount2 { + public static void main(String[] args) { + PetCount.countPets(Pets.CREATOR); + } +} +/* Output: +Rat Manx Cymric Mutt Pug Cymric Pug Manx Cymric Rat +EgyptianMau Hamster EgyptianMau Mutt Mutt Cymric Mouse +Pug Mouse Cymric +{EgyptianMau=2, Pug=3, Rat=2, Cymric=5, Mouse=2, Cat=9, +Manx=7, Rodent=5, Mutt=3, Dog=6, Pet=20, Hamster=1} +*/ diff --git a/selftypeinfo/typeinfo/PetCount3.java b/selftypeinfo/typeinfo/PetCount3.java new file mode 100644 index 000000000..24f2379a4 --- /dev/null +++ b/selftypeinfo/typeinfo/PetCount3.java @@ -0,0 +1,118 @@ +// typeinfo/PetCount3.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// Using isInstance() + +import typeinfo.pets.LiteralPetCreator; +import typeinfo.pets.Pet; +import typeinfo.pets.Pets; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.stream.Collectors; + + +public class PetCount3 { + static class Counter extends LinkedHashMap, Integer> { + Counter() { + super( +//self-note: fun1 + /* LiteralPetCreator.ALL_TYPES.stream() + .map(lpc -> Pair.make(lpc, 0)) + .collect(Collectors.toMap(Pair::key, Pair::value))*/ + + +//self-note: fun2 +// listToMap(LiteralPetCreator.ALL_TYPES, newList() ) + +//self-note: fun3 + /*listToMap(LiteralPetCreator.ALL_TYPES, + Stream.generate(() -> 0) + .limit(LiteralPetCreator.ALL_TYPES.size()) + .collect(Collectors.toList()))*/ +//self-note: fun4 +// LiteralPetCreator.ALL_TYPES.stream().collect(Collectors.toMap(x->x, x->0)) + +//self-note: fun5 + LiteralPetCreator.ALL_TYPES.stream().collect(Collectors.toMap(Function.identity(), x->0)) + +//2021年4月1日10:45:25 上述均是从原来的一个list,生成一个key为list的值,且所有value均为0的初始Map,为下一步count()中累加做准备的 + ); + } + + private static List newList() { + List l = new ArrayList<>(); + int len = LiteralPetCreator.ALL_TYPES.size(); + for (int i = 0; i < len; i++) { + l.add(0); + } + return l; + } + + public void count(Pet pet) { + // Class.isInstance() eliminates instanceofs: + entrySet().stream() + .filter(pair -> pair.getKey().isInstance(pet)) + .forEach(pair -> + put(pair.getKey(), pair.getValue() + 1)); + } + + @Override + public String toString() { + String result = entrySet().stream() + .map(pair -> String.format("%s=%s", + pair.getKey().getSimpleName(), + pair.getValue())) + .collect(Collectors.joining(", ")); + return "{" + result + "}"; + } + } + + public static void main(String[] args) { + Counter petCount = new Counter(); + Consumer count = petCount::count; + Consumer petConsumer = p -> System.err.print(p.getClass().getSimpleName() + " "); + Pets.stream() + .limit(20) + .peek(count) + .forEach(petConsumer);//self-note: 这两个consumer可互换位置 + + System.err.println("\n" + petCount); + } + + + public static Map listToMap(List keys, List values) { + return keys.stream().collect( + Collectors.toMap( + key -> key, + key -> values.get(keys.indexOf(key)) + ) + ); + } + + + + + +} +/* Output: +Rat Manx Cymric Mutt Pug Cymric Pug Manx Cymric Rat +EgyptianMau Hamster EgyptianMau Mutt Mutt Cymric Mouse +Pug Mouse Cymric +{Rat=2, Pug=3, Mutt=3, Mouse=2, Cat=9, Dog=6, Cymric=5, +EgyptianMau=2, Rodent=5, Hamster=1, Manx=7, Pet=20} +*/ + + +/** + * + * {EgyptianMau=2, Pug=3, Rat=2, Cymric=5, Mouse=2, Cat=9, Manx=7, Rodent=5, Mutt=3, Dog=6, Pet=20, Hamster=1} + * {EgyptianMau=2, Pug=3, Rat=2, Cymric=5, Mouse=2, Cat=9, Manx=7, Rodent=5, Mutt=3, Dog=6, Pet=20, Hamster=1} + * {EgyptianMau=2, Pug=3, Rat=2, Cymric=5, Mouse=2, Cat=9, Manx=7, Rodent=5, Mutt=3, Dog=6, Pet=20, Hamster=1} + * + */ diff --git a/selftypeinfo/typeinfo/PetCount4.java b/selftypeinfo/typeinfo/PetCount4.java new file mode 100644 index 000000000..e3aa5c9f3 --- /dev/null +++ b/selftypeinfo/typeinfo/PetCount4.java @@ -0,0 +1,26 @@ +package typeinfo;// typeinfo/PetCount4.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +import typeinfo.pets.*; +//import onjava.*; + +public class PetCount4 { + public static void main(String[] args) { + TypeCounter counter = new TypeCounter(Pet.class); + Pets.stream() + .limit(20) + .peek(counter::count) + .forEach(p -> System.err.print( + p.getClass().getSimpleName() + " ")); + System.err.println("\n" + counter); + } +} +/* Output: +Rat Manx Cymric Mutt Pug Cymric Pug Manx Cymric Rat +EgyptianMau Hamster EgyptianMau Mutt Mutt Cymric Mouse +Pug Mouse Cymric +{Dog=6, Manx=7, Cat=9, Rodent=5, Hamster=1, Rat=2, +Pug=3, Mutt=3, Cymric=5, EgyptianMau=2, Pet=20, +Mouse=2} +*/ diff --git a/selftypeinfo/typeinfo/Position.java b/selftypeinfo/typeinfo/Position.java new file mode 100644 index 000000000..a1d60f06b --- /dev/null +++ b/selftypeinfo/typeinfo/Position.java @@ -0,0 +1,65 @@ +package typeinfo;// typeinfo/Position.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. + + +import java.util.*; + +class EmptyTitleException extends RuntimeException { +} + +class Position { + private String title; + private Person person; + + Position(String jobTitle, Person employee) { + setTitle(jobTitle); + setPerson(employee); + } + + Position(String jobTitle) { + this(jobTitle, null); + } + + public String getTitle() { + return title; + } + + public void setTitle(String newTitle) { + // Throws EmptyTitleException if newTitle is null: + title = Optional.ofNullable(newTitle) + .orElseThrow(EmptyTitleException::new); + } + + public Person getPerson() { + return person; + } + + public void setPerson(Person newPerson) { + // Uses empty Person if newPerson is null: + person = Optional.ofNullable(newPerson) + .orElse(new Person()); + } + + @Override + public String toString() { + return "Position: " + title + + ", Employee: " + person; + } + + public static void main(String[] args) { + System.err.println(new Position("CEO")); + System.err.println(new Position("Programmer", new Person("Arthur", "Fonzarelli"))); + try { + new Position(null); + } catch (Exception e) { + System.err.println("caught " + e); + } + } +} +/* Output: +Position: CEO, Employee: +Position: Programmer, Employee: Arthur Fonzarelli +caught EmptyTitleException +*/ diff --git a/selftypeinfo/typeinfo/RegisteredFactories.java b/selftypeinfo/typeinfo/RegisteredFactories.java new file mode 100644 index 000000000..7f2e124f2 --- /dev/null +++ b/selftypeinfo/typeinfo/RegisteredFactories.java @@ -0,0 +1,102 @@ +// typeinfo/RegisteredFactories.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// Registering Factories in the base class +import java.util.*; +import java.util.function.*; +import java.util.stream.*; + +class Part implements Supplier { + @Override + public String toString() { + return getClass().getSimpleName(); + } + static List> prototypes; + + static { + AirFilter airFilter = new AirFilter(); + prototypes = Arrays.asList( + new FuelFilter(), + airFilter, + new CabinAirFilter(), + new OilFilter(), + new FanBelt(), + new PowerSteeringBelt(), + new GeneratorBelt() + ); + } + + private static Random rand = new Random(47); + @Override + public Part get() { + int n = rand.nextInt(prototypes.size()); + System.out.println("RANDNUM: "+n); + return prototypes.get(n).get(); + } +} + +class Filter extends Part {} + +class FuelFilter extends Filter { + @Override + public FuelFilter get() { return new FuelFilter(); } +} + +class AirFilter extends Filter { + @Override + public AirFilter get() { return new AirFilter(); } +} + +class CabinAirFilter extends Filter { + @Override + public CabinAirFilter get() { + return new CabinAirFilter(); + } +} + +class OilFilter extends Filter { + @Override + public OilFilter get() { return new OilFilter(); } +} + +class Belt extends Part {} + +class FanBelt extends Belt { + @Override + public FanBelt get() { return new FanBelt(); } +} + +class GeneratorBelt extends Belt { + @Override + public GeneratorBelt get() { + return new GeneratorBelt(); + } +} + +class PowerSteeringBelt extends Belt { + @Override + public PowerSteeringBelt get() { + return new PowerSteeringBelt(); + } +} + +public class RegisteredFactories { + public static void main(String[] args) { + Stream.generate(new Part()) + .limit(10) + .forEach(System.out::println); + } +} +/* Output: +GeneratorBelt +CabinAirFilter +GeneratorBelt +AirFilter +PowerSteeringBelt +CabinAirFilter +FuelFilter +PowerSteeringBelt +PowerSteeringBelt +FuelFilter +*/ diff --git a/selftypeinfo/typeinfo/Robot.java b/selftypeinfo/typeinfo/Robot.java new file mode 100644 index 000000000..8e7fd6c2a --- /dev/null +++ b/selftypeinfo/typeinfo/Robot.java @@ -0,0 +1,22 @@ +package typeinfo;// typeinfo/Robot.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. + +import java.util.*; + +public interface Robot { + String name(); + String model(); + List operations(); + static void test(Robot r) { + if(r instanceof Null) + System.err.println("[Null Robot]"); + System.err.println("Robot name: " + r.name()); + System.err.println("Robot model: " + r.model()); + for(Operation operation : r.operations()) { + System.err.println(operation.description.get()); + operation.command.run(); + } + } +} diff --git a/selftypeinfo/typeinfo/SelectingMethods.java b/selftypeinfo/typeinfo/SelectingMethods.java new file mode 100644 index 000000000..279c7fefe --- /dev/null +++ b/selftypeinfo/typeinfo/SelectingMethods.java @@ -0,0 +1,66 @@ +// typeinfo/SelectingMethods.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// Looking for particular methods in a dynamic proxy +import java.lang.reflect.*; + +class MethodSelector implements InvocationHandler { + private Object proxied; + MethodSelector(Object proxied) { + this.proxied = proxied; + } + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + if(method.getName().equals("interesting")) + System.err.println("Proxy detected the interesting method"); + return method.invoke(proxied, args); + } +} + +interface SomeMethods { + void boring1(); + void boring2(); + void interesting(String arg); + void boring3(); +} + +class Implementation implements SomeMethods { + @Override + public void boring1() { + System.err.println("boring1"); + } + @Override + public void boring2() { + System.err.println("boring2"); + } + @Override + public void interesting(String arg) { + System.err.println("interesting " + arg); + } + @Override + public void boring3() { + System.err.println("boring3"); + } +} + +class SelectingMethods { + public static void main(String[] args) { + SomeMethods proxy = + (SomeMethods)Proxy.newProxyInstance( + SomeMethods.class.getClassLoader(), + new Class[]{ SomeMethods.class }, + new MethodSelector(new Implementation())); + proxy.boring1(); + proxy.boring2(); + proxy.interesting("bonobo"); + proxy.boring3(); + } +} +/* Output: +boring1 +boring2 +Proxy detected the interesting method +interesting bonobo +boring3 +*/ diff --git a/selftypeinfo/typeinfo/Shapes.java b/selftypeinfo/typeinfo/Shapes.java new file mode 100644 index 000000000..0bc0d66ab --- /dev/null +++ b/selftypeinfo/typeinfo/Shapes.java @@ -0,0 +1,39 @@ +// typeinfo/Shapes.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +import java.util.stream.*; + +abstract class Shape { + void draw() { System.err.println(this + ".draw()"); } + @Override + public abstract String toString(); +} + +class Circle extends Shape { + @Override + public String toString() { return "Circle"; } +} + +class Square extends Shape { + @Override + public String toString() { return "Square"; } +} + +class Triangle extends Shape { + @Override + public String toString() { return "Triangle"; } +} + +public class Shapes { + public static void main(String[] args) { + Stream.of( + new Circle(), new Square(), new Triangle()) + .forEach(Shape::draw); + } +} +/* Output: +Circle.draw() +Square.draw() +Triangle.draw() +*/ diff --git a/selftypeinfo/typeinfo/ShowMethods.java b/selftypeinfo/typeinfo/ShowMethods.java new file mode 100644 index 000000000..221bd35a0 --- /dev/null +++ b/selftypeinfo/typeinfo/ShowMethods.java @@ -0,0 +1,77 @@ +// typeinfo/ShowMethods.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// Using reflection to show all the methods of a class, +// even if the methods are defined in the base class +// {java ShowMethods ShowMethods} +import java.lang.reflect.*; +import java.util.regex.*; + + class ShowMethods { + private static String usage = + "usage:\n" + + "ShowMethods qualified.class.name\n" + + "To show all methods in class or:\n" + + "ShowMethods qualified.class.name word\n" + + "To search for methods involving 'word'"; + private static Pattern p = Pattern.compile("\\w+\\."); + public static void main(String[] args) { + if(args.length < 1) { + System.err.println(usage); + System.exit(0); + } + int lines = 0; + try { + Class c = Class.forName(args[0]); + System.err.println("简单名字:"+c.getSimpleName()); + System.err.println(); + + + Method[] methods = c.getMethods(); + Constructor[] ctors = c.getConstructors(); + Constructor[] ctors2 = c.getDeclaredConstructors(); + + + if(args.length == 1) { + for(Method method : methods) { + System.err.println(p.matcher(method.toString()).replaceAll("")); +// System.err.println("M->"+method.toString().replaceAll("\\w+\\.","")); + } + for(Constructor ctor : ctors) + System.err.println("ctor: "+p.matcher(ctor.toString()).replaceAll("")); + for(Constructor ctor : ctors2) + System.err.println("ctor2: "+ctor.toString()); + lines = methods.length + ctors.length; + } else { + for(Method method : methods) + if(method.toString().contains(args[1])) { + System.err.println(p.matcher(method.toString()).replaceAll("")); + lines++; + } + for(Constructor ctor : ctors) + if(ctor.toString().contains(args[1])) { + System.err.println(p.matcher(ctor.toString()).replaceAll("")); + lines++; + } + } + } catch(ClassNotFoundException e) { + System.err.println("No such class: " + e); + } + } +} +/* Output: +public static void main(String[]) +public final void wait() throws InterruptedException +public final void wait(long,int) throws +InterruptedException +public final native void wait(long) throws +InterruptedException +public boolean equals(Object) +public String toString() +public native int hashCode() +public final native Class getClass() +public final native void notify() +public final native void notifyAll() +public ShowMethods() +*/ diff --git a/selftypeinfo/typeinfo/SimpleDynamicProxy.java b/selftypeinfo/typeinfo/SimpleDynamicProxy.java new file mode 100644 index 000000000..0c0a35f23 --- /dev/null +++ b/selftypeinfo/typeinfo/SimpleDynamicProxy.java @@ -0,0 +1,57 @@ +package typeinfo;// typeinfo/SimpleDynamicProxy.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. + +import java.lang.reflect.*; + +class DynamicProxyHandler implements InvocationHandler { + private Object proxied; + + DynamicProxyHandler(Object proxied) { + this.proxied = proxied; + } + + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + System.err.println( + "**** proxy: " + proxy.getClass() + ", method: " + method + ", args: " + args); + if (args != null) + for (Object arg : args) + System.err.println(" " + arg); + return method.invoke(proxied, args); + } +} + +class SimpleDynamicProxy { + public static void consumer(Interface iface) { + iface.doSomething(); + iface.somethingElse("bonobo"); + } + + public static void main(String[] args) { + RealObject real = new RealObject(); + consumer(real); + System.err.println(); + + // Insert a proxy and call again: + Interface proxy = (Interface) Proxy.newProxyInstance( + Interface.class.getClassLoader(), + new Class[]{Interface.class}, + new DynamicProxyHandler(real) + ); + consumer(proxy); + } +} +/* Output: +doSomething +somethingElse bonobo +**** proxy: class $Proxy0, method: public abstract void +Interface.doSomething(), args: null +doSomething +**** proxy: class $Proxy0, method: public abstract void +Interface.somethingElse(java.lang.String), args: +[Ljava.lang.Object;@6bc7c054 + bonobo +somethingElse bonobo +*/ diff --git a/selftypeinfo/typeinfo/SimpleProxyDemo.java b/selftypeinfo/typeinfo/SimpleProxyDemo.java new file mode 100644 index 000000000..922c2e899 --- /dev/null +++ b/selftypeinfo/typeinfo/SimpleProxyDemo.java @@ -0,0 +1,58 @@ +package typeinfo;// typeinfo/SimpleProxyDemo.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. + +interface Interface { + void doSomething(); + void somethingElse(String arg); +} + +class RealObject implements Interface { + @Override + public void doSomething() { + System.err.println("doSomething"); + } + @Override + public void somethingElse(String arg) { + System.err.println("somethingElse " + arg); + } +} + +class SimpleProxy implements Interface { + private Interface proxied; + SimpleProxy(Interface proxied) { + this.proxied = proxied; + } + @Override + public void doSomething() { + System.err.println("SimpleProxy doSomething"); + proxied.doSomething(); + } + @Override + public void somethingElse(String arg) { + System.err.println( + "SimpleProxy somethingElse " + arg); + proxied.somethingElse(arg); + } +} + +class SimpleProxyDemo { + public static void consumer(Interface iface) { + iface.doSomething(); + iface.somethingElse("bonobo"); + } + public static void main(String[] args) { + consumer(new RealObject()); + System.err.println(); + consumer(new SimpleProxy(new RealObject())); + } +} +/* Output: +doSomething +somethingElse bonobo +SimpleProxy doSomething +doSomething +SimpleProxy somethingElse bonobo +somethingElse bonobo +*/ diff --git a/selftypeinfo/typeinfo/SnowRemovalRobot.java b/selftypeinfo/typeinfo/SnowRemovalRobot.java new file mode 100644 index 000000000..bb79affd0 --- /dev/null +++ b/selftypeinfo/typeinfo/SnowRemovalRobot.java @@ -0,0 +1,43 @@ +package typeinfo;// typeinfo/SnowRemovalRobot.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +import java.util.*; + +public class SnowRemovalRobot implements Robot { + private String name; + public SnowRemovalRobot(String name) { + this.name = name; + } + @Override + public String name() { return name; } + @Override + public String model() { return "SnowBot Series 11"; } + private List ops = Arrays.asList( + new Operation( + () -> name + " can shovel snow", + () -> System.err.println( + name + " shoveling snow")), + new Operation( + () -> name + " can chip ice", + () -> System.err.println(name + " chipping ice")), + new Operation( + () -> name + " can clear the roof", + () -> System.err.println( + name + " clearing roof"))); + @Override + public List operations() { return ops; } + public static void main(String[] args) { + Robot.test(new SnowRemovalRobot("Slusher")); + } +} +/* Output: +Robot name: Slusher +Robot model: SnowBot Series 11 +Slusher can shovel snow +Slusher shoveling snow +Slusher can chip ice +Slusher chipping ice +Slusher can clear the roof +Slusher clearing roof +*/ diff --git a/selftypeinfo/typeinfo/Staff.java b/selftypeinfo/typeinfo/Staff.java new file mode 100644 index 000000000..9d6bcc47c --- /dev/null +++ b/selftypeinfo/typeinfo/Staff.java @@ -0,0 +1,65 @@ +package typeinfo;// typeinfo/Staff.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. + + +import java.util.*; + +public class Staff extends ArrayList { + public void add(String title, Person person) { + add(new Position(title, person)); + } + public void add(String... titles) { + for(String title : titles) + add(new Position(title)); + } + public Staff(String... titles) { add(titles); } + + public boolean positionAvailable(String title) { + for(Position position : this) { + if(position.getTitle().equals(title) && position.getPerson().empty) + return true; + } + return false; + } + public void fillPosition(String title, Person hire) { + for(Position position : this) { + if(position.getTitle().equals(title) && position.getPerson().empty) { + position.setPerson(hire); + return; + } + } + throw new RuntimeException("Position " + title + " not available"); + } + public static void main(String[] args) { + Staff staff = new Staff("President", "CTO", + "Marketing Manager", "Product Manager", + "Project Lead", "Software Engineer", + "Software Engineer", "Software Engineer", + "Software Engineer", "Test Engineer", + "Technical Writer"); + staff.fillPosition("President", + new Person("Me", "Last", "The Top, Lonely At")); + staff.fillPosition("Project Lead", + new Person("Janet", "Planner", "The Burbs")); + if(staff.positionAvailable("Software Engineer")) + staff.fillPosition("Software Engineer", + new Person( + "Bob", "Coder", "Bright Light City")); + System.err.println(staff); + } +} +/* Output: +[Position: President, Employee: Me Last The Top, Lonely +At, Position: CTO, Employee: , Position: +Marketing Manager, Employee: , Position: Product +Manager, Employee: , Position: Project Lead, +Employee: Janet Planner The Burbs, Position: Software +Engineer, Employee: Bob Coder Bright Light City, +Position: Software Engineer, Employee: , +Position: Software Engineer, Employee: , +Position: Software Engineer, Employee: , +Position: Test Engineer, Employee: , Position: +Technical Writer, Employee: ] +*/ diff --git a/selftypeinfo/typeinfo/SweetShop.java b/selftypeinfo/typeinfo/SweetShop.java new file mode 100644 index 000000000..25bd96a4c --- /dev/null +++ b/selftypeinfo/typeinfo/SweetShop.java @@ -0,0 +1,42 @@ +// typeinfo/SweetShop.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// Examination of the way the class loader works + +class Cookie { + static { System.err.println("Loading Cookie"); } +} + +class Gum { + static { System.err.println("Loading Gum"); } +} + +class Candy { + static { System.err.println("Loading Candy"); } +} + +public class SweetShop { + public static void main(String[] args) { + System.err.println("inside main"); + new Candy(); + System.err.println("After creating Candy"); + try { + Class.forName("Gum"); + } catch(ClassNotFoundException e) { + System.err.println("Couldn't find Gum"); + } + System.err.println("After Class.forName(\"Gum\")"); + new Cookie(); + System.err.println("After creating Cookie"); + } +} +/* Output: +inside main +Loading Candy +After creating Candy +Loading Gum +After Class.forName("Gum") +Loading Cookie +After creating Cookie +*/ diff --git a/selftypeinfo/typeinfo/TypeCounter.java b/selftypeinfo/typeinfo/TypeCounter.java new file mode 100644 index 000000000..91013fbf8 --- /dev/null +++ b/selftypeinfo/typeinfo/TypeCounter.java @@ -0,0 +1,40 @@ +package typeinfo;// onjava/TypeCounter.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// Counts instances of a type family +//package onjava; + +import java.util.HashMap; +import java.util.stream.Collectors; + +public class TypeCounter extends HashMap, Integer> { + private Class baseType; + public TypeCounter(Class baseType) { + this.baseType = baseType; + } + public void count(Object obj) { + Class type = obj.getClass(); + if(!baseType.isAssignableFrom(type)) throw new RuntimeException( + obj + " incorrect type: " + type + + ", should be type or subtype of " + baseType); + countClass(type); + } + private void countClass(Class type) { + Integer quantity = get(type); + put(type, quantity == null ? 1 : quantity + 1); + Class superClass = type.getSuperclass(); + if(superClass != null && + baseType.isAssignableFrom(superClass)) + countClass(superClass); + } + @Override + public String toString() { + String result = entrySet().stream() + .map(pair -> String.format("%s=%s", + pair.getKey().getSimpleName(), + pair.getValue())) + .collect(Collectors.joining(", ")); + return "{" + result + "}"; + } +} diff --git a/selftypeinfo/typeinfo/WildcardClassReferences.java b/selftypeinfo/typeinfo/WildcardClassReferences.java new file mode 100644 index 000000000..32d75e868 --- /dev/null +++ b/selftypeinfo/typeinfo/WildcardClassReferences.java @@ -0,0 +1,11 @@ +// typeinfo/WildcardClassReferences.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. + +public class WildcardClassReferences { + public static void main(String[] args) { + Class intClass = int.class; + intClass = double.class; + } +} diff --git a/selftypeinfo/typeinfo/interfacea/A.java b/selftypeinfo/typeinfo/interfacea/A.java new file mode 100644 index 000000000..2ebb99d32 --- /dev/null +++ b/selftypeinfo/typeinfo/interfacea/A.java @@ -0,0 +1,9 @@ +// typeinfo/interfacea/A.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +package typeinfo.interfacea; + +public interface A { + void f(); +} diff --git a/selftypeinfo/typeinfo/packageaccess/HiddenC.java b/selftypeinfo/typeinfo/packageaccess/HiddenC.java new file mode 100644 index 000000000..37558d3b5 --- /dev/null +++ b/selftypeinfo/typeinfo/packageaccess/HiddenC.java @@ -0,0 +1,29 @@ +// typeinfo/packageaccess/HiddenC.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +package typeinfo.packageaccess; +import typeinfo.interfacea.*; + +class C implements A { + @Override + public void f() { + System.err.println("public C.f()"); + } + public void g() { + System.err.println("public C.g()"); + } + void u() { + System.err.println("package C.u()"); + } + protected void v() { + System.err.println("protected C.v()"); + } + private void w() { + System.err.println("private C.w()"); + } +} + +public class HiddenC { + public static A makeA() { return new C(); } +} diff --git a/selftypeinfo/typeinfo/pets/Cat.java b/selftypeinfo/typeinfo/pets/Cat.java new file mode 100644 index 000000000..75781fd7f --- /dev/null +++ b/selftypeinfo/typeinfo/pets/Cat.java @@ -0,0 +1,10 @@ +// typeinfo/pets/Cat.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +package typeinfo.pets; + +public class Cat extends Pet { + public Cat(String name) { super(name); } + public Cat() { super(); } +} diff --git a/selftypeinfo/typeinfo/pets/Cymric.java b/selftypeinfo/typeinfo/pets/Cymric.java new file mode 100644 index 000000000..fd86fa953 --- /dev/null +++ b/selftypeinfo/typeinfo/pets/Cymric.java @@ -0,0 +1,10 @@ +// typeinfo/pets/Cymric.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +package typeinfo.pets; + +public class Cymric extends Manx { + public Cymric(String name) { super(name); } + public Cymric() { super(); } +} diff --git a/selftypeinfo/typeinfo/pets/Dog.java b/selftypeinfo/typeinfo/pets/Dog.java new file mode 100644 index 000000000..68f43a322 --- /dev/null +++ b/selftypeinfo/typeinfo/pets/Dog.java @@ -0,0 +1,10 @@ +// typeinfo/pets/Dog.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +package typeinfo.pets; + +public class Dog extends Pet { + public Dog(String name) { super(name); } + public Dog() { super(); } +} diff --git a/selftypeinfo/typeinfo/pets/EgyptianMau.java b/selftypeinfo/typeinfo/pets/EgyptianMau.java new file mode 100644 index 000000000..adbdfbb18 --- /dev/null +++ b/selftypeinfo/typeinfo/pets/EgyptianMau.java @@ -0,0 +1,10 @@ +// typeinfo/pets/EgyptianMau.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +package typeinfo.pets; + +public class EgyptianMau extends Cat { + public EgyptianMau(String name) { super(name); } + public EgyptianMau() { super(); } +} diff --git a/selftypeinfo/typeinfo/pets/ForNameCreator.java b/selftypeinfo/typeinfo/pets/ForNameCreator.java new file mode 100644 index 000000000..c00830f5f --- /dev/null +++ b/selftypeinfo/typeinfo/pets/ForNameCreator.java @@ -0,0 +1,45 @@ +// typeinfo/pets/ForNameCreator.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +package typeinfo.pets; + +import java.util.*; + +public class ForNameCreator extends PetCreator { + private static List> types = new ArrayList<>(); + // Types you want randomly created: + private static String[] typeNames = { + "typeinfo.pets.Mutt", + "typeinfo.pets.Pug", + "typeinfo.pets.EgyptianMau", + "typeinfo.pets.Manx", + "typeinfo.pets.Cymric", + "typeinfo.pets.Rat", + "typeinfo.pets.Mouse", + "typeinfo.pets.Hamster" + }; + + @SuppressWarnings("unchecked") + private static void loader() { + try { + for (String name : typeNames) + types.add((Class) Class.forName(name)); + } catch (ClassNotFoundException e) { + throw new RuntimeException(e); + } + } + + static { + loader(); + } + + @Override + public List> types() { + return types; + } + public static void main(String[] args) { + System.err.println(types); + } + +} diff --git a/selftypeinfo/typeinfo/pets/Hamster.java b/selftypeinfo/typeinfo/pets/Hamster.java new file mode 100644 index 000000000..8408ef623 --- /dev/null +++ b/selftypeinfo/typeinfo/pets/Hamster.java @@ -0,0 +1,10 @@ +// typeinfo/pets/Hamster.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +package typeinfo.pets; + +public class Hamster extends Rodent { + public Hamster(String name) { super(name); } + public Hamster() { super(); } +} diff --git a/selftypeinfo/typeinfo/pets/Individual.java b/selftypeinfo/typeinfo/pets/Individual.java new file mode 100644 index 000000000..e3c87dacb --- /dev/null +++ b/selftypeinfo/typeinfo/pets/Individual.java @@ -0,0 +1,46 @@ +// typeinfo/pets/Individual.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +package typeinfo.pets; +import java.util.*; + +public class +Individual implements Comparable { + private static long counter = 0; + private final long id = counter++; + private String name; + public Individual(String name) { this.name = name; } + // 'name' is optional: + public Individual() {} + @Override + public String toString() { + return getClass().getSimpleName() + + (name == null ? "" : " " + name); + } + public long id() { return id; } + @Override + public boolean equals(Object o) { + return o instanceof Individual && + Objects.equals(id, ((Individual)o).id); + } + @Override + public int hashCode() { + return Objects.hash(name, id); + } + @Override + public int compareTo(Individual arg) { + // Compare by class name first: + String first = getClass().getSimpleName(); + String argFirst = arg.getClass().getSimpleName(); + int firstCompare = first.compareTo(argFirst); + if(firstCompare != 0) + return firstCompare; + if(name != null && arg.name != null) { + int secondCompare = name.compareTo(arg.name); + if(secondCompare != 0) + return secondCompare; + } + return (arg.id < id ? -1 : (arg.id == id ? 0 : 1)); + } +} diff --git a/selftypeinfo/typeinfo/pets/LiteralPetCreator.java b/selftypeinfo/typeinfo/pets/LiteralPetCreator.java new file mode 100644 index 000000000..4743406cc --- /dev/null +++ b/selftypeinfo/typeinfo/pets/LiteralPetCreator.java @@ -0,0 +1,40 @@ +// typeinfo/pets/LiteralPetCreator.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// Using class literals +// {java typeinfo.pets.LiteralPetCreator} +package typeinfo.pets; + +import java.util.*; + +public class LiteralPetCreator extends PetCreator { + // No try block needed. + @SuppressWarnings("unchecked") + public static final List> ALL_TYPES = + Collections.unmodifiableList(Arrays.asList( + Pet.class, Dog.class, Cat.class, Rodent.class, + Mutt.class, Pug.class, EgyptianMau.class, + Manx.class, Cymric.class, Rat.class, + Mouse.class, Hamster.class)); + + // Types for random creation: + private static final List> TYPES = + ALL_TYPES.subList(ALL_TYPES.indexOf(Mutt.class), ALL_TYPES.size()); + + @Override + public List> types() { + return TYPES; + } + + public static void main(String[] args) { + System.err.println(TYPES); + } +} +/* Output: +[class typeinfo.pets.Mutt, class typeinfo.pets.Pug, +class typeinfo.pets.EgyptianMau, class +typeinfo.pets.Manx, class typeinfo.pets.Cymric, class +typeinfo.pets.Rat, class typeinfo.pets.Mouse, class +typeinfo.pets.Hamster] +*/ diff --git a/selftypeinfo/typeinfo/pets/Manx.java b/selftypeinfo/typeinfo/pets/Manx.java new file mode 100644 index 000000000..6a5534b13 --- /dev/null +++ b/selftypeinfo/typeinfo/pets/Manx.java @@ -0,0 +1,10 @@ +// typeinfo/pets/Manx.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +package typeinfo.pets; + +public class Manx extends Cat { + public Manx(String name) { super(name); } + public Manx() { super(); } +} diff --git a/selftypeinfo/typeinfo/pets/Mouse.java b/selftypeinfo/typeinfo/pets/Mouse.java new file mode 100644 index 000000000..bbb97cda0 --- /dev/null +++ b/selftypeinfo/typeinfo/pets/Mouse.java @@ -0,0 +1,10 @@ +// typeinfo/pets/Mouse.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +package typeinfo.pets; + +public class Mouse extends Rodent { + public Mouse(String name) { super(name); } + public Mouse() { super(); } +} diff --git a/selftypeinfo/typeinfo/pets/Mutt.java b/selftypeinfo/typeinfo/pets/Mutt.java new file mode 100644 index 000000000..f51814b93 --- /dev/null +++ b/selftypeinfo/typeinfo/pets/Mutt.java @@ -0,0 +1,10 @@ +// typeinfo/pets/Mutt.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +package typeinfo.pets; + +public class Mutt extends Dog { + public Mutt(String name) { super(name); } + public Mutt() { super(); } +} diff --git a/selftypeinfo/typeinfo/pets/Person.java b/selftypeinfo/typeinfo/pets/Person.java new file mode 100644 index 000000000..4dcfff2ce --- /dev/null +++ b/selftypeinfo/typeinfo/pets/Person.java @@ -0,0 +1,9 @@ +// typeinfo/pets/Person.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +package typeinfo.pets; + +public class Person extends Individual { + public Person(String name) { super(name); } +} diff --git a/selftypeinfo/typeinfo/pets/Pet.java b/selftypeinfo/typeinfo/pets/Pet.java new file mode 100644 index 000000000..dcbfd4ab7 --- /dev/null +++ b/selftypeinfo/typeinfo/pets/Pet.java @@ -0,0 +1,10 @@ +// typeinfo/pets/Pet.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +package typeinfo.pets; + +public class Pet extends Individual { + public Pet(String name) { super(name); } + public Pet() { super(); } +} diff --git a/selftypeinfo/typeinfo/pets/PetCreator.java b/selftypeinfo/typeinfo/pets/PetCreator.java new file mode 100644 index 000000000..3fdb26b07 --- /dev/null +++ b/selftypeinfo/typeinfo/pets/PetCreator.java @@ -0,0 +1,31 @@ +// typeinfo/pets/PetCreator.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// Creates random sequences of Pets +package typeinfo.pets; + +import java.util.*; +import java.util.function.*; +import java.lang.reflect.InvocationTargetException; + +public abstract +class PetCreator implements Supplier { + private Random rand = new Random(47); + + // The List of the different types of Pet to create: + public abstract List> types(); + + @Override + public Pet get() { // Create one random Pet + int n = rand.nextInt(types().size()); + try { + return types().get(n).getConstructor().newInstance(); + } catch (InstantiationException | + NoSuchMethodException | + InvocationTargetException | + IllegalAccessException e) { + throw new RuntimeException(e); + } + } +} diff --git a/selftypeinfo/typeinfo/pets/Pets.java b/selftypeinfo/typeinfo/pets/Pets.java new file mode 100644 index 000000000..69c16088f --- /dev/null +++ b/selftypeinfo/typeinfo/pets/Pets.java @@ -0,0 +1,35 @@ +// typeinfo/pets/Pets.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// Facade to produce a default PetCreator +package typeinfo.pets; + +import java.util.*; +import java.util.stream.*; + +public class Pets { + public static final PetCreator CREATOR = new LiteralPetCreator(); + + public static Pet get() { + return CREATOR.get(); + } + + public static Pet[] array(int size) { + Pet[] result = new Pet[size]; + for (int i = 0; i < size; i++) + result[i] = CREATOR.get(); + return result; + } + + public static List list(int size) { + List result = new ArrayList<>(); + Collections.addAll(result, array(size)); + return result; + } + + public static Stream stream() { + Stream generate = Stream.generate(CREATOR); + return generate; + } +} diff --git a/selftypeinfo/typeinfo/pets/Pug.java b/selftypeinfo/typeinfo/pets/Pug.java new file mode 100644 index 000000000..9d8ab4670 --- /dev/null +++ b/selftypeinfo/typeinfo/pets/Pug.java @@ -0,0 +1,10 @@ +// typeinfo/pets/Pug.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +package typeinfo.pets; + +public class Pug extends Dog { + public Pug(String name) { super(name); } + public Pug() { super(); } +} diff --git a/selftypeinfo/typeinfo/pets/Rat.java b/selftypeinfo/typeinfo/pets/Rat.java new file mode 100644 index 000000000..2ce5534b8 --- /dev/null +++ b/selftypeinfo/typeinfo/pets/Rat.java @@ -0,0 +1,10 @@ +// typeinfo/pets/Rat.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +package typeinfo.pets; + +public class Rat extends Rodent { + public Rat(String name) { super(name); } + public Rat() { super(); } +} diff --git a/selftypeinfo/typeinfo/pets/Rodent.java b/selftypeinfo/typeinfo/pets/Rodent.java new file mode 100644 index 000000000..7b998d0aa --- /dev/null +++ b/selftypeinfo/typeinfo/pets/Rodent.java @@ -0,0 +1,10 @@ +// typeinfo/pets/Rodent.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +package typeinfo.pets; + +public class Rodent extends Pet { + public Rodent(String name) { super(name); } + public Rodent() { super(); } +} diff --git a/selftypeinfo/typeinfo/toys/GenericToyTest.java b/selftypeinfo/typeinfo/toys/GenericToyTest.java new file mode 100644 index 000000000..ee03189fa --- /dev/null +++ b/selftypeinfo/typeinfo/toys/GenericToyTest.java @@ -0,0 +1,23 @@ +// typeinfo/toys/GenericToyTest.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// Testing class Class +// {java typeinfo.toys.GenericToyTest} +package typeinfo.toys; + +public class GenericToyTest { + @SuppressWarnings("deprecation") + public static void + main(String[] args) throws Exception { + Class ftClass = typeinfo.toys.FancyToy.class; + // Produces exact type: + typeinfo.toys.FancyToy fancyToy = ftClass.newInstance(); + Class up = + ftClass.getSuperclass(); + // This won't compile: + Class up2 = (Class) ftClass.getSuperclass(); + // Only produces Object: + Object obj = up.newInstance(); + } +} diff --git a/selftypeinfo/typeinfo/toys/ToyTest.java b/selftypeinfo/typeinfo/toys/ToyTest.java new file mode 100644 index 000000000..98794b657 --- /dev/null +++ b/selftypeinfo/typeinfo/toys/ToyTest.java @@ -0,0 +1,78 @@ +// typeinfo/toys/ToyTest.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// Testing class Class +// {java typeinfo.toys.ToyTest} +package typeinfo.toys; +import java.lang.reflect.InvocationTargetException; + +interface HasBatteries {} +interface Waterproof {} +interface Shoots {} + +class Toy { + // Comment out the following no-arg + // constructor to see NoSuchMethodError + Toy() {} + Toy(int i) {} +} + +class FancyToy extends Toy +implements HasBatteries, Waterproof, Shoots { + FancyToy() { super(1); } +} + +public class ToyTest { + static void printInfo(Class cc) { + System.err.println("Class name: " + cc.getName() + + " is interface? [" + cc.isInterface() + "]"); + System.err.println( + "Simple name: " + cc.getSimpleName()); + System.err.println( + "Canonical name : " + cc.getCanonicalName()); + } + @SuppressWarnings("deprecation") + public static void main(String[] args) { + Class c = null; + try { + c = Class.forName("typeinfo.toys.FancyToy"); + } catch(ClassNotFoundException e) { + System.err.println("Can't find FancyToy"); + System.exit(1); + } + printInfo(c); + System.err.println("-------------------------------------------------------"); + for(Class face : c.getInterfaces()) + printInfo(face); + System.err.println("-------------------------------------------------------"); + + Class up = c.getSuperclass(); + Object obj = null; + try { + // Requires no-arg constructor: + obj = up.newInstance(); + } catch(Exception e) { + throw new + RuntimeException("Cannot instantiate"); + } + printInfo(obj.getClass()); + } +} +/* Output: +Class name: typeinfo.toys.FancyToy is interface? [false] +Simple name: FancyToy +Canonical name : typeinfo.toys.FancyToy +Class name: typeinfo.toys.HasBatteries is interface? [true] +Simple name: HasBatteries +Canonical name : typeinfo.toys.HasBatteries +Class name: typeinfo.toys.Waterproof is interface? [true] +Simple name: Waterproof +Canonical name : typeinfo.toys.Waterproof +Class name: typeinfo.toys.Shoots is interface? [true] +Simple name: Shoots +Canonical name : typeinfo.toys.Shoots +Class name: typeinfo.toys.Toy is interface? [false] +Simple name: Toy +Canonical name : typeinfo.toys.Toy +*/ diff --git a/serialization/APerson.java b/serialization/APerson.java index 1f67eb1cb..fd78f7af9 100644 --- a/serialization/APerson.java +++ b/serialization/APerson.java @@ -53,7 +53,7 @@ public String toString() { new APerson("Dr. Bunsen", "Honeydew"), new APerson("Gonzo", "The Great"), new APerson("Phillip J.", "Fry")); - System.out.println(people); + System.err.println(people); Element root = new Element("people"); for(APerson p : people) root.appendChild(p.getXML()); diff --git a/serialization/AStoreCADState.java b/serialization/AStoreCADState.java index 0ce8858a0..e5ed2a9fb 100644 --- a/serialization/AStoreCADState.java +++ b/serialization/AStoreCADState.java @@ -102,7 +102,7 @@ public static void main(String[] args) { throw new RuntimeException(e); } // Display the shapes: - System.out.println(shapes); + System.err.println(shapes); } } /* Output: diff --git a/serialization/Blip3.java b/serialization/Blip3.java index 6741298c0..a54a093c3 100644 --- a/serialization/Blip3.java +++ b/serialization/Blip3.java @@ -9,11 +9,11 @@ public class Blip3 implements Externalizable { private int i; private String s; // No initialization public Blip3() { - System.out.println("Blip3 Constructor"); + System.err.println("Blip3 Constructor"); // s, i not initialized } public Blip3(String x, int a) { - System.out.println("Blip3(String x, int a)"); + System.err.println("Blip3(String x, int a)"); s = x; i = a; // s & i initialized only in non-no-arg constructor. @@ -23,7 +23,7 @@ public Blip3(String x, int a) { @Override public void writeExternal(ObjectOutput out) throws IOException { - System.out.println("Blip3.writeExternal"); + System.err.println("Blip3.writeExternal"); // You must do this: out.writeObject(s); out.writeInt(i); @@ -31,26 +31,26 @@ public void writeExternal(ObjectOutput out) @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { - System.out.println("Blip3.readExternal"); + System.err.println("Blip3.readExternal"); // You must do this: s = (String)in.readObject(); i = in.readInt(); } public static void main(String[] args) { - System.out.println("Constructing objects:"); + System.err.println("Constructing objects:"); Blip3 b3 = new Blip3("A String ", 47); - System.out.println(b3); + System.err.println(b3); try( ObjectOutputStream o = new ObjectOutputStream( new FileOutputStream("Blip3.serialized")) ) { - System.out.println("Saving object:"); + System.err.println("Saving object:"); o.writeObject(b3); } catch(IOException e) { throw new RuntimeException(e); } // Now get it back: - System.out.println("Recovering b3:"); + System.err.println("Recovering b3:"); try( ObjectInputStream in = new ObjectInputStream( new FileInputStream("Blip3.serialized")) @@ -59,7 +59,7 @@ public static void main(String[] args) { } catch(IOException | ClassNotFoundException e) { throw new RuntimeException(e); } - System.out.println(b3); + System.err.println(b3); } } /* Output: diff --git a/serialization/Blips.java b/serialization/Blips.java index 88116d844..43e2f8b02 100644 --- a/serialization/Blips.java +++ b/serialization/Blips.java @@ -7,53 +7,53 @@ class Blip1 implements Externalizable { public Blip1() { - System.out.println("Blip1 Constructor"); + System.err.println("Blip1 Constructor"); } @Override public void writeExternal(ObjectOutput out) throws IOException { - System.out.println("Blip1.writeExternal"); + System.err.println("Blip1.writeExternal"); } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { - System.out.println("Blip1.readExternal"); + System.err.println("Blip1.readExternal"); } } class Blip2 implements Externalizable { Blip2() { - System.out.println("Blip2 Constructor"); + System.err.println("Blip2 Constructor"); } @Override public void writeExternal(ObjectOutput out) throws IOException { - System.out.println("Blip2.writeExternal"); + System.err.println("Blip2.writeExternal"); } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { - System.out.println("Blip2.readExternal"); + System.err.println("Blip2.readExternal"); } } public class Blips { public static void main(String[] args) { - System.out.println("Constructing objects:"); + System.err.println("Constructing objects:"); Blip1 b1 = new Blip1(); Blip2 b2 = new Blip2(); try( ObjectOutputStream o = new ObjectOutputStream( new FileOutputStream("Blips.serialized")) ) { - System.out.println("Saving objects:"); + System.err.println("Saving objects:"); o.writeObject(b1); o.writeObject(b2); } catch(IOException e) { throw new RuntimeException(e); } // Now get them back: - System.out.println("Recovering b1:"); + System.err.println("Recovering b1:"); try( ObjectInputStream in = new ObjectInputStream( new FileInputStream("Blips.serialized")) @@ -63,7 +63,7 @@ public static void main(String[] args) { throw new RuntimeException(e); } // OOPS! Throws an exception: - //- System.out.println("Recovering b2:"); + //- System.err.println("Recovering b2:"); //- b2 = (Blip2)in.readObject(); } } diff --git a/serialization/Logon.java b/serialization/Logon.java index 3b9109681..149aca609 100644 --- a/serialization/Logon.java +++ b/serialization/Logon.java @@ -24,7 +24,7 @@ public String toString() { } public static void main(String[] args) { Logon a = new Logon("Hulk", "myLittlePony"); - System.out.println("logon a = " + a); + System.err.println("logon a = " + a); try( ObjectOutputStream o = new ObjectOutputStream( @@ -40,13 +40,13 @@ public static void main(String[] args) { ObjectInputStream in = new ObjectInputStream( new FileInputStream("Logon.dat")) ) { - System.out.println( + System.err.println( "Recovering object at " + new Date()); a = (Logon)in.readObject(); } catch(IOException | ClassNotFoundException e) { throw new RuntimeException(e); } - System.out.println("logon a = " + a); + System.err.println("logon a = " + a); } } /* Output: diff --git a/serialization/MyWorld.java b/serialization/MyWorld.java index 99e39de34..b8fdda193 100644 --- a/serialization/MyWorld.java +++ b/serialization/MyWorld.java @@ -31,7 +31,7 @@ public static void main(String[] args) { new Animal("Ralph the hamster", house)); animals.add( new Animal("Molly the cat", house)); - System.out.println("animals: " + animals); + System.err.println("animals: " + animals); try( ByteArrayOutputStream buf1 = new ByteArrayOutputStream(); @@ -63,11 +63,11 @@ public static void main(String[] args) { animals1 = (List)in1.readObject(), animals2 = (List)in1.readObject(), animals3 = (List)in2.readObject(); - System.out.println( + System.err.println( "animals1: " + animals1); - System.out.println( + System.err.println( "animals2: " + animals2); - System.out.println( + System.err.println( "animals3: " + animals3); } } diff --git a/serialization/People.java b/serialization/People.java index 0e588749a..75f41d574 100644 --- a/serialization/People.java +++ b/serialization/People.java @@ -20,7 +20,7 @@ public People(String fileName) throws Exception { public static void main(String[] args) throws Exception { People p = new People("People.xml"); - System.out.println(p); + System.err.println(p); } } /* Output: diff --git a/serialization/RecoverCADState.java b/serialization/RecoverCADState.java index 612f501cf..add7f12e8 100644 --- a/serialization/RecoverCADState.java +++ b/serialization/RecoverCADState.java @@ -21,7 +21,7 @@ public static void main(String[] args) { Line.deserializeStaticState(in); List shapes = (List)in.readObject(); - System.out.println(shapes); + System.err.println(shapes); } catch(IOException | ClassNotFoundException e) { throw new RuntimeException(e); } diff --git a/serialization/SerialCtl.java b/serialization/SerialCtl.java index ed891633d..1ba9a4de0 100644 --- a/serialization/SerialCtl.java +++ b/serialization/SerialCtl.java @@ -27,7 +27,7 @@ private void readObject(ObjectInputStream stream) } public static void main(String[] args) { SerialCtl sc = new SerialCtl("Test1", "Test2"); - System.out.println("Before:\n" + sc); + System.err.println("Before:\n" + sc); try ( ByteArrayOutputStream buf = new ByteArrayOutputStream(); @@ -43,7 +43,7 @@ public static void main(String[] args) { buf.toByteArray())); ) { SerialCtl sc2 = (SerialCtl)in.readObject(); - System.out.println("After:\n" + sc2); + System.err.println("After:\n" + sc2); } } catch(IOException | ClassNotFoundException e) { throw new RuntimeException(e); diff --git a/serialization/Worm.java b/serialization/Worm.java index 666beb87b..7cfa101e5 100644 --- a/serialization/Worm.java +++ b/serialization/Worm.java @@ -26,13 +26,13 @@ public class Worm implements Serializable { private char c; // Value of i == number of segments public Worm(int i, char x) { - System.out.println("Worm constructor: " + i); + System.err.println("Worm constructor: " + i); c = x; if(--i > 0) next = new Worm(i, (char)(x + 1)); } public Worm() { - System.out.println("No-arg constructor"); + System.err.println("No-arg constructor"); } @Override public String toString() { @@ -50,7 +50,7 @@ public String toString() { main(String[] args) throws ClassNotFoundException, IOException { Worm w = new Worm(6, 'a'); - System.out.println("w = " + w); + System.err.println("w = " + w); try( ObjectOutputStream out = new ObjectOutputStream( new FileOutputStream("worm.dat")) @@ -64,7 +64,7 @@ public String toString() { ) { String s = (String)in.readObject(); Worm w2 = (Worm)in.readObject(); - System.out.println(s + "w2 = " + w2); + System.err.println(s + "w2 = " + w2); } try( ByteArrayOutputStream bout = @@ -82,7 +82,7 @@ public String toString() { ) { String s = (String)in2.readObject(); Worm w3 = (Worm)in2.readObject(); - System.out.println(s + "w3 = " + w3); + System.err.println(s + "w3 = " + w3); } } } diff --git a/serialization/xfiles/ThawAlien.java b/serialization/xfiles/ThawAlien.java index 1de6ce6af..1e348618f 100644 --- a/serialization/xfiles/ThawAlien.java +++ b/serialization/xfiles/ThawAlien.java @@ -14,7 +14,7 @@ public class ThawAlien { ObjectInputStream in = new ObjectInputStream( new FileInputStream(new File("X.file"))); Object mystery = in.readObject(); - System.out.println(mystery.getClass()); + System.err.println(mystery.getClass()); } } /* Output: diff --git a/staticchecking/dr/DogsAndRobots.java b/staticchecking/dr/DogsAndRobots.java index 9bede8045..d62e3ab2a 100644 --- a/staticchecking/dr/DogsAndRobots.java +++ b/staticchecking/dr/DogsAndRobots.java @@ -9,14 +9,14 @@ interface Speaks { void talk(); } class Dog implements Speaks { public void talk() { - System.out.println("Woof!"); + System.err.println("Woof!"); } public void reproduce() { } } class Robot implements Speaks { public void talk() { - System.out.println("Click!"); + System.err.println("Click!"); } public void oilChange() { } } diff --git a/staticchecking/drc/DogAndRobotCollections.java b/staticchecking/drc/DogAndRobotCollections.java index 16a82ed54..9a031ac7f 100644 --- a/staticchecking/drc/DogAndRobotCollections.java +++ b/staticchecking/drc/DogAndRobotCollections.java @@ -8,14 +8,14 @@ class Dog { public void talk() { - System.out.println("Woof!"); + System.err.println("Woof!"); } public void reproduce() { } } class Robot { public void talk() { - System.out.println("Click!"); + System.err.println("Click!"); } public void oilChange() { } } diff --git a/staticchecking/latent/Latent.java b/staticchecking/latent/Latent.java index 29e53713e..b46969918 100644 --- a/staticchecking/latent/Latent.java +++ b/staticchecking/latent/Latent.java @@ -8,14 +8,14 @@ class Dog { public void talk() { - System.out.println("Woof!"); + System.err.println("Woof!"); } public void reproduce() {} } class Robot { public void talk() { - System.out.println("Click!"); + System.err.println("Click!"); } public void oilChange() {} } @@ -34,13 +34,13 @@ public static void speak(Object speaker) { spkr.getMethod("talk", (Class[])null); talk.invoke(speaker, new Object[]{}); } catch(NoSuchMethodException e) { - System.out.println( + System.err.println( speaker + " cannot talk"); } catch(IllegalAccessException e) { - System.out.println( + System.err.println( speaker + " IllegalAccessException"); } catch(InvocationTargetException e) { - System.out.println( + System.err.println( speaker + " InvocationTargetException"); } } diff --git a/staticchecking/petspeak/PetSpeak.java b/staticchecking/petspeak/PetSpeak.java index 0b850c3b4..0b02f5d4b 100644 --- a/staticchecking/petspeak/PetSpeak.java +++ b/staticchecking/petspeak/PetSpeak.java @@ -12,13 +12,13 @@ interface Pet { class Cat implements Pet { public void speak() { - System.out.println("meow!"); + System.err.println("meow!"); } } class Dog implements Pet { public void speak() { - System.out.println("woof!"); + System.err.println("woof!"); } } diff --git a/streams/ArrayStreams.java b/streams/ArrayStreams.java index dfed6e83b..37b31d633 100644 --- a/streams/ArrayStreams.java +++ b/streams/ArrayStreams.java @@ -9,18 +9,18 @@ public class ArrayStreams { public static void main(String[] args) { Arrays.stream( new double[] { 3.14159, 2.718, 1.618 }) - .forEach(n -> System.out.format("%f ", n)); - System.out.println(); + .forEach(n -> System.err.format("%f ", n)); + System.err.println(); Arrays.stream(new int[] { 1, 3, 5 }) - .forEach(n -> System.out.format("%d ", n)); - System.out.println(); + .forEach(n -> System.err.format("%d ", n)); + System.err.println(); Arrays.stream(new long[] { 11, 22, 44, 66 }) - .forEach(n -> System.out.format("%d ", n)); - System.out.println(); + .forEach(n -> System.err.format("%d ", n)); + System.err.println(); // Select a subrange: Arrays.stream( new int[] { 1, 3, 5, 7, 15, 28, 37 }, 3, 6) - .forEach(n -> System.out.format("%d ", n)); + .forEach(n -> System.err.format("%d ", n)); } } /* Output: diff --git a/streams/CollectionToStream.java b/streams/CollectionToStream.java index 93236ef1f..1bfe2c4e7 100644 --- a/streams/CollectionToStream.java +++ b/streams/CollectionToStream.java @@ -9,7 +9,7 @@ public class CollectionToStream { public static void main(String[] args) { List bubbles = Arrays.asList( new Bubble(1), new Bubble(2), new Bubble(3)); - System.out.println( + System.err.println( bubbles.stream() .mapToInt(b -> b.i) .sum()); @@ -19,7 +19,7 @@ public static void main(String[] args) { w.stream() .map(x -> x + " ") .forEach(System.out::print); - System.out.println(); + System.err.println(); Map m = new HashMap<>(); m.put("pi", 3.14159); diff --git a/streams/CreatingOptionals.java b/streams/CreatingOptionals.java index 7e886ddc2..c9df71de0 100644 --- a/streams/CreatingOptionals.java +++ b/streams/CreatingOptionals.java @@ -9,8 +9,8 @@ class CreatingOptionals { static void test(String testName, Optional opt) { - System.out.println(" === " + testName + " === "); - System.out.println(opt.orElse("Null")); + System.err.println(" === " + testName + " === "); + System.err.println(opt.orElse("Null")); } public static void main(String[] args) { test("empty", Optional.empty()); @@ -18,7 +18,7 @@ public static void main(String[] args) { try { test("of", Optional.of(null)); } catch(Exception e) { - System.out.println(e); + System.err.println(e); } test("ofNullable", Optional.ofNullable("Hi")); test("ofNullable", Optional.ofNullable(null)); diff --git a/streams/Fibonacci.java b/streams/Fibonacci.java index fa53c6879..f7080ed2c 100644 --- a/streams/Fibonacci.java +++ b/streams/Fibonacci.java @@ -7,7 +7,7 @@ public class Fibonacci { int x = 1; Stream numbers() { - return Stream.iterate(0, i -> { + return Stream.iterate(70, i -> { int result = x + i; x = i; return result; @@ -15,7 +15,7 @@ Stream numbers() { } public static void main(String[] args) { new Fibonacci().numbers() - .skip(20) // Don't use the first 20 +// .skip(20) // Don't use the first 20 .limit(10) // Then take 10 of them .forEach(System.out::println); } diff --git a/streams/FileToWords.java b/streams/FileToWords.java index 7f7174cbe..4eee505f7 100644 --- a/streams/FileToWords.java +++ b/streams/FileToWords.java @@ -11,7 +11,6 @@ public static Stream stream(String filePath) throws Exception { return Files.lines(Paths.get(filePath)) .skip(1) // First (comment) line - .flatMap(line -> - Pattern.compile("\\W+").splitAsStream(line)); + .flatMap(line -> Pattern.compile("\\W+").splitAsStream(line)); } } diff --git a/streams/FileToWordsRegexp.java b/streams/FileToWordsRegexp.java index dfff507e1..13821594b 100644 --- a/streams/FileToWordsRegexp.java +++ b/streams/FileToWordsRegexp.java @@ -16,8 +16,7 @@ public FileToWordsRegexp(String filePath) .collect(Collectors.joining(" ")); } public Stream stream() { - return Pattern - .compile("[ .,?]+").splitAsStream(all); + return Pattern.compile("[ .,?]+").splitAsStream(all); } public static void main(String[] args) throws Exception { diff --git a/streams/FileToWordsTest.java b/streams/FileToWordsTest.java index a81f72096..4b7baf992 100644 --- a/streams/FileToWordsTest.java +++ b/streams/FileToWordsTest.java @@ -9,12 +9,12 @@ public class FileToWordsTest { main(String[] args) throws Exception { FileToWords.stream("Cheese.dat") .limit(7) - .forEach(s -> System.out.format("%s ", s)); - System.out.println(); + .forEach(s -> System.err.format("%s ", s)); + System.err.println(); FileToWords.stream("Cheese.dat") .skip(7) .limit(2) - .forEach(s -> System.out.format("%s ", s)); + .forEach(s -> System.err.format("%s ", s)); } } /* Output: diff --git a/streams/ForEach.java b/streams/ForEach.java index f0abe2558..0def42f95 100644 --- a/streams/ForEach.java +++ b/streams/ForEach.java @@ -10,15 +10,15 @@ public class ForEach { static final int SZ = 14; public static void main(String[] args) { rands().limit(SZ) - .forEach(n -> System.out.format("%d ", n)); - System.out.println(); + .forEach(n -> System.err.format("%d ", n)); + System.err.println(); rands().limit(SZ) .parallel() - .forEach(n -> System.out.format("%d ", n)); - System.out.println(); + .forEach(n -> System.err.format("%d ", n)); + System.err.println(); rands().limit(SZ) .parallel() - .forEachOrdered(n -> System.out.format("%d ", n)); + .forEachOrdered(n -> System.err.format("%d ", n)); } } /* Output: diff --git a/streams/FunctionMap.java b/streams/FunctionMap.java index 3c7c90e79..459cd7049 100644 --- a/streams/FunctionMap.java +++ b/streams/FunctionMap.java @@ -13,7 +13,7 @@ static Stream testStream() { } static void test(String descr, Function func) { - System.out.println(" ---( " + descr + " )---"); + System.err.println(" ---( " + descr + " )---"); testStream() .map(func) .forEach(System.out::println); diff --git a/streams/FunctionMap3.java b/streams/FunctionMap3.java index 74236af31..a74471465 100644 --- a/streams/FunctionMap3.java +++ b/streams/FunctionMap3.java @@ -10,15 +10,15 @@ class FunctionMap3 { public static void main(String[] args) { Stream.of("5", "7", "9") .mapToInt(Integer::parseInt) - .forEach(n -> System.out.format("%d ", n)); - System.out.println(); + .forEach(n -> System.err.format("%d ", n)); + System.err.println(); Stream.of("17", "19", "23") .mapToLong(Long::parseLong) - .forEach(n -> System.out.format("%d ", n)); - System.out.println(); + .forEach(n -> System.err.format("%d ", n)); + System.err.println(); Stream.of("17", "1.9", ".23") .mapToDouble(Double::parseDouble) - .forEach(n -> System.out.format("%f ", n)); + .forEach(n -> System.err.format("%f ", n)); } } /* Output: diff --git a/streams/Generator.java b/streams/Generator.java index c9aba7404..f8544b12d 100644 --- a/streams/Generator.java +++ b/streams/Generator.java @@ -17,7 +17,7 @@ public static void main(String[] args) { String word = Stream.generate(new Generator()) .limit(30) .collect(Collectors.joining()); - System.out.println(word); + System.err.println(word); } } /* Output: diff --git a/streams/ImperativeRandoms.java b/streams/ImperativeRandoms.java index f9baaca5b..b3df332d2 100644 --- a/streams/ImperativeRandoms.java +++ b/streams/ImperativeRandoms.java @@ -13,7 +13,7 @@ public static void main(String[] args) { if(r < 5) continue; rints.add(r); } - System.out.println(rints); + System.err.println(rints); } } /* Output: diff --git a/streams/Informational.java b/streams/Informational.java index dd80585c3..fd1d95402 100644 --- a/streams/Informational.java +++ b/streams/Informational.java @@ -8,13 +8,13 @@ public class Informational { public static void main(String[] args) throws Exception { - System.out.println( + System.err.println( FileToWords.stream("Cheese.dat").count()); - System.out.println( + System.err.println( FileToWords.stream("Cheese.dat") .min(String.CASE_INSENSITIVE_ORDER) .orElse("NONE")); - System.out.println( + System.err.println( FileToWords.stream("Cheese.dat") .max(String.CASE_INSENSITIVE_ORDER) .orElse("NONE")); diff --git a/streams/LastElement.java b/streams/LastElement.java index 398b0488d..3367dc1cb 100644 --- a/streams/LastElement.java +++ b/streams/LastElement.java @@ -9,12 +9,12 @@ public class LastElement { public static void main(String[] args) { OptionalInt last = IntStream.range(10, 20) .reduce((n1, n2) -> n2); - System.out.println(last.orElse(-1)); + System.err.println(last.orElse(-1)); // Non-numeric object: Optional lastobj = Stream.of("one", "two", "three") .reduce((n1, n2) -> n2); - System.out.println( + System.err.println( lastobj.orElse("Nothing there!")); } } diff --git a/streams/Looping.java b/streams/Looping.java index 715ad052e..54b71ef8f 100644 --- a/streams/Looping.java +++ b/streams/Looping.java @@ -5,9 +5,9 @@ import static onjava.Repeat.*; public class Looping { - static void hi() { System.out.println("Hi!"); } + static void hi() { System.err.println("Hi!"); } public static void main(String[] args) { - repeat(3, () -> System.out.println("Looping!")); + repeat(3, () -> System.err.println("Looping!")); repeat(2, Looping::hi); } } diff --git a/streams/Machine2.java b/streams/Machine2.java index 3d407185c..1afc18b4c 100644 --- a/streams/Machine2.java +++ b/streams/Machine2.java @@ -7,8 +7,11 @@ public class Machine2 { public static void main(String[] args) { + Operations bing = () -> Operations.show("Bing"); + bing.execute();//self-note: 重点! 这是将静态方法重新给接口方法execute引用了! 该接口是函数式接口@FunctionalInterface + Arrays.stream(new Operations[] { - () -> Operations.show("Bing"), + bing, () -> Operations.show("Crack"), () -> Operations.show("Twist"), () -> Operations.show("Pop") diff --git a/streams/MapCollector.java b/streams/MapCollector.java index 95811e4b1..08eb882a0 100644 --- a/streams/MapCollector.java +++ b/streams/MapCollector.java @@ -2,47 +2,57 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. + import java.util.*; import java.util.stream.*; class Pair { - public final Character c; - public final Integer i; - Pair(Character c, Integer i) { - this.c = c; - this.i = i; - } - public Character getC() { return c; } - public Integer getI() { return i; } - @Override - public String toString() { - return "Pair(" + c + ", " + i + ")"; - } + public final Character c; + public final Integer i; + + Pair(Character c, Integer i) { + this.c = c; + this.i = i; + } + + public Character getC() { + return c; + } + + public Integer getI() { + return i; + } + + @Override + public String toString() { + return "Pair(" + c + ", " + i + ")"; + } } class RandomPair { - Random rand = new Random(47); - // An infinite iterator of random capital letters: - Iterator capChars = rand.ints(65,91) - .mapToObj(i -> (char)i) - .iterator(); - public Stream stream() { - return rand.ints(100, 1000).distinct() - .mapToObj(i -> new Pair(capChars.next(), i)); - } + Random rand = new Random(47); + // An infinite iterator of random capital letters: + Iterator iterator = rand.ints(65, 91) + .mapToObj(i -> (char) i) + .iterator(); + + public Stream stream() { + return rand.ints(100, 1000).distinct()//去重,防止报map重复key的异常 + .mapToObj(i -> new Pair(iterator.next(), i));//这是将多个流组合成新的对象流的唯一方法。 + } } public class MapCollector { - public static void main(String[] args) { - Map map = - new RandomPair().stream() - .limit(8) - .collect( - Collectors.toMap(Pair::getI, Pair::getC)); - System.out.println(map); - } + public static void main(String[] args) { + Map map = + new RandomPair().stream() + .limit(8) + .peek(System.err::println) + .collect( + Collectors.toMap(Pair::getI, Pair::getC));//self-note: 这里反过来会报重复key的异常 + System.err.println(map); + } } /* Output: -{688=W, 309=C, 293=B, 761=N, 858=N, 668=G, 622=F, -751=N} +{688=W, 309=C, 293=B, 761=N, 858=N, 668=G, 622=F, 751=N} */ diff --git a/streams/Matching.java b/streams/Matching.java index f5c01bc6d..0a24c120d 100644 --- a/streams/Matching.java +++ b/streams/Matching.java @@ -3,30 +3,38 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Demonstrates short-circuiting of *Match() operations + import java.util.stream.*; import java.util.function.*; + import static streams.RandInts.*; -interface Matcher extends - BiPredicate, Predicate> {} +/*interface Matcher extends BiPredicate, Predicate> { +}*/ public class Matching { - static void show(Matcher match, int val) { - System.out.println( - match.test( - IntStream.rangeClosed(1, 9) - .boxed() - .peek(n -> System.out.format("%d ", n)), - n -> n < val)); - } - public static void main(String[] args) { - show(Stream::allMatch, 10); - show(Stream::allMatch, 4); - show(Stream::anyMatch, 2); - show(Stream::anyMatch, 0); - show(Stream::noneMatch, 5); - show(Stream::noneMatch, 0); - } + static void show(BiPredicate, Predicate> matcher, int val) { + System.err.println( + matcher.test( + IntStream.rangeClosed(1, 9) + .boxed() + .peek(n -> System.err.format("%d ", n)), + n -> n < val) + ); + } + + public static void main(String[] args) { + BiFunction, Predicate, Boolean> aaa = Stream::allMatch; + BiPredicate, Predicate> allMatch = Stream::allMatch; + show( allMatch, 10); + BiPredicate, Predicate> allMatch1 = Stream::allMatch; + show(allMatch1, 4); + BiPredicate, Predicate> anyMatch = Stream::anyMatch; + show(anyMatch, 2); + show(Stream::anyMatch, 0); + show(Stream::noneMatch, 5); + show(Stream::noneMatch, 0); + } } /* Output: 1 2 3 4 5 6 7 8 9 true diff --git a/streams/NumericStreamInfo.java b/streams/NumericStreamInfo.java index 0d04b6ef3..1eb7f5af3 100644 --- a/streams/NumericStreamInfo.java +++ b/streams/NumericStreamInfo.java @@ -7,11 +7,11 @@ public class NumericStreamInfo { public static void main(String[] args) { - System.out.println(rands().average().getAsDouble()); - System.out.println(rands().max().getAsInt()); - System.out.println(rands().min().getAsInt()); - System.out.println(rands().sum()); - System.out.println(rands().summaryStatistics()); + System.err.println(rands().average().getAsDouble()); + System.err.println(rands().max().getAsInt()); + System.err.println(rands().min().getAsInt()); + System.err.println(rands().sum()); + System.err.println(rands().summaryStatistics()); } } /* Output: diff --git a/streams/OptionalBasics.java b/streams/OptionalBasics.java index 625c450ab..b13aae73b 100644 --- a/streams/OptionalBasics.java +++ b/streams/OptionalBasics.java @@ -8,9 +8,9 @@ class OptionalBasics { static void test(Optional optString) { if(optString.isPresent()) - System.out.println(optString.get()); + System.err.println(optString.get()); else - System.out.println("Nothing inside!"); + System.err.println("Nothing inside!"); } public static void main(String[] args) { test(Stream.of("Epithets").findFirst()); diff --git a/streams/OptionalFilter.java b/streams/OptionalFilter.java index a2095ec3b..be5783bd1 100644 --- a/streams/OptionalFilter.java +++ b/streams/OptionalFilter.java @@ -15,9 +15,9 @@ static Stream testStream() { } static void test(String descr, Predicate pred) { - System.out.println(" ---( " + descr + " )---"); + System.err.println(" ---( " + descr + " )---"); for(int i = 0; i <= elements.length; i++) { - System.out.println( + System.err.println( testStream() .skip(i) .findFirst() diff --git a/streams/OptionalFlatMap.java b/streams/OptionalFlatMap.java index 52e8e81e8..645b17b69 100644 --- a/streams/OptionalFlatMap.java +++ b/streams/OptionalFlatMap.java @@ -13,9 +13,9 @@ static Stream testStream() { } static void test(String descr, Function> func) { - System.out.println(" ---( " + descr + " )---"); + System.err.println(" ---( " + descr + " )---"); for(int i = 0; i <= elements.length; i++) { - System.out.println( + System.err.println( testStream() .skip(i) .findFirst() diff --git a/streams/OptionalMap.java b/streams/OptionalMap.java index 83ae4396b..9c3e96348 100644 --- a/streams/OptionalMap.java +++ b/streams/OptionalMap.java @@ -13,9 +13,9 @@ static Stream testStream() { } static void test(String descr, Function func) { - System.out.println(" ---( " + descr + " )---"); + System.err.println(" ---( " + descr + " )---"); for(int i = 0; i <= elements.length; i++) { - System.out.println( + System.err.println( testStream() .skip(i) .findFirst() // Produces an Optional diff --git a/streams/Optionals.java b/streams/Optionals.java index 4d0d96cbd..9160ade57 100644 --- a/streams/Optionals.java +++ b/streams/Optionals.java @@ -2,48 +2,57 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. + import java.util.*; import java.util.stream.*; import java.util.function.*; public class Optionals { - static void basics(Optional optString) { - if(optString.isPresent()) - System.out.println(optString.get()); - else - System.out.println("Nothing inside!"); - } - static void ifPresent(Optional optString) { - optString.ifPresent(System.out::println); - } - static void orElse(Optional optString) { - System.out.println(optString.orElse("Nada")); - } - static void orElseGet(Optional optString) { - System.out.println( + static void basics(Optional optString) { + if (optString.isPresent()) + System.err.println(optString.get()); + else + System.err.println("Nothing inside!"); + } + + static void ifPresent(Optional optString) { + optString.ifPresent(System.out::println); + } + + static void orElse(Optional optString) { + System.err.println(optString.orElse("Nada")); + } + + static void orElseGet(Optional optString) { + System.err.println( optString.orElseGet(() -> "Generated")); - } - static void orElseThrow(Optional optString) { - try { - System.out.println(optString.orElseThrow( - () -> new Exception("Supplied"))); - } catch(Exception e) { - System.out.println("Caught " + e); +// optString.orElse("Generated")); self-note: 是上面这种的简化 + + } + + static void orElseThrow(Optional optString) { + try { + System.err.println(optString.orElseThrow( + () -> new Exception("Supplied"))); + } catch (Exception e) { + System.err.println("Caught " + e); + } + } + + static void test(String testName, + Consumer> cos) { + System.err.println(" === " + testName + " === "); + cos.accept(Stream.of("Epithets").findFirst()); + cos.accept(Stream.empty().findFirst()); + } + + public static void main(String[] args) { + test("basics", Optionals::basics); + test("ifPresent", Optionals::ifPresent); + test("orElse", Optionals::orElse); + test("orElseGet", Optionals::orElseGet); + test("orElseThrow", Optionals::orElseThrow); } - } - static void test(String testName, - Consumer> cos) { - System.out.println(" === " + testName + " === "); - cos.accept(Stream.of("Epithets").findFirst()); - cos.accept(Stream.empty().findFirst()); - } - public static void main(String[] args) { - test("basics", Optionals::basics); - test("ifPresent", Optionals::ifPresent); - test("orElse", Optionals::orElse); - test("orElseGet", Optionals::orElseGet); - test("orElseThrow", Optionals::orElseThrow); - } } /* Output: === basics === diff --git a/streams/OptionalsFromEmptyStreams.java b/streams/OptionalsFromEmptyStreams.java index 771a84c0b..819fd7370 100644 --- a/streams/OptionalsFromEmptyStreams.java +++ b/streams/OptionalsFromEmptyStreams.java @@ -7,17 +7,17 @@ class OptionalsFromEmptyStreams { public static void main(String[] args) { - System.out.println(Stream.empty() + System.err.println(Stream.empty() .findFirst()); - System.out.println(Stream.empty() + System.err.println(Stream.empty() .findAny()); - System.out.println(Stream.empty() + System.err.println(Stream.empty() .max(String.CASE_INSENSITIVE_ORDER)); - System.out.println(Stream.empty() + System.err.println(Stream.empty() .min(String.CASE_INSENSITIVE_ORDER)); - System.out.println(Stream.empty() + System.err.println(Stream.empty() .reduce((s1, s2) -> s1 + s2)); - System.out.println(IntStream.empty() + System.err.println(IntStream.empty() .average()); } } diff --git a/streams/Prime.java b/streams/Prime.java index e14459d1a..10c5622f4 100644 --- a/streams/Prime.java +++ b/streams/Prime.java @@ -17,12 +17,12 @@ public LongStream numbers() { public static void main(String[] args) { new Prime().numbers() .limit(10) - .forEach(n -> System.out.format("%d ", n)); - System.out.println(); + .forEach(n -> System.err.format("%d ", n)); + System.err.println(); new Prime().numbers() .skip(90) .limit(10) - .forEach(n -> System.out.format("%d ", n)); + .forEach(n -> System.err.format("%d ", n)); } } /* Output: diff --git a/streams/RandomGenerators.java b/streams/RandomGenerators.java index 904216ac6..7146a34ec 100644 --- a/streams/RandomGenerators.java +++ b/streams/RandomGenerators.java @@ -10,7 +10,7 @@ public static void show(Stream stream) { stream .limit(4) .forEach(System.out::println); - System.out.println("++++++++"); + System.err.println("++++++++"); } public static void main(String[] args) { Random rand = new Random(47); diff --git a/streams/RandomWords.java b/streams/RandomWords.java index 3bf2e51bb..8702efb1d 100644 --- a/streams/RandomWords.java +++ b/streams/RandomWords.java @@ -13,13 +13,17 @@ public class RandomWords implements Supplier { Random rand = new Random(47); RandomWords(String fname) throws IOException { List lines = - Files.readAllLines(Paths.get(fname)); + Files.readAllLines(Paths.get("") + .resolve("streams") + .resolve(fname) + .toRealPath()); // Skip the first line: for(String line : lines.subList(1, lines.size())) { for(String word : line.split("[ .?,]+")) words.add(word.toLowerCase()); } } + @Override public String get() { return words.get(rand.nextInt(words.size())); } @@ -30,10 +34,10 @@ public String toString() { } public static void main(String[] args) throws Exception { - System.out.println( + System.err.println( Stream.generate(new RandomWords("Cheese.dat")) .limit(10) - .collect(Collectors.joining(" "))); + .collect(Collectors.joining("|"))); } } /* Output: diff --git a/streams/Ranges.java b/streams/Ranges.java index d8fc681ac..f8f07045f 100644 --- a/streams/Ranges.java +++ b/streams/Ranges.java @@ -6,20 +6,21 @@ public class Ranges { public static void main(String[] args) { + //self-note: 左闭右开,1到99之和 // rangeClosed的话就是1到100了! // The traditional way: int result = 0; - for(int i = 10; i < 20; i++) + for(int i = 1; i < 100; i++) result += i; - System.out.println(result); + System.err.println(result); // for-in with a range: result = 0; - for(int i : range(10, 20).toArray()) + for(int i : range(1, 100).toArray()) result += i; - System.out.println(result); + System.err.println(result); // Use streams: - System.out.println(range(10, 20).sum()); + System.err.println(rangeClosed(1, 100).sum()); } } /* Output: diff --git a/streams/Reduce.java b/streams/Reduce.java index 0e9f07ba9..3000be425 100644 --- a/streams/Reduce.java +++ b/streams/Reduce.java @@ -26,7 +26,7 @@ public static void main(String[] args) { .limit(10) .peek(System.out::println) .reduce((fr0, fr1) -> fr0.size < 50 ? fr0 : fr1) - .ifPresent(System.out::println); + .ifPresent(System.err::println); } } /* Output: diff --git a/streams/SelectElement.java b/streams/SelectElement.java index 86846e404..90bd4a30a 100644 --- a/streams/SelectElement.java +++ b/streams/SelectElement.java @@ -8,11 +8,11 @@ public class SelectElement { public static void main(String[] args) { - System.out.println(rands().findFirst().getAsInt()); - System.out.println( + System.err.println(rands().findFirst().getAsInt()); + System.err.println( rands().parallel().findFirst().getAsInt()); - System.out.println(rands().findAny().getAsInt()); - System.out.println( + System.err.println(rands().findAny().getAsInt()); + System.err.println( rands().parallel().findAny().getAsInt()); } } diff --git a/streams/SpecialCollector.java b/streams/SpecialCollector.java index 9526a73ea..f8d57844d 100644 --- a/streams/SpecialCollector.java +++ b/streams/SpecialCollector.java @@ -9,12 +9,16 @@ public class SpecialCollector { public static void main(String[] args) throws Exception { ArrayList words = - FileToWords.stream("Cheese.dat") - .collect(ArrayList::new, + FileToWords.stream("D:\\GitOnlyTestProject\\OnJava8-Examples\\streams\\Cheese.dat") +// .parallel() + .collect( +// ArrayList::new, + ()->{ System.err.println("NEW");return new ArrayList<>();}, ArrayList::add, - ArrayList::addAll); + ArrayList::addAll); //self-note: [非并发时]该参数无效 + //该参数包含两个方法combiner以及finisher: finisher将结果容器转换成最终的返回结果。如果结果容器类型和最终返回结果类型一致,那么finisher就可以不执行 words.stream() - .filter(s -> s.equals("cheese")) +// .filter(s -> s.equals("cheese")) .forEach(System.out::println); } } diff --git a/streams/StreamOf.java b/streams/StreamOf.java index c143388a3..dc8cca73d 100644 --- a/streams/StreamOf.java +++ b/streams/StreamOf.java @@ -12,7 +12,7 @@ public static void main(String[] args) { Stream.of("It's ", "a ", "wonderful ", "day ", "for ", "pie!") .forEach(System.out::print); - System.out.println(); + System.err.println(); Stream.of(3.14159, 2.718, 1.618) .forEach(System.out::println); } diff --git a/streams/StreamOfOptionals.java b/streams/StreamOfOptionals.java index f725df578..3252f563a 100644 --- a/streams/StreamOfOptionals.java +++ b/streams/StreamOfOptionals.java @@ -7,12 +7,14 @@ public class StreamOfOptionals { public static void main(String[] args) { - Signal.stream() +/* Signal.stream() .limit(10) - .forEach(System.out::println); - System.out.println(" ---"); + .forEach(System.err::println); + System.err.println(" ---");*/ + Signal.stream() .limit(10) + .peek(x-> System.err.println("[P]:"+x)) .filter(Optional::isPresent) .map(Optional::get) .forEach(System.out::println); @@ -29,7 +31,7 @@ public static void main(String[] args) { Optional[Signal(dot)] Optional[Signal(dash)] Optional[Signal(dash)] - --- + --- self-note: 上面的和下面无关, 种子拿取一次之后就延续下去了, 因此取出的随机元素是顺延的 Signal(dot) Signal(dot) Signal(dash) diff --git a/streams/StreamOfRandoms.java b/streams/StreamOfRandoms.java index 66bf2bc7d..35e6e5f46 100644 --- a/streams/StreamOfRandoms.java +++ b/streams/StreamOfRandoms.java @@ -11,7 +11,7 @@ public static void main(String[] args) { Stream.of(1, 2, 3, 4, 5) .flatMapToInt(i -> IntStream.concat( rand.ints(0, 100).limit(i), IntStream.of(-1))) - .forEach(n -> System.out.format("%d ", n)); + .forEach(n -> System.err.format("%d ", n)); } } /* Output: diff --git a/streams/TreeSetOfWords.java b/streams/TreeSetOfWords.java index feaa56a2a..e2711153b 100644 --- a/streams/TreeSetOfWords.java +++ b/streams/TreeSetOfWords.java @@ -17,7 +17,7 @@ public class TreeSetOfWords { .filter(s -> s.length() > 2) .limit(100) .collect(Collectors.toCollection(TreeSet::new)); - System.out.println(words2); + System.err.println(words2); } } /* Output: diff --git a/streams/onjava/Operations.java b/streams/onjava/Operations.java new file mode 100644 index 000000000..44839660d --- /dev/null +++ b/streams/onjava/Operations.java @@ -0,0 +1,19 @@ +package onjava;// onjava/Operations.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. + +import java.util.*; + +@FunctionalInterface +public interface Operations { + void execute (); + + static void runOps(Operations... ops) { + for(Operations op : ops) + op.execute(); + } + static void show(String msg) { + System.err.println(msg); + } +} diff --git a/strings/ArrayListDisplay.java b/strings/ArrayListDisplay.java index 7b83296f0..ac81f6622 100644 --- a/strings/ArrayListDisplay.java +++ b/strings/ArrayListDisplay.java @@ -12,7 +12,7 @@ public static void main(String[] args) { Stream.generate(new CoffeeSupplier()) .limit(10) .collect(Collectors.toList()); - System.out.println(coffees); + System.err.println(coffees); } } /* Output: diff --git a/strings/BetterRead.java b/strings/BetterRead.java index a3b7aaa2d..4aee88153 100644 --- a/strings/BetterRead.java +++ b/strings/BetterRead.java @@ -7,20 +7,20 @@ public class BetterRead { public static void main(String[] args) { Scanner stdin = new Scanner(SimpleRead.input); - System.out.println("What is your name?"); + System.err.println("What is your name?"); String name = stdin.nextLine(); - System.out.println(name); - System.out.println( + System.err.println(name); + System.err.println( "How old are you? What is your favorite double?"); - System.out.println("(input: )"); + System.err.println("(input: )"); int age = stdin.nextInt(); double favorite = stdin.nextDouble(); - System.out.println(age); - System.out.println(favorite); - System.out.format("Hi %s.%n", name); - System.out.format("In 5 years you will be %d.%n", + System.err.println(age); + System.err.println(favorite); + System.err.format("Hi %s.%n", name); + System.err.format("In 5 years you will be %d.%n", age + 5); - System.out.format("My favorite double is %f.", + System.err.format("My favorite double is %f.", favorite / 2); } } diff --git a/strings/Concatenation.java b/strings/Concatenation.java index 685f4dbb6..c149d38f4 100644 --- a/strings/Concatenation.java +++ b/strings/Concatenation.java @@ -7,7 +7,7 @@ public class Concatenation { public static void main(String[] args) { String mango = "mango"; String s = "abc" + mango + "def" + 47; - System.out.println(s); + System.err.println(s); } } /* Output: diff --git a/strings/Conversion.java b/strings/Conversion.java index f839e81a2..1d2f0fc5c 100644 --- a/strings/Conversion.java +++ b/strings/Conversion.java @@ -10,7 +10,7 @@ public static void main(String[] args) { Formatter f = new Formatter(System.out); char u = 'a'; - System.out.println("u = 'a'"); + System.err.println("u = 'a'"); f.format("s: %s%n", u); // f.format("d: %d%n", u); f.format("c: %c%n", u); @@ -21,7 +21,7 @@ public static void main(String[] args) { f.format("h: %h%n", u); int v = 121; - System.out.println("v = 121"); + System.err.println("v = 121"); f.format("d: %d%n", v); f.format("c: %c%n", v); f.format("b: %b%n", v); @@ -32,7 +32,7 @@ public static void main(String[] args) { f.format("h: %h%n", v); BigInteger w = new BigInteger("50000000000000"); - System.out.println( + System.err.println( "w = new BigInteger(\"50000000000000\")"); f.format("d: %d%n", w); // f.format("c: %c%n", w); @@ -44,7 +44,7 @@ public static void main(String[] args) { f.format("h: %h%n", w); double x = 179.543; - System.out.println("x = 179.543"); + System.err.println("x = 179.543"); // f.format("d: %d%n", x); // f.format("c: %c%n", x); f.format("b: %b%n", x); @@ -55,7 +55,7 @@ public static void main(String[] args) { f.format("h: %h%n", x); Conversion y = new Conversion(); - System.out.println("y = new Conversion()"); + System.err.println("y = new Conversion()"); // f.format("d: %d%n", y); // f.format("c: %c%n", y); f.format("b: %b%n", y); @@ -66,7 +66,7 @@ public static void main(String[] args) { f.format("h: %h%n", y); boolean z = false; - System.out.println("z = false"); + System.err.println("z = false"); // f.format("d: %d%n", z); // f.format("c: %c%n", z); f.format("b: %b%n", z); diff --git a/strings/DatabaseException.java b/strings/DatabaseException.java index e84412546..7f6267c1c 100644 --- a/strings/DatabaseException.java +++ b/strings/DatabaseException.java @@ -13,7 +13,7 @@ public static void main(String[] args) { try { throw new DatabaseException(3, 7, "Write failed"); } catch(Exception e) { - System.out.println(e); + System.err.println(e); } } } diff --git a/strings/Finding.java b/strings/Finding.java index f8d7cbbce..3e6cc7c5e 100644 --- a/strings/Finding.java +++ b/strings/Finding.java @@ -10,13 +10,56 @@ public static void main(String[] args) { .matcher( "Evening is full of the linnet's wings"); while(m.find()) - System.out.print(m.group() + " "); - System.out.println(); + System.err.print(m.group() + " "); + System.err.println(); + int i = 0; while(m.find(i)) { - System.out.print(m.group() + " "); + System.err.print(m.group() + " "); i++; } + + + test(); + } + + + + public static void test() { + Pattern pattern = Pattern.compile("\\d{3,5}"); + String charSequence = "123-34345-234-00"; + Matcher matcher = pattern.matcher(charSequence); + + //虽然匹配失败,但由于charSequence里面的"123"和pattern是匹配的,所以下次的匹配从位置4开始 +// print(matcher.matches()); + //测试匹配位置 + matcher.find(); + matcher.find(); + + print("orginal:"+matcher.start()); + + //使用reset方法重置匹配位置 + matcher.reset(); + + //第一次find匹配以及匹配的目标和匹配的起始位置 + print(matcher.find()); + print(matcher.group()+" - "+matcher.start()); + //第二次find匹配以及匹配的目标和匹配的起始位置 + print(matcher.find()); + print(matcher.group()+" - "+matcher.start()); + + //第一次lookingAt匹配以及匹配的目标和匹配的起始位置 + print(matcher.lookingAt()); + print(matcher.group()+" - "+matcher.start()); + + //第二次lookingAt匹配以及匹配的目标和匹配的起始位置 + print(matcher.lookingAt()); + print(matcher.group()+" - "+matcher.start()); + } + + + public static void print(Object o){ + System.out.println(o); } } /* Output: diff --git a/strings/Groups.java b/strings/Groups.java index 298caf627..1643e81c9 100644 --- a/strings/Groups.java +++ b/strings/Groups.java @@ -20,8 +20,9 @@ public static void main(String[] args) { .matcher(POEM); while(m.find()) { for(int j = 0; j <= m.groupCount(); j++) - System.out.print("[" + m.group(j) + "]"); - System.out.println(); + System.err.print("[" + m.group(j) + "]"); +// System.err.println(m.groupCount()); + System.err.println(); } } } diff --git a/strings/Hex.java b/strings/Hex.java index 0fbcea8e4..ab8ca5604 100644 --- a/strings/Hex.java +++ b/strings/Hex.java @@ -25,11 +25,11 @@ public static String format(byte[] data) { main(String[] args) throws Exception { if(args.length == 0) // Test by displaying this class file: - System.out.println(format( + System.err.println(format( Files.readAllBytes(Paths.get( "build/classes/java/main/onjava/Hex.class")))); else - System.out.println(format( + System.err.println(format( Files.readAllBytes(Paths.get(args[0])))); } } diff --git a/strings/Immutable.java b/strings/Immutable.java index 4c8b529e7..fb3bdfca6 100644 --- a/strings/Immutable.java +++ b/strings/Immutable.java @@ -5,14 +5,19 @@ public class Immutable { public static String upcase(String s) { - return s.toUpperCase(); + System.err.println("内,原:"+System.identityHashCode(s));//self-note: 原引用的拷贝,但指向相同内存地址 + String s1 = s.toUpperCase(); + System.err.println("内,新:"+System.identityHashCode(s1));//self-note:指向了不同的内存地址 + return s1; } public static void main(String[] args) { String q = "howdy"; - System.out.println(q); // howdy + System.err.println(q); // howdy + System.err.println("外:"+System.identityHashCode(q)); + String qq = upcase(q); - System.out.println(qq); // HOWDY - System.out.println(q); // howdy + System.err.println(qq); // HOWDY + System.err.println(q); // howdy } } /* Output: diff --git a/strings/InfiniteRecursion.java b/strings/InfiniteRecursion.java index 6941490a5..dfac313e7 100644 --- a/strings/InfiniteRecursion.java +++ b/strings/InfiniteRecursion.java @@ -15,8 +15,16 @@ public String toString() { " InfiniteRecursion address: " + this + "\n"; } public static void main(String[] args) { - Stream.generate(InfiniteRecursion::new) - .limit(10) - .forEach(System.out::println); + System.err.println( new InfiniteRecursion());//self-note: 神奇现象: 异常递归 + /** + * 因为编译器发现一个 `String` 对象后面跟着一个 “+”,而 “+” 后面的对象不是 `String`, + * 于是编译器试着将 `this` 转换成一个 `String`。它怎么转换呢? + * 正是通过调用 `this` 上的 `toString()` 方法,于是就发生了递归调用。 + */ + + +/* Stream.generate(InfiniteRecursion::new) + .limit(1) + .forEach(System.out::println);*/ } } diff --git a/strings/IntegerMatch.java b/strings/IntegerMatch.java index 5a3a38ac8..7c0672c5a 100644 --- a/strings/IntegerMatch.java +++ b/strings/IntegerMatch.java @@ -5,10 +5,10 @@ public class IntegerMatch { public static void main(String[] args) { - System.out.println("-1234".matches("-?\\d+")); - System.out.println("5678".matches("-?\\d+")); - System.out.println("+911".matches("-?\\d+")); - System.out.println("+911".matches("(-|\\+)?\\d+")); + System.err.println("-1234".matches("-?\\d+")); + System.err.println("5678".matches("-?\\d+")); + System.err.println("+911".matches("-?\\d+")); + System.err.println("+911".matches("(-|\\+)?\\d+")); } } /* Output: diff --git a/strings/JGrep.java b/strings/JGrep.java index 49cec9547..6c61f1a8f 100644 --- a/strings/JGrep.java +++ b/strings/JGrep.java @@ -10,23 +10,19 @@ import java.util.stream.*; public class JGrep { - public static void - main(String[] args) throws Exception { + public static void main(String[] args) throws Exception { if(args.length < 2) { - System.out.println( - "Usage: java JGrep file regex"); + System.out.println("Usage: java JGrep file regex"); System.exit(0); } Pattern p = Pattern.compile(args[1]); // Iterate through the lines of the input file: int index = 0; Matcher m = p.matcher(""); - for(String line : - Files.readAllLines(Paths.get(args[0]))) { + for(String line: Files.readAllLines(Paths.get(args[0]))) { m.reset(line); while(m.find()) - System.out.println(index++ + ": " + - m.group() + ": " + m.start()); + System.out.println(index++ + ": " + m.group() + ": " + m.start()); } } } diff --git a/strings/ReFlags.java b/strings/ReFlags.java index 856806eee..bbf17c41d 100644 --- a/strings/ReFlags.java +++ b/strings/ReFlags.java @@ -2,19 +2,26 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. + import java.util.regex.*; public class ReFlags { - public static void main(String[] args) { - Pattern p = Pattern.compile("^java", - Pattern.CASE_INSENSITIVE | Pattern.MULTILINE); - Matcher m = p.matcher( - "java has regex\nJava has regex\n" + - "JAVA has pretty good regular expressions\n" + - "Regular expressions are in Java"); - while(m.find()) - System.out.println(m.group()); - } + public static void main(String[] args) { + Pattern p = Pattern.compile("^java", + Pattern.CASE_INSENSITIVE + | Pattern.MULTILINE + ); + Matcher m = p.matcher( + "java has regex\n" + + "Java has regex\n" + + "JAVA has pretty good regular expressions\n" + + "Regular expressions are in Java"); //这个不符合^, 开头java + while (m.find()) { + System.err.print(m.end() + "---"); + System.err.println(m.group()); + } + + } } /* Output: java diff --git a/strings/ReceiptBuilder.java b/strings/ReceiptBuilder.java index 234ca1e67..c255175b5 100644 --- a/strings/ReceiptBuilder.java +++ b/strings/ReceiptBuilder.java @@ -33,7 +33,7 @@ public static void main(String[] args) { receiptBuilder.add("Princess Peas", 3, 5.1); receiptBuilder.add( "Three Bears Porridge", 1, 14.29); - System.out.println(receiptBuilder.build()); + System.err.println(receiptBuilder.build()); } } /* Output: diff --git a/strings/Replacing.java b/strings/Replacing.java index dbc21afe2..8c8c25c66 100644 --- a/strings/Replacing.java +++ b/strings/Replacing.java @@ -6,9 +6,9 @@ public class Replacing { static String s = Splitting.knights; public static void main(String[] args) { - System.out.println( + System.err.println( s.replaceFirst("f\\w+", "located")); - System.out.println( + System.err.println( s.replaceAll("shrubbery|tree|herring","banana")); } } diff --git a/strings/ReplacingStringTokenizer.java b/strings/ReplacingStringTokenizer.java index 60fad1848..0531c943d 100644 --- a/strings/ReplacingStringTokenizer.java +++ b/strings/ReplacingStringTokenizer.java @@ -10,13 +10,13 @@ public static void main(String[] args) { "But I'm not dead yet! I feel happy!"; StringTokenizer stoke = new StringTokenizer(input); while(stoke.hasMoreElements()) - System.out.print(stoke.nextToken() + " "); - System.out.println(); - System.out.println( + System.err.print(stoke.nextToken() + " "); + System.err.println(); + System.err.println( Arrays.toString(input.split(" "))); Scanner scanner = new Scanner(input); while(scanner.hasNext()) - System.out.print(scanner.next() + " "); + System.err.print(scanner.next() + " "); } } /* Output: diff --git a/strings/Resetting.java b/strings/Resetting.java index f15653903..497123079 100644 --- a/strings/Resetting.java +++ b/strings/Resetting.java @@ -10,11 +10,11 @@ public class Resetting { Matcher m = Pattern.compile("[frb][aiu][gx]") .matcher("fix the rug with bags"); while(m.find()) - System.out.print(m.group() + " "); - System.out.println(); + System.err.print(m.group() + " "); + System.err.println(); m.reset("fix the rig with rags"); while(m.find()) - System.out.print(m.group() + " "); + System.err.print(m.group() + " "); } } /* Output: diff --git a/strings/Rudolph.java b/strings/Rudolph.java index 7a338510a..be6a31346 100644 --- a/strings/Rudolph.java +++ b/strings/Rudolph.java @@ -10,7 +10,7 @@ public static void main(String[] args) { "[rR]udolph", "[rR][aeiou][a-z]ol.*", "R.*" }) - System.out.println("Rudolph".matches(pattern)); + System.err.println("Rudolph".matches(pattern)); } } /* Output: diff --git a/strings/ScannerDelimiter.java b/strings/ScannerDelimiter.java index a06ed990d..84d8acfa4 100644 --- a/strings/ScannerDelimiter.java +++ b/strings/ScannerDelimiter.java @@ -8,8 +8,9 @@ public class ScannerDelimiter { public static void main(String[] args) { Scanner scanner = new Scanner("12, 42, 78, 99, 42"); scanner.useDelimiter("\\s*,\\s*"); + System.err.println(scanner.delimiter());//返回当前正在作为分隔符使用的 `Pattern` 对象 while(scanner.hasNextInt()) - System.out.println(scanner.nextInt()); + System.err.println(scanner.nextInt()); } } /* Output: diff --git a/strings/SimpleFormat.java b/strings/SimpleFormat.java index a3a6e52fe..7f3fdde20 100644 --- a/strings/SimpleFormat.java +++ b/strings/SimpleFormat.java @@ -8,11 +8,11 @@ public static void main(String[] args) { int x = 5; double y = 5.332542; // The old way: - System.out.println("Row 1: [" + x + " " + y + "]"); + System.err.println("Row 1: [" + x + " " + y + "]"); // The new way: - System.out.format("Row 1: [%d %f]%n", x, y); + System.err.format("Row 1: [%d %f]%n", x, y); // or - System.out.printf("Row 1: [%d %f]%n", x, y); + System.err.printf("Row 1: [%d %f]%n", x, y); } } /* Output: diff --git a/strings/SimpleRead.java b/strings/SimpleRead.java index e85a058a5..ca47a8d3a 100644 --- a/strings/SimpleRead.java +++ b/strings/SimpleRead.java @@ -5,26 +5,23 @@ import java.io.*; public class SimpleRead { - public static BufferedReader input = - new BufferedReader(new StringReader( - "Sir Robin of Camelot\n22 1.61803")); + public static BufferedReader input = new BufferedReader(new StringReader("Sir Robin of Camelot\n22 1.61803")); public static void main(String[] args) { try { - System.out.println("What is your name?"); + System.err.println("What is your name?"); String name = input.readLine(); - System.out.println(name); - System.out.println("How old are you? " + - "What is your favorite double?"); - System.out.println("(input: )"); + System.err.println(name); + System.err.println("How old are you? " + "What is your favorite double?"); + System.err.println("(input: )"); String numbers = input.readLine(); - System.out.println(numbers); + System.err.println(numbers); String[] numArray = numbers.split(" "); int age = Integer.parseInt(numArray[0]); double favorite = Double.parseDouble(numArray[1]); - System.out.format("Hi %s.%n", name); - System.out.format("In 5 years you will be %d.%n", + System.err.format("Hi %s.%n", name); + System.err.format("In 5 years you will be %d.%n", age + 5); - System.out.format("My favorite double is %f.", + System.err.format("My favorite double is %f.", favorite / 2); } catch(IOException e) { System.err.println("I/O exception"); diff --git a/strings/SplitDemo.java b/strings/SplitDemo.java index 657453922..68054c1a7 100644 --- a/strings/SplitDemo.java +++ b/strings/SplitDemo.java @@ -9,10 +9,10 @@ public class SplitDemo { public static void main(String[] args) { String input = "This!!unusual use!!of exclamation!!points"; - System.out.println(Arrays.toString( + System.err.println(Arrays.toString( Pattern.compile("!!").split(input))); // Only do the first three: - System.out.println(Arrays.toString( + System.err.println(Arrays.toString( Pattern.compile("!!").split(input, 3))); } } diff --git a/strings/Splitting.java b/strings/Splitting.java index 0afe3a402..e0a4bf85d 100644 --- a/strings/Splitting.java +++ b/strings/Splitting.java @@ -10,7 +10,7 @@ public class Splitting { "you must cut down the mightiest tree in the " + "forest...with... a herring!"; public static void split(String regex) { - System.out.println( + System.err.println( Arrays.toString(knights.split(regex))); } public static void main(String[] args) { diff --git a/strings/StartEnd.java b/strings/StartEnd.java index 03caf520c..596660509 100644 --- a/strings/StartEnd.java +++ b/strings/StartEnd.java @@ -18,10 +18,10 @@ private static class Display { Display(String regex) { this.regex = regex; } void display(String message) { if(!regexPrinted) { - System.out.println(regex); + System.err.println("模式---------"+regex); regexPrinted = true; } - System.out.println(message); + System.err.println(message); } } static void examine(String s, String regex) { @@ -40,8 +40,8 @@ static void examine(String s, String regex) { } public static void main(String[] args) { for(String in : input.split("\n")) { - System.out.println("input : " + in); - for(String regex : new String[]{"\\w*ere\\w*", + System.err.println("input : " + in); + for(String regex : new String[]{"A\\w*","\\w*ere\\w*", "\\w*ever", "T\\w+", "Never.*?!"}) examine(in, regex); } diff --git a/strings/TestRegularExpression.java b/strings/TestRegularExpression.java index fe79ce8b2..905344019 100644 --- a/strings/TestRegularExpression.java +++ b/strings/TestRegularExpression.java @@ -5,29 +5,29 @@ // Simple regular expression demonstration // {java TestRegularExpression // abcabcabcdefabc "abc+" "(abc)+" } + import java.util.regex.*; public class TestRegularExpression { - public static void main(String[] args) { - if(args.length < 2) { - System.out.println( - "Usage:\njava TestRegularExpression " + - "characterSequence regularExpression+"); - System.exit(0); - } - System.out.println("Input: \"" + args[0] + "\""); - for(String arg : args) { - System.out.println( - "Regular expression: \"" + arg + "\""); - Pattern p = Pattern.compile(arg); - Matcher m = p.matcher(args[0]); - while(m.find()) { - System.out.println( - "Match \"" + m.group() + "\" at positions " + - m.start() + "-" + (m.end() - 1)); - } + public static void main(String[] args) { + if (args.length < 2) { + System.err.println( + "Usage:\njava TestRegularExpression " + "characterSequence regularExpression+"); + System.exit(0); + } + System.err.println("Input: \"" + args[0] + "\""); + for (String arg : args) { + System.err.println( + "Regular expression: \"" + arg + "\""+"---------------"); + Pattern p = Pattern.compile(arg); + Matcher m = p.matcher(args[0]); + while (m.find()) { + System.err.println( + "Match \"" + m.group() + "\" at positions " + + m.start() + "-" + (m.end() - 1)); + } + } } - } } /* Output: Input: "abcabcabcdefabc" diff --git a/strings/TheReplacements.java b/strings/TheReplacements.java index 2319552fe..410b46a9d 100644 --- a/strings/TheReplacements.java +++ b/strings/TheReplacements.java @@ -16,7 +16,7 @@ public class TheReplacements { public static void main(String[] args) throws Exception { String s = Files.lines( - Paths.get("TheReplacements.java")) + Paths.get("./strings/TheReplacements.java")) .collect(Collectors.joining("\n")); // Match specially commented block of text above: Matcher mInput = Pattern.compile( @@ -28,7 +28,7 @@ public class TheReplacements { // Replace 1+ spaces at the beginning of each // line with no spaces. Must enable MULTILINE mode: s = s.replaceAll("(?m)^ +", ""); - System.out.println(s); + System.err.println(s); s = s.replaceFirst("[aeiou]", "(VOWEL1)"); StringBuffer sbuf = new StringBuffer(); Pattern p = Pattern.compile("[aeiou]"); @@ -40,7 +40,7 @@ public class TheReplacements { sbuf, m.group().toUpperCase()); // Put in the remainder of the text: m.appendTail(sbuf); - System.out.println(sbuf); + System.err.println(sbuf); } } /* Output: diff --git a/strings/ThreatAnalyzer.java b/strings/ThreatAnalyzer.java index fc145c86e..f59698ef3 100644 --- a/strings/ThreatAnalyzer.java +++ b/strings/ThreatAnalyzer.java @@ -22,7 +22,7 @@ public static void main(String[] args) { MatchResult match = scanner.match(); String ip = match.group(1); String date = match.group(2); - System.out.format( + System.err.format( "Threat on %s from %s%n", date,ip); } } diff --git a/strings/UsingStringBuilder.java b/strings/UsingStringBuilder.java index 0ff324102..718656e4b 100644 --- a/strings/UsingStringBuilder.java +++ b/strings/UsingStringBuilder.java @@ -25,8 +25,8 @@ public static String string2() { return "[" + result + "]"; } public static void main(String[] args) { - System.out.println(string1()); - System.out.println(string2()); + System.err.println(string1()); + System.err.println(string2()); } } /* Output: diff --git a/typeinfo/AnonymousImplementation.java b/typeinfo/AnonymousImplementation.java index 34fa7832c..7624fc897 100644 --- a/typeinfo/AnonymousImplementation.java +++ b/typeinfo/AnonymousImplementation.java @@ -9,19 +9,19 @@ class AnonymousA { public static A makeA() { return new A() { public void f() { - System.out.println("public C.f()"); + System.err.println("public C.f()"); } public void g() { - System.out.println("public C.g()"); + System.err.println("public C.g()"); } void u() { - System.out.println("package C.u()"); + System.err.println("package C.u()"); } protected void v() { - System.out.println("protected C.v()"); + System.err.println("protected C.v()"); } private void w() { - System.out.println("private C.w()"); + System.err.println("private C.w()"); } }; } @@ -32,7 +32,7 @@ public class AnonymousImplementation { main(String[] args) throws Exception { A a = AnonymousA.makeA(); a.f(); - System.out.println(a.getClass().getName()); + System.err.println(a.getClass().getName()); // Reflection still gets into the anonymous class: HiddenImplementation.callHiddenMethod(a, "g"); HiddenImplementation.callHiddenMethod(a, "u"); diff --git a/typeinfo/ClassInitialization.java b/typeinfo/ClassInitialization.java index ba1d50e81..1dfe6c573 100644 --- a/typeinfo/ClassInitialization.java +++ b/typeinfo/ClassInitialization.java @@ -9,39 +9,41 @@ class Initable { static final int STATIC_FINAL2 = ClassInitialization.rand.nextInt(1000); static { - System.out.println("Initializing Initable"); + System.err.println("Initializing Initable"); } } class Initable2 { static int staticNonFinal = 147; static { - System.out.println("Initializing Initable2"); + System.err.println("Initializing Initable2"); } } class Initable3 { static int staticNonFinal = 74; static { - System.out.println("Initializing Initable3"); + System.err.println("Initializing Initable3"); } } public class ClassInitialization { public static Random rand = new Random(47); - public static void - main(String[] args) throws Exception { + public static void main(String[] args) throws Exception { Class initable = Initable.class; - System.out.println("After creating Initable ref"); + System.err.println("After creating Initable ref"); // Does not trigger initialization: - System.out.println(Initable.STATIC_FINAL); + System.err.println(Initable.STATIC_FINAL); + System.err.println(); + System.err.println(); + // Does trigger initialization: - System.out.println(Initable.STATIC_FINAL2); + System.err.println(Initable.STATIC_FINAL2); // Does trigger initialization: - System.out.println(Initable2.staticNonFinal); + System.err.println(Initable2.staticNonFinal); Class initable3 = Class.forName("Initable3"); - System.out.println("After creating Initable3 ref"); - System.out.println(Initable3.staticNonFinal); + System.err.println("After creating Initable3 ref"); + System.err.println(Initable3.staticNonFinal); } } /* Output: diff --git a/typeinfo/DynamicSupplier.java b/typeinfo/DynamicSupplier.java index 271af6399..60a8fc221 100644 --- a/typeinfo/DynamicSupplier.java +++ b/typeinfo/DynamicSupplier.java @@ -17,7 +17,7 @@ public class DynamicSupplier implements Supplier { public DynamicSupplier(Class type) { this.type = type; } - @SuppressWarnings("deprecation") + @Override public T get() { try { return type.newInstance(); diff --git a/typeinfo/FamilyVsExactType.java b/typeinfo/FamilyVsExactType.java index 5981bbe63..afb8725bd 100644 --- a/typeinfo/FamilyVsExactType.java +++ b/typeinfo/FamilyVsExactType.java @@ -11,27 +11,27 @@ class Derived extends Base {} public class FamilyVsExactType { static void test(Object x) { - System.out.println( + System.err.println( "Testing x of type " + x.getClass()); - System.out.println( + System.err.println( "x instanceof Base " + (x instanceof Base)); - System.out.println( + System.err.println( "x instanceof Derived " + (x instanceof Derived)); - System.out.println( + System.err.println( "Base.isInstance(x) " + Base.class.isInstance(x)); - System.out.println( + System.err.println( "Derived.isInstance(x) " + Derived.class.isInstance(x)); - System.out.println( + System.err.println( "x.getClass() == Base.class " + (x.getClass() == Base.class)); - System.out.println( + System.err.println( "x.getClass() == Derived.class " + (x.getClass() == Derived.class)); - System.out.println( + System.err.println( "x.getClass().equals(Base.class)) "+ (x.getClass().equals(Base.class))); - System.out.println( + System.err.println( "x.getClass().equals(Derived.class)) " + (x.getClass().equals(Derived.class))); } diff --git a/typeinfo/HiddenImplementation.java b/typeinfo/HiddenImplementation.java index 7b41f6575..186b227cb 100644 --- a/typeinfo/HiddenImplementation.java +++ b/typeinfo/HiddenImplementation.java @@ -12,7 +12,7 @@ public class HiddenImplementation { main(String[] args) throws Exception { A a = HiddenC.makeA(); a.f(); - System.out.println(a.getClass().getName()); + System.err.println(a.getClass().getName()); // Compile error: cannot find symbol 'C': /* if(a instanceof C) { C c = (C)a; diff --git a/typeinfo/InnerImplementation.java b/typeinfo/InnerImplementation.java index 2b6541fa5..4ba75d711 100644 --- a/typeinfo/InnerImplementation.java +++ b/typeinfo/InnerImplementation.java @@ -8,19 +8,19 @@ class InnerA { private static class C implements A { public void f() { - System.out.println("public C.f()"); + System.err.println("public C.f()"); } public void g() { - System.out.println("public C.g()"); + System.err.println("public C.g()"); } void u() { - System.out.println("package C.u()"); + System.err.println("package C.u()"); } protected void v() { - System.out.println("protected C.v()"); + System.err.println("protected C.v()"); } private void w() { - System.out.println("private C.w()"); + System.err.println("private C.w()"); } } public static A makeA() { return new C(); } @@ -31,7 +31,7 @@ public class InnerImplementation { main(String[] args) throws Exception { A a = InnerA.makeA(); a.f(); - System.out.println(a.getClass().getName()); + System.err.println(a.getClass().getName()); // Reflection still gets into the private class: HiddenImplementation.callHiddenMethod(a, "g"); HiddenImplementation.callHiddenMethod(a, "u"); diff --git a/typeinfo/InterfaceViolation.java b/typeinfo/InterfaceViolation.java index 06b13f65c..42a1af340 100644 --- a/typeinfo/InterfaceViolation.java +++ b/typeinfo/InterfaceViolation.java @@ -15,7 +15,7 @@ public static void main(String[] args) { A a = new B(); a.f(); // a.g(); // Compile error - System.out.println(a.getClass().getName()); + System.err.println(a.getClass().getName()); if(a instanceof B) { B b = (B)a; b.g(); diff --git a/typeinfo/ModifyingPrivateFields.java b/typeinfo/ModifyingPrivateFields.java index fa1a175d8..9315d5c35 100644 --- a/typeinfo/ModifyingPrivateFields.java +++ b/typeinfo/ModifyingPrivateFields.java @@ -19,23 +19,23 @@ public class ModifyingPrivateFields { main(String[] args) throws Exception { WithPrivateFinalField pf = new WithPrivateFinalField(); - System.out.println(pf); + System.err.println(pf); Field f = pf.getClass().getDeclaredField("i"); f.setAccessible(true); - System.out.println( + System.err.println( "f.getInt(pf): " + f.getInt(pf)); f.setInt(pf, 47); - System.out.println(pf); + System.err.println(pf); f = pf.getClass().getDeclaredField("s"); f.setAccessible(true); - System.out.println("f.get(pf): " + f.get(pf)); + System.err.println("f.get(pf): " + f.get(pf)); f.set(pf, "No, you're not!"); - System.out.println(pf); + System.err.println(pf); f = pf.getClass().getDeclaredField("s2"); f.setAccessible(true); - System.out.println("f.get(pf): " + f.get(pf)); + System.err.println("f.get(pf): " + f.get(pf)); f.set(pf, "No, you're not!"); - System.out.println(pf); + System.err.println(pf); } } /* Output: diff --git a/typeinfo/Person.java b/typeinfo/Person.java index 7a9807c0c..f805c8019 100644 --- a/typeinfo/Person.java +++ b/typeinfo/Person.java @@ -34,10 +34,10 @@ public String toString() { " " + address.orElse("")).trim(); } public static void main(String[] args) { - System.out.println(new Person()); - System.out.println(new Person("Smith")); - System.out.println(new Person("Bob", "Smith")); - System.out.println(new Person("Bob", "Smith", + System.err.println(new Person()); + System.err.println(new Person("Smith")); + System.err.println(new Person("Bob", "Smith")); + System.err.println(new Person("Bob", "Smith", "11 Degree Lane, Frostbite Falls, MN")); } } diff --git a/typeinfo/PetCount.java b/typeinfo/PetCount.java index 53438d29a..72341c7eb 100644 --- a/typeinfo/PetCount.java +++ b/typeinfo/PetCount.java @@ -21,7 +21,7 @@ public void count(String type) { Counter counter = new Counter(); for(Pet pet : Pets.array(20)) { // List each individual pet: - System.out.print( + System.err.print( pet.getClass().getSimpleName() + " "); if(pet instanceof Pet) counter.count("Pet"); @@ -49,8 +49,8 @@ public void count(String type) { counter.count("Hamster"); } // Show the counts: - System.out.println(); - System.out.println(counter); + System.err.println(); + System.err.println(counter); } public static void main(String[] args) { countPets(new ForNameCreator()); diff --git a/typeinfo/PetCount3.java b/typeinfo/PetCount3.java index 5b08fb660..f72b91e11 100644 --- a/typeinfo/PetCount3.java +++ b/typeinfo/PetCount3.java @@ -39,9 +39,9 @@ public static void main(String[] args) { Pets.stream() .limit(20) .peek(petCount::count) - .forEach(p -> System.out.print( + .forEach(p -> System.err.print( p.getClass().getSimpleName() + " ")); - System.out.println("\n" + petCount); + System.err.println("\n" + petCount); } } /* Output: diff --git a/typeinfo/PetCount4.java b/typeinfo/PetCount4.java index 1ea4873ac..d304d7064 100644 --- a/typeinfo/PetCount4.java +++ b/typeinfo/PetCount4.java @@ -11,9 +11,9 @@ public static void main(String[] args) { Pets.stream() .limit(20) .peek(counter::count) - .forEach(p -> System.out.print( + .forEach(p -> System.err.print( p.getClass().getSimpleName() + " ")); - System.out.println("\n" + counter); + System.err.println("\n" + counter); } } /* Output: diff --git a/typeinfo/Position.java b/typeinfo/Position.java index ca81643b0..4b26e2e50 100644 --- a/typeinfo/Position.java +++ b/typeinfo/Position.java @@ -34,13 +34,13 @@ public String toString() { ", Employee: " + person; } public static void main(String[] args) { - System.out.println(new Position("CEO")); - System.out.println(new Position("Programmer", + System.err.println(new Position("CEO")); + System.err.println(new Position("Programmer", new Person("Arthur", "Fonzarelli"))); try { new Position(null); } catch(Exception e) { - System.out.println("caught " + e); + System.err.println("caught " + e); } } } diff --git a/typeinfo/Robot.java b/typeinfo/Robot.java index 803ee9fe2..3ff54dad6 100644 --- a/typeinfo/Robot.java +++ b/typeinfo/Robot.java @@ -11,11 +11,11 @@ public interface Robot { List operations(); static void test(Robot r) { if(r instanceof Null) - System.out.println("[Null Robot]"); - System.out.println("Robot name: " + r.name()); - System.out.println("Robot model: " + r.model()); + System.err.println("[Null Robot]"); + System.err.println("Robot name: " + r.name()); + System.err.println("Robot model: " + r.model()); for(Operation operation : r.operations()) { - System.out.println(operation.description.get()); + System.err.println(operation.description.get()); operation.command.run(); } } diff --git a/typeinfo/SelectingMethods.java b/typeinfo/SelectingMethods.java index d87e928bc..4779ef3f9 100644 --- a/typeinfo/SelectingMethods.java +++ b/typeinfo/SelectingMethods.java @@ -15,7 +15,7 @@ class MethodSelector implements InvocationHandler { invoke(Object proxy, Method method, Object[] args) throws Throwable { if(method.getName().equals("interesting")) - System.out.println( + System.err.println( "Proxy detected the interesting method"); return method.invoke(proxied, args); } @@ -31,19 +31,19 @@ interface SomeMethods { class Implementation implements SomeMethods { @Override public void boring1() { - System.out.println("boring1"); + System.err.println("boring1"); } @Override public void boring2() { - System.out.println("boring2"); + System.err.println("boring2"); } @Override public void interesting(String arg) { - System.out.println("interesting " + arg); + System.err.println("interesting " + arg); } @Override public void boring3() { - System.out.println("boring3"); + System.err.println("boring3"); } } diff --git a/typeinfo/Shapes.java b/typeinfo/Shapes.java index 34a2bc561..0bc0d66ab 100644 --- a/typeinfo/Shapes.java +++ b/typeinfo/Shapes.java @@ -5,7 +5,7 @@ import java.util.stream.*; abstract class Shape { - void draw() { System.out.println(this + ".draw()"); } + void draw() { System.err.println(this + ".draw()"); } @Override public abstract String toString(); } diff --git a/typeinfo/ShowMethods.java b/typeinfo/ShowMethods.java index be1b635b0..4d297758b 100644 --- a/typeinfo/ShowMethods.java +++ b/typeinfo/ShowMethods.java @@ -18,7 +18,7 @@ public class ShowMethods { private static Pattern p = Pattern.compile("\\w+\\."); public static void main(String[] args) { if(args.length < 1) { - System.out.println(usage); + System.err.println(usage); System.exit(0); } int lines = 0; @@ -28,29 +28,29 @@ public static void main(String[] args) { Constructor[] ctors = c.getConstructors(); if(args.length == 1) { for(Method method : methods) - System.out.println( + System.err.println( p.matcher( method.toString()).replaceAll("")); for(Constructor ctor : ctors) - System.out.println( + System.err.println( p.matcher(ctor.toString()).replaceAll("")); lines = methods.length + ctors.length; } else { for(Method method : methods) if(method.toString().contains(args[1])) { - System.out.println(p.matcher( + System.err.println(p.matcher( method.toString()).replaceAll("")); lines++; } for(Constructor ctor : ctors) if(ctor.toString().contains(args[1])) { - System.out.println(p.matcher( + System.err.println(p.matcher( ctor.toString()).replaceAll("")); lines++; } } } catch(ClassNotFoundException e) { - System.out.println("No such class: " + e); + System.err.println("No such class: " + e); } } } diff --git a/typeinfo/SimpleDynamicProxy.java b/typeinfo/SimpleDynamicProxy.java index bece57f8a..946db7324 100644 --- a/typeinfo/SimpleDynamicProxy.java +++ b/typeinfo/SimpleDynamicProxy.java @@ -13,12 +13,12 @@ class DynamicProxyHandler implements InvocationHandler { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - System.out.println( + System.err.println( "**** proxy: " + proxy.getClass() + ", method: " + method + ", args: " + args); if(args != null) for(Object arg : args) - System.out.println(" " + arg); + System.err.println(" " + arg); return method.invoke(proxied, args); } } diff --git a/typeinfo/SimpleProxyDemo.java b/typeinfo/SimpleProxyDemo.java index 24c3c2c25..3778498fd 100644 --- a/typeinfo/SimpleProxyDemo.java +++ b/typeinfo/SimpleProxyDemo.java @@ -11,11 +11,11 @@ interface Interface { class RealObject implements Interface { @Override public void doSomething() { - System.out.println("doSomething"); + System.err.println("doSomething"); } @Override public void somethingElse(String arg) { - System.out.println("somethingElse " + arg); + System.err.println("somethingElse " + arg); } } @@ -26,12 +26,12 @@ class SimpleProxy implements Interface { } @Override public void doSomething() { - System.out.println("SimpleProxy doSomething"); + System.err.println("SimpleProxy doSomething"); proxied.doSomething(); } @Override public void somethingElse(String arg) { - System.out.println( + System.err.println( "SimpleProxy somethingElse " + arg); proxied.somethingElse(arg); } diff --git a/typeinfo/SnowRemovalRobot.java b/typeinfo/SnowRemovalRobot.java index af5b46cd9..236196a26 100644 --- a/typeinfo/SnowRemovalRobot.java +++ b/typeinfo/SnowRemovalRobot.java @@ -16,14 +16,14 @@ public SnowRemovalRobot(String name) { private List ops = Arrays.asList( new Operation( () -> name + " can shovel snow", - () -> System.out.println( + () -> System.err.println( name + " shoveling snow")), new Operation( () -> name + " can chip ice", - () -> System.out.println(name + " chipping ice")), + () -> System.err.println(name + " chipping ice")), new Operation( () -> name + " can clear the roof", - () -> System.out.println( + () -> System.err.println( name + " clearing roof"))); public List operations() { return ops; } public static void main(String[] args) { diff --git a/typeinfo/Staff.java b/typeinfo/Staff.java index 569e598f7..7e25efbdf 100644 --- a/typeinfo/Staff.java +++ b/typeinfo/Staff.java @@ -45,7 +45,7 @@ public static void main(String[] args) { staff.fillPosition("Software Engineer", new Person( "Bob", "Coder", "Bright Light City")); - System.out.println(staff); + System.err.println(staff); } } /* Output: diff --git a/typeinfo/SweetShop.java b/typeinfo/SweetShop.java index f85b8c3f9..25bd96a4c 100644 --- a/typeinfo/SweetShop.java +++ b/typeinfo/SweetShop.java @@ -5,30 +5,30 @@ // Examination of the way the class loader works class Cookie { - static { System.out.println("Loading Cookie"); } + static { System.err.println("Loading Cookie"); } } class Gum { - static { System.out.println("Loading Gum"); } + static { System.err.println("Loading Gum"); } } class Candy { - static { System.out.println("Loading Candy"); } + static { System.err.println("Loading Candy"); } } public class SweetShop { public static void main(String[] args) { - System.out.println("inside main"); + System.err.println("inside main"); new Candy(); - System.out.println("After creating Candy"); + System.err.println("After creating Candy"); try { Class.forName("Gum"); } catch(ClassNotFoundException e) { - System.out.println("Couldn't find Gum"); + System.err.println("Couldn't find Gum"); } - System.out.println("After Class.forName(\"Gum\")"); + System.err.println("After Class.forName(\"Gum\")"); new Cookie(); - System.out.println("After creating Cookie"); + System.err.println("After creating Cookie"); } } /* Output: diff --git a/typeinfo/packageaccess/HiddenC.java b/typeinfo/packageaccess/HiddenC.java index 9fb8ffde9..37558d3b5 100644 --- a/typeinfo/packageaccess/HiddenC.java +++ b/typeinfo/packageaccess/HiddenC.java @@ -8,19 +8,19 @@ class C implements A { @Override public void f() { - System.out.println("public C.f()"); + System.err.println("public C.f()"); } public void g() { - System.out.println("public C.g()"); + System.err.println("public C.g()"); } void u() { - System.out.println("package C.u()"); + System.err.println("package C.u()"); } protected void v() { - System.out.println("protected C.v()"); + System.err.println("protected C.v()"); } private void w() { - System.out.println("private C.w()"); + System.err.println("private C.w()"); } } diff --git a/typeinfo/pets/LiteralPetCreator.java b/typeinfo/pets/LiteralPetCreator.java index 398baac8c..590252565 100644 --- a/typeinfo/pets/LiteralPetCreator.java +++ b/typeinfo/pets/LiteralPetCreator.java @@ -27,7 +27,7 @@ public List> types() { return TYPES; } public static void main(String[] args) { - System.out.println(TYPES); + System.err.println(TYPES); } } /* Output: diff --git a/typeinfo/toys/GenericToyTest.java b/typeinfo/toys/GenericToyTest.java index 7dc016cdc..ee03189fa 100644 --- a/typeinfo/toys/GenericToyTest.java +++ b/typeinfo/toys/GenericToyTest.java @@ -10,13 +10,13 @@ public class GenericToyTest { @SuppressWarnings("deprecation") public static void main(String[] args) throws Exception { - Class ftClass = FancyToy.class; + Class ftClass = typeinfo.toys.FancyToy.class; // Produces exact type: - FancyToy fancyToy = ftClass.newInstance(); - Class up = + typeinfo.toys.FancyToy fancyToy = ftClass.newInstance(); + Class up = ftClass.getSuperclass(); // This won't compile: - // Class up2 = ftClass.getSuperclass(); + Class up2 = (Class) ftClass.getSuperclass(); // Only produces Object: Object obj = up.newInstance(); } diff --git a/typeinfo/toys/ToyTest.java b/typeinfo/toys/ToyTest.java index e4e5e92db..98794b657 100644 --- a/typeinfo/toys/ToyTest.java +++ b/typeinfo/toys/ToyTest.java @@ -25,11 +25,11 @@ class FancyToy extends Toy public class ToyTest { static void printInfo(Class cc) { - System.out.println("Class name: " + cc.getName() + + System.err.println("Class name: " + cc.getName() + " is interface? [" + cc.isInterface() + "]"); - System.out.println( + System.err.println( "Simple name: " + cc.getSimpleName()); - System.out.println( + System.err.println( "Canonical name : " + cc.getCanonicalName()); } @SuppressWarnings("deprecation") @@ -38,12 +38,15 @@ public static void main(String[] args) { try { c = Class.forName("typeinfo.toys.FancyToy"); } catch(ClassNotFoundException e) { - System.out.println("Can't find FancyToy"); + System.err.println("Can't find FancyToy"); System.exit(1); } printInfo(c); + System.err.println("-------------------------------------------------------"); for(Class face : c.getInterfaces()) printInfo(face); + System.err.println("-------------------------------------------------------"); + Class up = c.getSuperclass(); Object obj = null; try { @@ -57,16 +60,13 @@ public static void main(String[] args) { } } /* Output: -Class name: typeinfo.toys.FancyToy is interface? -[false] +Class name: typeinfo.toys.FancyToy is interface? [false] Simple name: FancyToy Canonical name : typeinfo.toys.FancyToy -Class name: typeinfo.toys.HasBatteries is interface? -[true] +Class name: typeinfo.toys.HasBatteries is interface? [true] Simple name: HasBatteries Canonical name : typeinfo.toys.HasBatteries -Class name: typeinfo.toys.Waterproof is interface? -[true] +Class name: typeinfo.toys.Waterproof is interface? [true] Simple name: Waterproof Canonical name : typeinfo.toys.Waterproof Class name: typeinfo.toys.Shoots is interface? [true] diff --git a/validating/BadMicroBenchmark.java b/validating/BadMicroBenchmark.java index 2634e67c9..02d093c9c 100644 --- a/validating/BadMicroBenchmark.java +++ b/validating/BadMicroBenchmark.java @@ -11,14 +11,14 @@ public class BadMicroBenchmark { public static void main(String[] args) { try { // For machines with insufficient memory long[] la = new long[SIZE]; - System.out.println("setAll: " + + System.err.println("setAll: " + Timer.duration(() -> Arrays.setAll(la, n -> n))); - System.out.println("parallelSetAll: " + + System.err.println("parallelSetAll: " + Timer.duration(() -> Arrays.parallelSetAll(la, n -> n))); } catch(OutOfMemoryError e) { - System.out.println("Insufficient memory"); + System.err.println("Insufficient memory"); System.exit(0); } } diff --git a/validating/BadMicroBenchmark2.java b/validating/BadMicroBenchmark2.java index 123036a0c..a426e0fb7 100644 --- a/validating/BadMicroBenchmark2.java +++ b/validating/BadMicroBenchmark2.java @@ -3,29 +3,23 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Relying on a common resource + import java.util.*; -import onjava.Timer; +//import onjava.Timer; public class BadMicroBenchmark2 { - // SIZE reduced to make it run faster: - static final int SIZE = 5_000_000; - public static void main(String[] args) { - long[] la = new long[SIZE]; - Random r = new Random(); - System.out.println("parallelSetAll: " + - Timer.duration(() -> - Arrays.parallelSetAll(la, n -> r.nextLong()))); - System.out.println("setAll: " + - Timer.duration(() -> - Arrays.setAll(la, n -> r.nextLong()))); - SplittableRandom sr = new SplittableRandom(); - System.out.println("parallelSetAll: " + - Timer.duration(() -> - Arrays.parallelSetAll(la, n -> sr.nextLong()))); - System.out.println("setAll: " + - Timer.duration(() -> - Arrays.setAll(la, n -> sr.nextLong()))); - } + // SIZE reduced to make it run faster: + static final int SIZE = 5_000_000; + + public static void main(String[] args) { + long[] la = new long[SIZE]; + Random r = new Random(); + System.out.println("parallelSetAll: " + Timer.duration(() -> Arrays.parallelSetAll(la, n -> r.nextLong()))); + System.out.println("setAll: " + Timer.duration(() -> Arrays.setAll(la, n -> r.nextLong()))); + SplittableRandom sr = new SplittableRandom(); + System.out.println("parallelSetAll: " + Timer.duration(() -> Arrays.parallelSetAll(la, n -> sr.nextLong()))); + System.out.println("setAll: " + Timer.duration(() -> Arrays.setAll(la, n -> sr.nextLong()))); + } } /* Output: parallelSetAll: 1147 diff --git a/validating/CircularQueue.java b/validating/CircularQueue.java index 405e44101..0e68c5f88 100644 --- a/validating/CircularQueue.java +++ b/validating/CircularQueue.java @@ -3,8 +3,10 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Demonstration of Design by Contract (DbC) -package validating; -import java.util.*; +//package validating; +//import java.util.*; + +import java.util.Arrays; public class CircularQueue { private Object[] data; @@ -55,13 +57,11 @@ assert postcondition( return returnVal; } // Design-by-contract support methods: - private static void - precondition(boolean cond, String msg) { - if(!cond) throw new CircularQueueException(msg); + private static void precondition(boolean cond, String msg) { + if(!cond) throw new CircularQueueException(msg); } - private static boolean - postcondition(boolean cond, String msg) { - if(!cond) throw new CircularQueueException(msg); + private static boolean postcondition(boolean cond, String msg) { + if(!cond) throw new CircularQueueException(msg); return true; } private boolean invariant() { @@ -69,14 +69,14 @@ private boolean invariant() { // region of 'data' that holds objects: for(int i = out; i != in; i = (i + 1) % data.length) if(data[i] == null) - throw new CircularQueueException( + throw new CircularQueueException( "null in CircularQueue"); // Guarantee that only null values are outside the // region of 'data' that holds objects: if(full()) return true; for(int i = in; i != out; i = (i + 1) % data.length) if(data[i] != null) - throw new CircularQueueException( + throw new CircularQueueException( "non-null outside of CircularQueue range: " + dump()); return true; diff --git a/validating/CircularQueueException.java b/validating/CircularQueueException.java index 142b8ece2..5fa7a2e24 100644 --- a/validating/CircularQueueException.java +++ b/validating/CircularQueueException.java @@ -2,7 +2,7 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -package validating; +//package validating; public class CircularQueueException extends RuntimeException { diff --git a/validating/CountedList.java b/validating/CountedList.java index 6c780f216..93653478d 100644 --- a/validating/CountedList.java +++ b/validating/CountedList.java @@ -3,14 +3,14 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Keeps track of how many of itself are created. -package validating; +//package validating; import java.util.*; public class CountedList extends ArrayList { private static int counter = 0; private int id = counter++; public CountedList() { - System.out.println("CountedList #" + id); + System.err.println("CountedList #" + id); } public int getId() { return id; } } diff --git a/validating/GuavaAssertions.java b/validating/GuavaAssertions.java index a499f079b..9ab625a09 100644 --- a/validating/GuavaAssertions.java +++ b/validating/GuavaAssertions.java @@ -12,17 +12,17 @@ public static void main(String[] args) { try { verify(1 + 2 == 4); } catch(VerifyException e) { - System.out.println(e); + System.err.println(e); } try { verify(1 + 2 == 4, "Bad math"); } catch(VerifyException e) { - System.out.println(e.getMessage()); + System.err.println(e.getMessage()); } try { verify(1 + 2 == 4, "Bad math: %s", "not 4"); } catch(VerifyException e) { - System.out.println(e.getMessage()); + System.err.println(e.getMessage()); } String s = ""; s = verifyNotNull(s); @@ -30,13 +30,13 @@ public static void main(String[] args) { try { verifyNotNull(s); } catch(VerifyException e) { - System.out.println(e.getMessage()); + System.err.println(e.getMessage()); } try { verifyNotNull( s, "Shouldn't be null: %s", "arg s"); } catch(VerifyException e) { - System.out.println(e.getMessage()); + System.err.println(e.getMessage()); } } } diff --git a/validating/GuavaPreconditions.java b/validating/GuavaPreconditions.java index 3cfc66ae9..9320c64ba 100644 --- a/validating/GuavaPreconditions.java +++ b/validating/GuavaPreconditions.java @@ -9,13 +9,13 @@ public class GuavaPreconditions { static void test(Consumer c, String s) { try { - System.out.println(s); + System.err.println(s); c.accept(s); - System.out.println("Success"); + System.err.println("Success"); } catch(Exception e) { String type = e.getClass().getSimpleName(); String msg = e.getMessage(); - System.out.println(type + + System.err.println(type + (msg == null ? "" : ": " + msg)); } } diff --git a/validating/Inverter1.java b/validating/Inverter1.java index 8ef828d6e..7688dc045 100644 --- a/validating/Inverter1.java +++ b/validating/Inverter1.java @@ -2,7 +2,7 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -package validating; +//package validating; public class Inverter1 implements StringInverter { public String invert(String str) { return str; } diff --git a/validating/Inverter2.java b/validating/Inverter2.java index 3fb862fd4..a2368be5f 100644 --- a/validating/Inverter2.java +++ b/validating/Inverter2.java @@ -2,7 +2,7 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -package validating; +//package validating; import static java.lang.Character.*; public class Inverter2 implements StringInverter { diff --git a/validating/Inverter3.java b/validating/Inverter3.java index 4bd53c82a..2dda3b48e 100644 --- a/validating/Inverter3.java +++ b/validating/Inverter3.java @@ -2,7 +2,7 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -package validating; +//package validating; import static java.lang.Character.*; public class Inverter3 implements StringInverter { diff --git a/validating/Inverter4.java b/validating/Inverter4.java index 0b7870594..878985d69 100644 --- a/validating/Inverter4.java +++ b/validating/Inverter4.java @@ -2,7 +2,7 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -package validating; +//package validating; import static java.lang.Character.*; public class Inverter4 implements StringInverter { diff --git a/validating/SimpleDebugging.java b/validating/SimpleDebugging.java index 863e7de39..69a1102bd 100644 --- a/validating/SimpleDebugging.java +++ b/validating/SimpleDebugging.java @@ -6,15 +6,15 @@ public class SimpleDebugging { private static void foo1() { - System.out.println("In foo1"); + System.err.println("In foo1"); foo2(); } private static void foo2() { - System.out.println("In foo2"); + System.err.println("In foo2"); foo3(); } private static void foo3() { - System.out.println("In foo3"); + System.err.println("In foo3"); int j = 1; j--; int i = 5 / j; diff --git a/validating/StringInverter.java b/validating/StringInverter.java index 34c933a73..9f6c9ab16 100644 --- a/validating/StringInverter.java +++ b/validating/StringInverter.java @@ -2,7 +2,7 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -package validating; +//package validating; interface StringInverter { String invert(String str); diff --git a/validating/Timer.java b/validating/Timer.java new file mode 100644 index 000000000..72f0a9d9d --- /dev/null +++ b/validating/Timer.java @@ -0,0 +1,19 @@ +// onjava/Timer.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. + +import static java.util.concurrent.TimeUnit.*; + +public class Timer { + private long start = System.nanoTime(); + public long duration() { + return NANOSECONDS.toMillis( + System.nanoTime() - start); + } + public static long duration(Runnable test) { + Timer timer = new Timer(); + test.run(); + return timer.duration(); + } +} diff --git a/validating/tests/CircularQueue.java b/validating/tests/CircularQueue.java new file mode 100644 index 000000000..7700e9158 --- /dev/null +++ b/validating/tests/CircularQueue.java @@ -0,0 +1,90 @@ +// validating/CircularQueue.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// Demonstration of Design by Contract (DbC) +//package validating; + +import java.util.Arrays; + +public class CircularQueue { + private Object[] data; + private int + in = 0, // Next available storage space + out = 0; // Next gettable object + // Has it wrapped around the circular queue? + private boolean wrapped = false; + public CircularQueue(int size) { + data = new Object[size]; + // Must be true after construction: + assert invariant(); + } + public boolean empty() { + return !wrapped && in == out; + } + public boolean full() { + return wrapped && in == out; + } + public boolean isWrapped() { return wrapped; } + public void put(Object item) { + precondition(item != null, "put() null item"); + precondition(!full(), + "put() into full CircularQueue"); + assert invariant(); + data[in++] = item; + if(in >= data.length) { + in = 0; + wrapped = true; + } + assert invariant(); + } + public Object get() { + precondition(!empty(), + "get() from empty CircularQueue"); + assert invariant(); + Object returnVal = data[out]; + data[out] = null; + out++; + if(out >= data.length) { + out = 0; + wrapped = false; + } + assert postcondition( + returnVal != null, + "Null item in CircularQueue"); + assert invariant(); + return returnVal; + } + // Design-by-contract support methods: + private static void precondition(boolean cond, String msg) { + if(!cond) throw new CircularQueueException(msg); + } + private static boolean postcondition(boolean cond, String msg) { + if(!cond) throw new CircularQueueException(msg); + return true; + } + private boolean invariant() { + // Guarantee that no null values are in the + // region of 'data' that holds objects: + for(int i = out; i != in; i = (i + 1) % data.length) + if(data[i] == null) + throw new CircularQueueException( + "null in CircularQueue"); + // Guarantee that only null values are outside the + // region of 'data' that holds objects: + if(full()) return true; + for(int i = in; i != out; i = (i + 1) % data.length) + if(data[i] != null) + throw new CircularQueueException( + "non-null outside of CircularQueue range: " + + dump()); + return true; + } + public String dump() { + return "in = " + in + + ", out = " + out + + ", full() = " + full() + + ", empty() = " + empty() + + ", CircularQueue = " + Arrays.asList(data); + } +} diff --git a/validating/tests/CircularQueueException.java b/validating/tests/CircularQueueException.java new file mode 100644 index 000000000..5fa7a2e24 --- /dev/null +++ b/validating/tests/CircularQueueException.java @@ -0,0 +1,12 @@ +// validating/CircularQueueException.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +//package validating; + +public class +CircularQueueException extends RuntimeException { + public CircularQueueException(String why) { + super(why); + } +} diff --git a/validating/tests/CircularQueueTest.java b/validating/tests/CircularQueueTest.java index 8da6dc276..347e38484 100644 --- a/validating/tests/CircularQueueTest.java +++ b/validating/tests/CircularQueueTest.java @@ -2,7 +2,7 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -package validating; +//package validating; import org.junit.jupiter.api.*; import static org.junit.jupiter.api.Assertions.*; @@ -18,19 +18,19 @@ public void initialize() { private void showFullness() { assertTrue(queue.full()); assertFalse(queue.empty()); - System.out.println(queue.dump()); + System.err.println(queue.dump()); } private void showEmptiness() { assertFalse(queue.full()); assertTrue(queue.empty()); - System.out.println(queue.dump()); + System.err.println(queue.dump()); } @Test public void full() { - System.out.println("testFull"); - System.out.println(queue.dump()); - System.out.println(queue.get()); - System.out.println(queue.get()); + System.err.println("testFull"); + System.err.println(queue.dump()); + System.err.println(queue.get()); + System.err.println(queue.get()); while(!queue.full()) queue.put(Integer.toString(i++)); String msg = ""; @@ -38,53 +38,53 @@ public void full() { queue.put(""); } catch(CircularQueueException e) { msg = e.getMessage(); - System.out.println(msg); + System.err.println(msg); } assertEquals(msg, "put() into full CircularQueue"); showFullness(); } @Test public void empty() { - System.out.println("testEmpty"); + System.err.println("testEmpty"); while(!queue.empty()) - System.out.println(queue.get()); + System.err.println(queue.get()); String msg = ""; try { queue.get(); } catch(CircularQueueException e) { msg = e.getMessage(); - System.out.println(msg); + System.err.println(msg); } assertEquals(msg, "get() from empty CircularQueue"); showEmptiness(); } @Test public void nullPut() { - System.out.println("testNullPut"); + System.err.println("testNullPut"); String msg = ""; try { queue.put(null); } catch(CircularQueueException e) { msg = e.getMessage(); - System.out.println(msg); + System.err.println(msg); } assertEquals(msg, "put() null item"); } @Test public void circularity() { - System.out.println("testCircularity"); + System.err.println("testCircularity"); while(!queue.full()) queue.put(Integer.toString(i++)); showFullness(); assertTrue(queue.isWrapped()); while(!queue.empty()) - System.out.println(queue.get()); + System.err.println(queue.get()); showEmptiness(); while(!queue.full()) queue.put(Integer.toString(i++)); showFullness(); while(!queue.empty()) - System.out.println(queue.get()); + System.err.println(queue.get()); showEmptiness(); } } diff --git a/validating/tests/CountedList.java b/validating/tests/CountedList.java new file mode 100644 index 000000000..d83261eca --- /dev/null +++ b/validating/tests/CountedList.java @@ -0,0 +1,17 @@ +// validating/CountedList.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +// Keeps track of how many of itself are created. +//package validating; + +import java.util.ArrayList; + +public class CountedList extends ArrayList { + private static int counter = 0; + private int id = counter++; + public CountedList() { + System.err.println("CountedList #" + id); + } + public int getId() { return id; } +} diff --git a/validating/tests/CountedListTest.java b/validating/tests/CountedListTest.java index a9dc0c717..79073fe82 100644 --- a/validating/tests/CountedListTest.java +++ b/validating/tests/CountedListTest.java @@ -3,7 +3,7 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Simple use of JUnit to test CountedList. -package validating; +//package validating; import java.util.*; import org.junit.jupiter.api.*; import static org.junit.jupiter.api.Assertions.*; @@ -12,34 +12,35 @@ public class CountedListTest { private CountedList list; @BeforeAll static void beforeAllMsg() { - System.out.println(">>> Starting CountedListTest"); + System.err.println(">>> Starting CountedListTest"); } @AfterAll static void afterAllMsg() { - System.out.println(">>> Finished CountedListTest"); + System.err.println(">>> Finished CountedListTest"); } @BeforeEach public void initialize() { list = new CountedList(); - System.out.println("Set up for " + list.getId()); + System.err.println("Set up for " + list.getId()); for(int i = 0; i < 3; i++) list.add(Integer.toString(i)); } @AfterEach public void cleanup() { - System.out.println("Cleaning up " + list.getId()); + System.err.println("Cleaning up " + list.getId()); } @Test public void insert() { - System.out.println("Running testInsert()"); + System.err.println("Running testInsert()"); assertEquals(list.size(), 3); list.add(1, "Insert"); + System.err.println(list); assertEquals(list.size(), 4); assertEquals(list.get(1), "Insert"); } @Test public void replace() { - System.out.println("Running testReplace()"); + System.err.println("Running testReplace()"); assertEquals(list.size(), 3); list.set(1, "Replace"); assertEquals(list.size(), 3); @@ -54,12 +55,12 @@ void compare(List lst, String[] strs) { } @Test public void order() { - System.out.println("Running testOrder()"); + System.err.println("Running testOrder()"); compare(list, new String[] { "0", "1", "2" }); } @Test public void remove() { - System.out.println("Running testRemove()"); + System.err.println("Running testRemove()"); assertEquals(list.size(), 3); list.remove(1); assertEquals(list.size(), 2); @@ -67,7 +68,7 @@ public void remove() { } @Test public void addAll() { - System.out.println("Running testAddAll()"); + System.err.println("Running testAddAll()"); list.addAll(Arrays.asList(new String[] { "An", "African", "Swallow"})); assertEquals(list.size(), 6); diff --git a/validating/tests/DynamicStringInverterTests.java b/validating/tests/DynamicStringInverterTests.java index dc980971a..9e16bd76b 100644 --- a/validating/tests/DynamicStringInverterTests.java +++ b/validating/tests/DynamicStringInverterTests.java @@ -2,7 +2,7 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -package validating; +//package validating; import java.util.*; import java.util.function.*; import java.util.stream.*; @@ -21,14 +21,14 @@ Stream testVersions(String id, versions.iterator(), inverter -> inverter.getClass().getSimpleName(), inverter -> { - System.out.println( + System.err.println( inverter.getClass().getSimpleName() + ": " + id); try { if(test.apply(inverter) != "fail") - System.out.println("Success"); + System.err.println("Success"); } catch(Exception | Error e) { - System.out.println( + System.err.println( "Exception: " + e.getMessage()); } } @@ -37,17 +37,17 @@ Stream testVersions(String id, String isEqual(String lval, String rval) { if(lval.equals(rval)) return "success"; - System.out.println("FAIL: " + lval + " != " + rval); + System.err.println("FAIL: " + lval + " != " + rval); return "fail"; } @BeforeAll static void startMsg() { - System.out.println( + System.err.println( ">>> Starting DynamicStringInverterTests <<<"); } @AfterAll static void endMsg() { - System.out.println( + System.err.println( ">>> Finished DynamicStringInverterTests <<<"); } @TestFactory @@ -83,7 +83,7 @@ Stream disallowedCharacters() { }).collect(Collectors.joining("")); if(result.length() == 0) return "success"; - System.out.println("Bad characters: " + result); + System.err.println("Bad characters: " + result); return "fail"; } ); diff --git a/validating/tests/Inverter1.java b/validating/tests/Inverter1.java new file mode 100644 index 000000000..7688dc045 --- /dev/null +++ b/validating/tests/Inverter1.java @@ -0,0 +1,9 @@ +// validating/Inverter1.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +//package validating; + +public class Inverter1 implements StringInverter { + public String invert(String str) { return str; } +} diff --git a/validating/tests/Inverter2.java b/validating/tests/Inverter2.java new file mode 100644 index 000000000..a2368be5f --- /dev/null +++ b/validating/tests/Inverter2.java @@ -0,0 +1,19 @@ +// validating/Inverter2.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +//package validating; +import static java.lang.Character.*; + +public class Inverter2 implements StringInverter { + public String invert(String str) { + String result = ""; + for(int i = 0; i < str.length(); i++) { + char c = str.charAt(i); + result += isUpperCase(c) ? + toLowerCase(c) : + toUpperCase(c); + } + return result; + } +} diff --git a/validating/tests/Inverter3.java b/validating/tests/Inverter3.java new file mode 100644 index 000000000..2dda3b48e --- /dev/null +++ b/validating/tests/Inverter3.java @@ -0,0 +1,21 @@ +// validating/Inverter3.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +//package validating; +import static java.lang.Character.*; + +public class Inverter3 implements StringInverter { + public String invert(String str) { + if(str.length() > 30) + throw new RuntimeException("argument too long!"); + String result = ""; + for(int i = 0; i < str.length(); i++) { + char c = str.charAt(i); + result += isUpperCase(c) ? + toLowerCase(c) : + toUpperCase(c); + } + return result; + } +} diff --git a/validating/tests/Inverter4.java b/validating/tests/Inverter4.java new file mode 100644 index 000000000..878985d69 --- /dev/null +++ b/validating/tests/Inverter4.java @@ -0,0 +1,26 @@ +// validating/Inverter4.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +//package validating; +import static java.lang.Character.*; + +public class Inverter4 implements StringInverter { + static final String ALLOWED = + "abcdefghijklmnopqrstuvwxyz ,." + + "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + public String invert(String str) { + if(str.length() > 30) + throw new RuntimeException("argument too long!"); + String result = ""; + for(int i = 0; i < str.length(); i++) { + char c = str.charAt(i); + if(ALLOWED.indexOf(c) == -1) + throw new RuntimeException(c + " Not allowed"); + result += isUpperCase(c) ? + toLowerCase(c) : + toUpperCase(c); + } + return result; + } +} diff --git a/validating/tests/StringInverter.java b/validating/tests/StringInverter.java new file mode 100644 index 000000000..9f6c9ab16 --- /dev/null +++ b/validating/tests/StringInverter.java @@ -0,0 +1,9 @@ +// validating/StringInverter.java +// (c)2020 MindView LLC: see Copyright.txt +// We make no guarantees that this code is fit for any purpose. +// Visit http://OnJava8.com for more book information. +//package validating; + +interface StringInverter { + String invert(String str); +} diff --git a/validating/tests/StringInverterTests.java b/validating/tests/StringInverterTests.java index e32873b87..183c6dfa8 100644 --- a/validating/tests/StringInverterTests.java +++ b/validating/tests/StringInverterTests.java @@ -2,7 +2,7 @@ // (c)2020 MindView LLC: see Copyright.txt // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -package validating; +//package validating; import java.util.*; import java.util.stream.*; import org.junit.jupiter.api.*; @@ -12,7 +12,7 @@ public class StringInverterTests { StringInverter inverter = new Inverter4(); @BeforeAll static void startMsg() { - System.out.println(">>> StringInverterTests <<<"); + System.err.println(">>> StringInverterTests <<<"); } @Test void basicInversion1() {