diff --git a/arrays/ArrayCopying.java b/arrays/ArrayCopying.java index b5dc136f8..ce1cc0e62 100644 --- a/arrays/ArrayCopying.java +++ b/arrays/ArrayCopying.java @@ -51,6 +51,8 @@ public static void main(String[] args) { Arrays.copyOf(d, d.length, Sup[].class); // [4] show(b); +// Arrays.setAll(b, Sup::new); + // This "downcast" works fine: Sub[] d2 = Arrays.copyOf(b, b.length, Sub[].class); // [5] diff --git a/arrays/ArrayOfGenericType.java b/arrays/ArrayOfGenericType.java index 6c2df8468..bf2920757 100644 --- a/arrays/ArrayOfGenericType.java +++ b/arrays/ArrayOfGenericType.java @@ -8,9 +8,9 @@ public class ArrayOfGenericType { @SuppressWarnings("unchecked") public ArrayOfGenericType(int size) { // error: generic array creation: - //- array = new T[size]; +// array = new T[size]; array = (T[])new Object[size]; // unchecked cast } // error: generic array creation: - //- public U[] makeArray() { return new U[10]; } +// public U[] makeArray() { return new U[10]; } } diff --git a/arrays/ArrayOfGenerics.java b/arrays/ArrayOfGenerics.java index 8040dfa1f..9dc3e6d52 100644 --- a/arrays/ArrayOfGenerics.java +++ b/arrays/ArrayOfGenerics.java @@ -12,22 +12,28 @@ public static void main(String[] args) { ls = (List[])la; // Unchecked cast ls[0] = new ArrayList<>(); - //- ls[1] = new ArrayList(); +// ls[1] = new ArrayList(); // error: incompatible types: ArrayList // cannot be converted to List // ls[1] = new ArrayList(); - // ^ + + ls[1] = new ArrayList(); // The problem: List is a subtype of Object Object[] objects = ls; // So assignment is OK // Compiles and runs without complaint: objects[1] = new ArrayList<>(); + objects[2] = new ArrayList(); + // However, if your needs are straightforward it is // possible to create an array of generics, albeit // with an "unchecked cast" warning: List[] spheres = (List[])new List[10]; Arrays.setAll(spheres, n -> new ArrayList<>()); + + System.out.println(spheres); + } } diff --git a/arrays/ArraySearching.java b/arrays/ArraySearching.java index deae72faf..4c1636cdc 100644 --- a/arrays/ArraySearching.java +++ b/arrays/ArraySearching.java @@ -15,6 +15,7 @@ public static void main(String[] args) { show("Sorted array", a); while(true) { int r = rand.getAsInt(); +// r = 1000; int location = Arrays.binarySearch(a, r); if(location >= 0) { System.out.println( diff --git a/arrays/CountUpward.java b/arrays/CountUpward.java index 3ac361c86..3604c6d13 100644 --- a/arrays/CountUpward.java +++ b/arrays/CountUpward.java @@ -8,14 +8,14 @@ public class CountUpward { static long[] fillCounted(int size) { - return LongStream.iterate(0, i -> i + 1) + return LongStream.iterate(10, i -> i + 2) .limit(size).toArray(); } public static void main(String[] args) { long[] l1 = fillCounted(20); // No problem show(l1); // On my machine, this runs out of heap space: - //- long[] l2 = fillCounted(10_000_000); +// long[] l2 = fillCounted(10_000_000); } } /* Output: diff --git a/arrays/IceCreamFlavors.java b/arrays/IceCreamFlavors.java index 1be802edd..0a10fe914 100644 --- a/arrays/IceCreamFlavors.java +++ b/arrays/IceCreamFlavors.java @@ -3,36 +3,40 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Returning arrays from methods + import java.util.*; + import static onjava.ArrayShow.*; public class IceCreamFlavors { - private static SplittableRandom rand = - new SplittableRandom(47); - static final String[] FLAVORS = { - "Chocolate", "Strawberry", "Vanilla Fudge Swirl", - "Mint Chip", "Mocha Almond Fudge", "Rum Raisin", - "Praline Cream", "Mud Pie" - }; - public static String[] flavorSet(int n) { - if(n > FLAVORS.length) - throw new IllegalArgumentException("Set too big"); - String[] results = new String[n]; - boolean[] picked = new boolean[FLAVORS.length]; - for(int i = 0; i < n; i++) { - int t; - do - t = rand.nextInt(FLAVORS.length); - while(picked[t]); - results[i] = FLAVORS[t]; - picked[t] = true; + private static SplittableRandom rand = + new SplittableRandom(47); + static final String[] FLAVORS = { + "Chocolate", "Strawberry", "Vanilla Fudge Swirl", + "Mint Chip", "Mocha Almond Fudge", "Rum Raisin", + "Praline Cream", "Mud Pie" + }; + + public static String[] flavorSet(int n) { + if (n > FLAVORS.length) + throw new IllegalArgumentException("Set too big"); + String[] results = new String[n]; + boolean[] picked = new boolean[FLAVORS.length]; + for (int i = 0; i < n; i++) { + int t; + do + t = rand.nextInt(FLAVORS.length); + while (picked[t]); + results[i] = FLAVORS[t]; + picked[t] = true; + } + return results; + } + + public static void main(String[] args) { + for (int i = 0; i < 7; i++) + show(flavorSet(3)); } - return results; - } - public static void main(String[] args) { - for(int i = 0; i < 7; i++) - show(flavorSet(3)); - } } /* Output: [Praline Cream, Mint Chip, Vanilla Fudge Swirl] diff --git a/arrays/SimpleSetAll.java b/arrays/SimpleSetAll.java index 072975b00..4ec1b8e48 100644 --- a/arrays/SimpleSetAll.java +++ b/arrays/SimpleSetAll.java @@ -32,6 +32,15 @@ public static void main(String[] args) { Arrays.setAll(ia, n -> val++); // [2] Arrays.setAll(la, n -> val++); Arrays.setAll(da, n -> val++); + + show(ia); + show(la); + show(da); + + Arrays.setAll(ia, n -> n*2); + Arrays.setAll(la, n -> n* 2L); + Arrays.setAll(da, n -> n*2); + show(ia); show(la); show(da); diff --git a/arrays/StreamFromArray.java b/arrays/StreamFromArray.java index b30ed6d44..20ff8d7cb 100644 --- a/arrays/StreamFromArray.java +++ b/arrays/StreamFromArray.java @@ -4,6 +4,7 @@ // Visit http://OnJava8.com for more book information. import java.util.*; import onjava.*; +import onjava.ConvertTo; public class StreamFromArray { public static void main(String[] args) { diff --git a/arrays/jmh/ParallelSort.java b/arrays/jmh/ParallelSort.java index 64ff004d3..8516b0e4c 100644 --- a/arrays/jmh/ParallelSort.java +++ b/arrays/jmh/ParallelSort.java @@ -2,7 +2,7 @@ // (c)2021 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 arrays.jmh; +package jmh; import java.util.*; import onjava.*; import org.openjdk.jmh.annotations.*; @@ -10,10 +10,10 @@ @State(Scope.Thread) public class ParallelSort { private long[] la; - @Setup - public void setup() { - la = new Rand.Plong().array(100_000); - } +// @Setup +// public void setup() { +// la = new Rand.Plong().array(100_000); +// } @Benchmark public void sort() { Arrays.sort(la); diff --git a/collections/ArrayIsNotIterable.java b/collections/ArrayIsNotIterable.java index a9660a67c..f6b35cf21 100644 --- a/collections/ArrayIsNotIterable.java +++ b/collections/ArrayIsNotIterable.java @@ -13,7 +13,7 @@ public static void main(String[] args) { test(Arrays.asList(1, 2, 3)); String[] strings = { "A", "B", "C" }; // An array works in for-in, but it's not Iterable: - //- test(strings); +// test(strings); // You must explicitly convert it to an Iterable: test(Arrays.asList(strings)); } diff --git a/collections/CollectionDifferences.java b/collections/CollectionDifferences.java index a8ea09d01..3881ec5ca 100644 --- a/collections/CollectionDifferences.java +++ b/collections/CollectionDifferences.java @@ -2,7 +2,7 @@ // (c)2021 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.*; public class CollectionDifferences { public static void main(String[] args) { diff --git a/collections/CollectionSequence.java b/collections/CollectionSequence.java index ea0e45740..e590bc825 100644 --- a/collections/CollectionSequence.java +++ b/collections/CollectionSequence.java @@ -2,33 +2,47 @@ // (c)2021 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 reflection.pets.*; + import java.util.*; public class CollectionSequence -extends AbstractCollection { - private Pet[] pets = new PetCreator().array(8); - @Override - public int size() { return pets.length; } - @Override public Iterator iterator() { - return new Iterator() { // [1] - private int index = 0; - @Override public boolean hasNext() { - return index < pets.length; - } - @Override - public Pet next() { return pets[index++]; } - @Override - public void remove() { // Not implemented - throw new UnsupportedOperationException(); - } - }; - } - public static void main(String[] args) { - CollectionSequence c = new CollectionSequence(); - InterfaceVsIterator.display(c); - InterfaceVsIterator.display(c.iterator()); - } + extends AbstractCollection { + private Pet[] pets = new PetCreator().array(8); + + @Override + public int size() { + return pets.length; + } + + @Override + public Iterator iterator() { + return new Iterator<>() { // [1] + private int index = 0; + + @Override + public boolean hasNext() { + return index < pets.length; + } + + @Override + public Pet next() { + return pets[index++]; + } + + @Override + public void remove() { // Not implemented + throw new UnsupportedOperationException(); + } + }; + } + + public static void main(String[] args) { + CollectionSequence c = new CollectionSequence(); + InterfaceVsIterator.display(c); + InterfaceVsIterator.display(c.iterator()); + } } /* Output: 0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug diff --git a/collections/FinalFields.java b/collections/FinalFields.java index 1cf0f4f4e..2c4469d04 100644 --- a/collections/FinalFields.java +++ b/collections/FinalFields.java @@ -7,6 +7,6 @@ record FinalFields(int i) { int timesTen() { return i * 10; } - // void tryToChange() { i++; } // Error: +// void tryToChange() { i++; } // Error: // cannot assign a value to final variable i } diff --git a/collections/ImplementingRecord.java b/collections/ImplementingRecord.java index 4a453f775..0aea6aa0a 100644 --- a/collections/ImplementingRecord.java +++ b/collections/ImplementingRecord.java @@ -11,4 +11,9 @@ interface Star { record RedDwarf(double brightness) implements Star { @Override public double density() { return 100.0; } + +// @Override +// public double brightness() { +// return brightness; +// } } diff --git a/collections/InterfaceVsIterator.java b/collections/InterfaceVsIterator.java index fdb50a588..038f97eb6 100644 --- a/collections/InterfaceVsIterator.java +++ b/collections/InterfaceVsIterator.java @@ -32,6 +32,7 @@ public static void main(String[] args) { display(petSet.iterator()); System.out.println(petMap); System.out.println(petMap.keySet()); +// display(); display(petMap.values()); display(petMap.values().iterator()); } diff --git a/collections/ListFeatures.java b/collections/ListFeatures.java index 12fb6b4f1..928795711 100644 --- a/collections/ListFeatures.java +++ b/collections/ListFeatures.java @@ -2,7 +2,10 @@ // (c)2021 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 reflection.pets.*; +import reflection.*; import reflection.pets.*; + import java.util.*; public class ListFeatures { @@ -56,6 +59,7 @@ public static void main(String[] args) { System.out.println("20: " + pets.isEmpty()); pets.addAll(new PetCreator().list(4)); System.out.println("21: " + pets); + Object[] o = pets.toArray(); System.out.println("22: " + o[3]); Pet[] pa = pets.toArray(new Pet[0]); diff --git a/collections/ListIteration.java b/collections/ListIteration.java index 4967f5260..2f97237de 100644 --- a/collections/ListIteration.java +++ b/collections/ListIteration.java @@ -8,13 +8,14 @@ public class ListIteration { public static void main(String[] args) { List pets = new PetCreator().list(8); +// System.out.println(pets); ListIterator it = pets.listIterator(); while(it.hasNext()) System.out.print(it.next() + ", " + it.nextIndex() + ", " + it.previousIndex() + "; "); System.out.println(); - // Backwards: +// // Backwards: while(it.hasPrevious()) System.out.print(it.previous().id() + " "); System.out.println(); diff --git a/collections/MapOfList.java b/collections/MapOfList.java index d7357a6ed..2f51796f7 100644 --- a/collections/MapOfList.java +++ b/collections/MapOfList.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 collections.MapOfList} -package collections; +//package collections; import reflection.pets.*; import java.util.*; diff --git a/collections/PlusTen.java b/collections/PlusTen.java index a52bfed5b..b222ce95e 100644 --- a/collections/PlusTen.java +++ b/collections/PlusTen.java @@ -6,11 +6,11 @@ record PlusTen(int x) { PlusTen { - x += 10; +// x += 10; } // Adjustment to field can only happen in // the constructor. Still not legal: - // void mutate() { x += 10; } +// void mutate() { x += 10; } public static void main(String[] args) { System.out.println(new PlusTen(10)); } diff --git a/collections/StackCollision.java b/collections/StackCollision.java index 7914e3496..f8ef17954 100644 --- a/collections/StackCollision.java +++ b/collections/StackCollision.java @@ -5,7 +5,7 @@ public class StackCollision { public static void main(String[] args) { - onjava.Stack stack = new onjava.Stack<>(); + Stack stack = new Stack<>(); for(String s : "My dog has fleas".split(" ")) stack.push(s); while(!stack.isEmpty()) diff --git a/collections/StackTest.java b/collections/StackTest.java index 54005700a..e681c101e 100644 --- a/collections/StackTest.java +++ b/collections/StackTest.java @@ -3,6 +3,7 @@ // 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.Stack; public class StackTest { public static void main(String[] args) { @@ -11,6 +12,8 @@ public static void main(String[] args) { stack.push(s); while(!stack.isEmpty()) System.out.print(stack.pop() + " "); + +// new Stack<>() } } /* Output: diff --git a/collections/StackTest2.java b/collections/StackTest2.java index 148a834a8..5467e866c 100644 --- a/collections/StackTest2.java +++ b/collections/StackTest2.java @@ -2,7 +2,7 @@ // (c)2021 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.*; public class StackTest2 { public static void main(String[] args) { diff --git a/collections/UniqueWords.java b/collections/UniqueWords.java index e39a9b882..5fb81f8e9 100644 --- a/collections/UniqueWords.java +++ b/collections/UniqueWords.java @@ -9,13 +9,14 @@ public class UniqueWords { public static void main(String[] args) throws Exception { List lines = Files.readAllLines( - Paths.get("SetOperations.java")); + Paths.get("/Users/zss/Projects/OnJava8-Examples/collections/SetOfInteger.java")); Set words = new TreeSet<>(); for(String line : lines) for(String word : line.split("\\W+")) if(word.trim().length() > 0) words.add(word); System.out.println(words); + } } /* Output: diff --git a/collections/UniqueWordsAlphabetic.java b/collections/UniqueWordsAlphabetic.java index 780ddb3f1..444d215c9 100644 --- a/collections/UniqueWordsAlphabetic.java +++ b/collections/UniqueWordsAlphabetic.java @@ -10,7 +10,7 @@ public class UniqueWordsAlphabetic { public static void main(String[] args) throws Exception { List lines = Files.readAllLines( - Paths.get("SetOperations.java")); + Paths.get("/Users/zss/Projects/OnJava8-Examples/collections/SetOfInteger.java")); Set words = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); for(String line : lines) diff --git a/enums/Reflection.java b/enums/Reflection.java index d9ac05a7b..1b4d5841e 100644 --- a/enums/Reflection.java +++ b/enums/Reflection.java @@ -6,6 +6,7 @@ import java.lang.reflect.*; import java.util.*; import onjava.*; +import onjava.OSExecute; enum Explore { HERE, THERE } @@ -38,7 +39,7 @@ public static void main(String[] args) { System.out.println(exploreMethods); // Decompile the code for the enum: OSExecute.command( - "javap -cp build/classes/java/main Explore"); + "javap -cp out/production/classes/java/main Explore"); } } /* Output: diff --git a/enums/TrafficLight.java b/enums/TrafficLight.java index a42089a7a..6b6bee262 100644 --- a/enums/TrafficLight.java +++ b/enums/TrafficLight.java @@ -16,6 +16,7 @@ public void change() { case RED: color = Signal.GREEN; break; case GREEN: color = Signal.YELLOW; +// return; break; case YELLOW: color = Signal.RED; break; diff --git a/enums/UpcastEnum.java b/enums/UpcastEnum.java index 5665e2e3d..1561b2c85 100644 --- a/enums/UpcastEnum.java +++ b/enums/UpcastEnum.java @@ -10,7 +10,7 @@ public class UpcastEnum { public static void main(String[] args) { Search[] vals = Search.values(); Enum e = Search.HITHER; // Upcast - // e.values(); // No values() in Enum +// e.values(); // No values() in Enum for(Enum en : e.getClass().getEnumConstants()) System.out.println(en); } diff --git a/enums/Burrito2.java b/enums/enums/Burrito2.java similarity index 95% rename from enums/Burrito2.java rename to enums/enums/Burrito2.java index 5892eaf73..81278b871 100644 --- a/enums/Burrito2.java +++ b/enums/enums/Burrito2.java @@ -4,6 +4,7 @@ // Visit http://OnJava8.com for more book information. // {java enums.Burrito2} package enums; +//import static SpicinessEnum.*; import static enums.SpicinessEnum.*; public class Burrito2 { diff --git a/enums/SpicinessEnum.java b/enums/enums/SpicinessEnum.java similarity index 100% rename from enums/SpicinessEnum.java rename to enums/enums/SpicinessEnum.java diff --git a/exceptions/BodyException.java b/exceptions/BodyException.java index 25a952a63..a7c1ef382 100644 --- a/exceptions/BodyException.java +++ b/exceptions/BodyException.java @@ -15,7 +15,8 @@ public static void main(String[] args) { Third t = new Third(); new SecondExcept(); System.out.println("End of body"); - } catch(CE e) { + } + catch(CE e) { System.out.println("Caught: " + e); } } diff --git a/exceptions/CloseExceptions.java b/exceptions/CloseExceptions.java index bc31496bc..885cf192a 100644 --- a/exceptions/CloseExceptions.java +++ b/exceptions/CloseExceptions.java @@ -32,7 +32,8 @@ public static void main(String[] args) { Second s = new Second() ) { System.out.println("In body"); - } catch(CloseException e) { + } + catch(CloseException e) { System.out.println("Caught: " + e); } } diff --git a/exceptions/ExtraFeatures.java b/exceptions/ExtraFeatures.java index abf9d0bef..836407693 100644 --- a/exceptions/ExtraFeatures.java +++ b/exceptions/ExtraFeatures.java @@ -39,6 +39,8 @@ public static void main(String[] args) { try { f(); } catch(MyException2 e) { + e.getMessage(); + e.getLocalizedMessage(); e.printStackTrace(System.out); } try { diff --git a/exceptions/FullConstructors.java b/exceptions/FullConstructors.java index bb10b0f1c..2efd837df 100644 --- a/exceptions/FullConstructors.java +++ b/exceptions/FullConstructors.java @@ -21,6 +21,7 @@ public static void main(String[] args) { try { f(); } catch(MyException e) { + System.out.println("---"); e.printStackTrace(System.out); } try { diff --git a/exceptions/Human.java b/exceptions/Human.java index b35f77954..63ab6c381 100644 --- a/exceptions/Human.java +++ b/exceptions/Human.java @@ -12,9 +12,9 @@ public static void main(String[] args) { // Catch the exact type: try { throw new Sneeze(); - } catch(Sneeze s) { + } catch(Sneeze s) { // Annoyance System.out.println("Caught Sneeze"); - } catch(Annoyance a) { + } catch(Annoyance a) { // Sneeze System.out.println("Caught Annoyance"); } // Catch the base type: diff --git a/exceptions/InputFile2.java b/exceptions/InputFile2.java index 4e8b8c49c..6e51aaa4c 100644 --- a/exceptions/InputFile2.java +++ b/exceptions/InputFile2.java @@ -17,9 +17,9 @@ Stream getLines() throws IOException { } public static void main(String[] args) throws IOException { - new InputFile2("InputFile2.java").getLines() - .skip(15) - .limit(1) + new InputFile2("/Users/zss/Projects/OnJava8-Examples/exceptions/InputFile2.java").getLines() + .skip(14) + .limit(2) .forEach(System.out::println); } } diff --git a/exceptions/LostMessage.java b/exceptions/LostMessage.java index 75c57e1c2..81e2e72b7 100644 --- a/exceptions/LostMessage.java +++ b/exceptions/LostMessage.java @@ -31,8 +31,11 @@ public static void main(String[] args) { } finally { lm.dispose(); } - } catch(VeryImportantException | - HoHumException e) { + } catch( + VeryImportantException + | + HoHumException e + ) { System.out.println(e); } } diff --git a/exceptions/StormyInning.java b/exceptions/StormyInning.java index b12d3a944..2fa15c93d 100644 --- a/exceptions/StormyInning.java +++ b/exceptions/StormyInning.java @@ -33,14 +33,21 @@ class StormyInning extends Inning implements Storm { // OK to add new exceptions for constructors, but you // must deal with the base constructor exceptions: public StormyInning() - throws RainedOut, BaseballException {} + throws + RainedOut + , + BaseballException + { + + } public StormyInning(String s) - throws BaseballException {} + throws BaseballException + {} // Regular methods must conform to base class: - //- void walk() throws PopFoul {} //Compile error +// void walk() throws PopFoul {} //Compile error // Interface CANNOT add exceptions to existing // methods from the base class: - //- public void event() throws RainedOut {} +// public void event() throws RainedOut {} // If the method doesn't already exist in the // base class, the exception is OK: @Override public void rainHard() throws RainedOut {} @@ -48,7 +55,7 @@ public StormyInning(String s) // even if the base version does: @Override public void event() {} // Overridden methods can throw inherited exceptions: - @Override public void atBat() throws PopFoul {} + @Override public void atBat() throws PopFoul{} public static void main(String[] args) { try { StormyInning si = new StormyInning(); @@ -67,13 +74,17 @@ public static void main(String[] args) { i.atBat(); // You must catch the exceptions from the // base-class version of the method: - } catch(Strike e) { + } + catch(Strike e) { System.out.println("Strike"); - } catch(Foul e) { + } + catch(Foul e) { System.out.println("Foul"); - } catch(RainedOut e) { + } + catch(RainedOut e) { System.out.println("Rained out"); - } catch(BaseballException e) { + } + catch(BaseballException e) { System.out.println("Generic baseball exception"); } } diff --git a/exceptions/TryAnything.java b/exceptions/TryAnything.java index faa446cd3..206689a8b 100644 --- a/exceptions/TryAnything.java +++ b/exceptions/TryAnything.java @@ -1,16 +1,16 @@ -// exceptions/TryAnything.java -// (c)2021 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. -// {WillNotCompile} - -class Anything {} - -public class TryAnything { - public static void main(String[] args) { - try( - Anything a = new Anything() - ) { - } - } -} +//// exceptions/TryAnything.java +//// (c)2021 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. +//// {WillNotCompile} +// +//class Anything {} +// +//public class TryAnything { +//// public static void main(String[] args) { +//// try( +////// Anything a = new Anything() +//// ) { +//// } +// } +//} diff --git a/exceptions/WhoCalled.java b/exceptions/WhoCalled.java index 9bdfb5abf..8c412d670 100644 --- a/exceptions/WhoCalled.java +++ b/exceptions/WhoCalled.java @@ -11,7 +11,8 @@ static void f() { throw new Exception(); } catch(Exception e) { for(StackTraceElement ste : e.getStackTrace()) - System.out.println(ste.getMethodName()); +// System.out.println(ste.getMethodName()); + System.out.println(ste); } } static void g() { f(); } diff --git a/files/AddAndSubtractPaths.java b/files/AddAndSubtractPaths.java index 06409c9c8..0100d92d5 100644 --- a/files/AddAndSubtractPaths.java +++ b/files/AddAndSubtractPaths.java @@ -25,7 +25,7 @@ static void show(int id, Path result) { public static void main(String[] args) { System.out.println(System.getProperty("os.name")); System.out.println(base); - Path p = Paths.get("AddAndSubtractPaths.java") + Path p = Paths.get("/Users/zss/Projects/OnJava8-Examples/files/AddAndSubtractPaths.java") .toAbsolutePath(); show(1, p); Path convoluted = p.getParent().getParent() diff --git a/files/Directories.java b/files/Directories.java index ffce7ecab..85176704a 100644 --- a/files/Directories.java +++ b/files/Directories.java @@ -4,7 +4,7 @@ // 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"); @@ -47,7 +47,7 @@ static void populateTestDir() throws Exception { Path variant = makeVariant(); if(!Files.exists(variant)) { Files.createDirectories(variant); - Files.copy(Paths.get("Directories.java"), + Files.copy(Paths.get("/Users/zss/Projects/OnJava8-Examples/files/Directories.java"), variant.resolve("File.txt")); Files.createTempFile(variant, null, null); } diff --git a/files/Find.java b/files/Find.java index d27c69ed7..08f99876f 100644 --- a/files/Find.java +++ b/files/Find.java @@ -3,38 +3,38 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // {ExcludeFromGradle} + import java.nio.file.*; public class Find { - public static void - main(String[] args) throws Exception { - Path test = Paths.get("test"); - Directories.refreshTestDir(); - Directories.populateTestDir(); - // Creating a *directory*, not a file: - Files.createDirectory(test.resolve("dir.tmp")); + public static void main(String[] args) throws Exception { + Path test = Paths.get("test"); + Directories.refreshTestDir(); + Directories.populateTestDir(); + // Creating a *directory*, not a file: + Files.createDirectory(test.resolve("dir.tmp")); - PathMatcher matcher = FileSystems.getDefault() - .getPathMatcher("glob:**/*.{tmp,txt}"); - Files.walk(test) - .filter(matcher::matches) - .forEach(System.out::println); - System.out.println("***************"); + PathMatcher matcher = FileSystems.getDefault() + .getPathMatcher("glob:**/*.{tmp,txt}"); + Files.walk(test) + .filter(matcher::matches) + .forEach(System.out::println); + System.out.println("***************"); - PathMatcher matcher2 = FileSystems.getDefault() - .getPathMatcher("glob:*.tmp"); - Files.walk(test) - .map(Path::getFileName) - .filter(matcher2::matches) - .forEach(System.out::println); - System.out.println("***************"); + PathMatcher matcher2 = FileSystems.getDefault() + .getPathMatcher("glob:*.tmp"); + Files.walk(test) + .map(Path::getFileName) + .filter(matcher2::matches) + .forEach(System.out::println); + System.out.println("***************"); - Files.walk(test) // Only look for files - .filter(Files::isRegularFile) - .map(Path::getFileName) - .filter(matcher2::matches) - .forEach(System.out::println); - } + Files.walk(test) // Only look for files + .filter(Files::isRegularFile) + .map(Path::getFileName) + .filter(matcher2::matches) + .forEach(System.out::println); + } } /* Output: test\bag\foo\bar\baz\5208762845883213974.tmp diff --git a/files/ListOfLines.java b/files/ListOfLines.java index ef1a7c4ec..f5ad8be2f 100644 --- a/files/ListOfLines.java +++ b/files/ListOfLines.java @@ -9,7 +9,7 @@ public class ListOfLines { public static void main(String[] args) throws Exception { Files.readAllLines( - Paths.get("../streams/Cheese.dat")) + Paths.get("/Users/zss/Projects/OnJava8-Examples/streams/Cheese.dat")) .stream() .filter(line -> !line.startsWith("//")) .map(line -> diff --git a/files/PartsOfPaths.java b/files/PartsOfPaths.java index 63a581e52..4c1878337 100644 --- a/files/PartsOfPaths.java +++ b/files/PartsOfPaths.java @@ -8,11 +8,13 @@ public class PartsOfPaths { public static void main(String[] args) { System.out.println(System.getProperty("os.name")); Path p = - Paths.get("PartsOfPaths.java").toAbsolutePath(); + Paths.get("/Users/zss/Projects/OnJava8-Examples/files/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.out.println("ends with 'PartsOfPaths.java': " + + p.endsWith("PartsOfPaths.java")); for(Path pp : p) { System.out.print(pp + ": "); System.out.print(p.startsWith(pp) + " : "); diff --git a/files/PathAnalysis.java b/files/PathAnalysis.java index 9800ed2c5..2fd9eb2d5 100644 --- a/files/PathAnalysis.java +++ b/files/PathAnalysis.java @@ -14,7 +14,7 @@ static void say(String id, Object result) { main(String[] args) throws IOException { System.out.println(System.getProperty("os.name")); Path p = - Paths.get("PathAnalysis.java").toAbsolutePath(); + Paths.get("/Users/zss/Projects/OnJava8-Examples/files/PathAnalysis.java").toAbsolutePath(); say("Exists", Files.exists(p)); say("Directory", Files.isDirectory(p)); say("Executable", Files.isExecutable(p)); diff --git a/files/PathInfo.java b/files/PathInfo.java index 78ef9e48b..0c5d930e3 100644 --- a/files/PathInfo.java +++ b/files/PathInfo.java @@ -26,7 +26,7 @@ public static void main(String[] args) { System.out.println(System.getProperty("os.name")); info(Paths.get( "C:", "path", "to", "nowhere", "NoFile.txt")); - Path p = Paths.get("PathInfo.java"); + Path p = Paths.get("/Users/zss/Projects/OnJava8-Examples/files/PathInfo.java"); info(p); Path ap = p.toAbsolutePath(); info(ap); diff --git a/files/ReadLineStream.java b/files/ReadLineStream.java index 812ed1058..c3e90b073 100644 --- a/files/ReadLineStream.java +++ b/files/ReadLineStream.java @@ -7,7 +7,7 @@ public class ReadLineStream { public static void main(String[] args) throws Exception { - Files.lines(Paths.get("PathInfo.java")) + Files.lines(Paths.get("/Users/zss/Projects/OnJava8-Examples/files/PathInfo.java")) .skip(13) .findFirst() .ifPresent(System.out::println); diff --git a/files/StreamInAndOut.java b/files/StreamInAndOut.java index 4f7297d55..cd06bb956 100644 --- a/files/StreamInAndOut.java +++ b/files/StreamInAndOut.java @@ -10,7 +10,7 @@ public class StreamInAndOut { public static void main(String[] args) { try( Stream input = - Files.lines(Paths.get("StreamInAndOut.java")); + Files.lines(Paths.get("/Users/zss/Projects/OnJava8-Examples/files/StreamInAndOut.java")); PrintWriter output = new PrintWriter("StreamInAndOut.txt") ) { diff --git a/files/Writing.java b/files/Writing.java index 82745e4d5..7434cc329 100644 --- a/files/Writing.java +++ b/files/Writing.java @@ -13,16 +13,16 @@ public class Writing { // Write bytes to a file: byte[] bytes = new byte[SIZE]; rand.nextBytes(bytes); - Files.write(Paths.get("bytes.dat"), bytes); + Files.write(Paths.get("/Users/zss/Projects/OnJava8-Examples/bytes.dat"), bytes); System.out.println("bytes.dat: " + - Files.size(Paths.get("bytes.dat"))); + Files.size(Paths.get("/Users/zss/Projects/OnJava8-Examples/bytes.dat"))); // Write an iterable to a file: List lines = Files.readAllLines( - Paths.get("../streams/Cheese.dat")); - Files.write(Paths.get("Cheese.txt"), lines); + Paths.get("/Users/zss/Projects/OnJava8-Examples/streams/Cheese.dat")); + Files.write(Paths.get("/Users/zss/Projects/OnJava8-Examples/streams/Cheese.dat"), lines); System.out.println("Cheese.txt: " + - Files.size(Paths.get("Cheese.txt"))); + Files.size(Paths.get("/Users/zss/Projects/OnJava8-Examples/streams/Cheese.txt"))); } } /* Output: diff --git a/functional/AnonymousClosure.java b/functional/AnonymousClosure.java index 6faa0925e..f866a4ec1 100644 --- a/functional/AnonymousClosure.java +++ b/functional/AnonymousClosure.java @@ -8,8 +8,8 @@ public class AnonymousClosure { IntSupplier makeFun(int x) { int i = 0; // Same rules apply: - // i++; // Not "effectively final" - // x++; // Ditto +// i++; // Not "effectively final" +// x++; // Ditto return new IntSupplier() { public int getAsInt() { return x + i; } }; diff --git a/functional/Closure3.java b/functional/Closure3.java index 40728b5f3..59f5fb737 100644 --- a/functional/Closure3.java +++ b/functional/Closure3.java @@ -6,9 +6,9 @@ import java.util.function.*; public class Closure3 { - IntSupplier makeFun(int x) { - int i = 0; + IntSupplier makeFun(final int x) { + final int i = 0; // Neither x++ nor i++ will work: - return () -> x++ + i++; + return () -> x + i; } } diff --git a/functional/Closure5.java b/functional/Closure5.java index dcd7a08f4..3eb663373 100644 --- a/functional/Closure5.java +++ b/functional/Closure5.java @@ -6,10 +6,10 @@ import java.util.function.*; public class Closure5 { - IntSupplier makeFun(int x) { - int i = 0; - i++; - x++; + IntSupplier makeFun(final int x) { + final int i = 0; +// i++; +// x++; return () -> x + i; } } diff --git a/functional/Closure6.java b/functional/Closure6.java index b102a67af..723df9462 100644 --- a/functional/Closure6.java +++ b/functional/Closure6.java @@ -9,7 +9,7 @@ IntSupplier makeFun(int x) { int i = 0; i++; x++; - final int iFinal = i; + int iFinal = i; final int xFinal = x; return () -> xFinal + iFinal; } diff --git a/functional/Closure7.java b/functional/Closure7.java index 098685296..f8ca2141d 100644 --- a/functional/Closure7.java +++ b/functional/Closure7.java @@ -8,7 +8,7 @@ public class Closure7 { IntSupplier makeFun(int x) { Integer i = 0; - i = i + 1; - return () -> x + i; + final int i1 = i + 1; + return () -> x + i1; } } diff --git a/functional/Closure8.java b/functional/Closure8.java index 8cfa1041b..aa010817a 100644 --- a/functional/Closure8.java +++ b/functional/Closure8.java @@ -5,7 +5,7 @@ import java.util.*; import java.util.function.*; -public class Closure8 { + public class Closure8 { Supplier> makeFun() { final List ai = new ArrayList<>(); ai.add(1); diff --git a/functional/Closure9.java b/functional/Closure9.java index 4679e474e..38298e430 100644 --- a/functional/Closure9.java +++ b/functional/Closure9.java @@ -6,10 +6,10 @@ import java.util.*; import java.util.function.*; -public class Closure9 { - Supplier> makeFun() { - List ai = new ArrayList<>(); - ai = new ArrayList<>(); // Reassignment - return () -> ai; - } -} +//public class Closure9 { +// Supplier> makeFun() { +// List ai = new ArrayList<>(); +// ai = new ArrayList<>(); // Reassignment +// return () -> ai; +// } +//} diff --git a/functional/CtorReference.java b/functional/CtorReference.java index ec74b00f7..3350aa950 100644 --- a/functional/CtorReference.java +++ b/functional/CtorReference.java @@ -6,9 +6,14 @@ class Dog { String name; int age = -1; // For "unknown" - Dog() { name = "stray"; } - Dog(String nm) { name = nm; } - Dog(String nm, int yrs) { name = nm; age = yrs; } + Dog() { + System.out.println("0"); + name = "stray"; + } + Dog(String nm) { + System.out.println("1");name = nm; } + Dog(String nm, int yrs) { + System.out.println("2");nm = nm; age = yrs; } } interface MakeNoArgs { @@ -29,6 +34,8 @@ public static void main(String[] args) { Make1Arg m1a = Dog::new; // [2] Make2Args m2a = Dog::new; // [3] + +// System.out::println; Dog dn = mna.make(); Dog d1 = m1a.make("Comet"); Dog d2 = m2a.make("Ralph", 4); diff --git a/functional/FunctionComposition.java b/functional/FunctionComposition.java index f20b115ca..ca3e1def2 100644 --- a/functional/FunctionComposition.java +++ b/functional/FunctionComposition.java @@ -5,8 +5,7 @@ import java.util.function.*; public class FunctionComposition { - static Function - f1 = s -> { + static Function f1 = s -> { System.out.println(s); return s.replace('A', '_'); }, diff --git a/functional/FunctionalAnnotation.java b/functional/FunctionalAnnotation.java index 29cc33056..6c131c8d5 100644 --- a/functional/FunctionalAnnotation.java +++ b/functional/FunctionalAnnotation.java @@ -18,6 +18,8 @@ interface NotFunctional { String goodbye(String arg); String hello(String arg); } + */ +/* Produces error message: NotFunctional is not a functional interface multiple non-overriding abstract methods @@ -33,7 +35,7 @@ public static void main(String[] args) { new FunctionalAnnotation(); Functional f = fa::goodbye; FunctionalNoAnn fna = fa::goodbye; - // Functional fac = fa; // Incompatible +// Functional fac = fa; // Incompatible Functional fl = a -> "Goodbye, " + a; FunctionalNoAnn fnal = a -> "Goodbye, " + a; } diff --git a/functional/MethodConversion.java b/functional/MethodConversion.java index 15e780749..04a5906b6 100644 --- a/functional/MethodConversion.java +++ b/functional/MethodConversion.java @@ -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/MyTriFunction.java b/functional/MyTriFunction.java new file mode 100644 index 000000000..e4807702a --- /dev/null +++ b/functional/MyTriFunction.java @@ -0,0 +1,4 @@ +@FunctionalInterface +public interface MyTriFunction { + E apply(A a, B b, C c, D d); +} diff --git a/functional/RecursiveFactorial.java b/functional/RecursiveFactorial.java index 5ddb0860c..b78edeaac 100644 --- a/functional/RecursiveFactorial.java +++ b/functional/RecursiveFactorial.java @@ -4,6 +4,7 @@ // Visit http://OnJava8.com for more book information. public class RecursiveFactorial { +// static IntCall fact = n -> n == 0 ? 1 : n * fact.call(n - 1); static IntCall fact; public static void main(String[] args) { fact = n -> n == 0 ? 1 : n * fact.call(n - 1); diff --git a/functional/TriFunctionTest.java b/functional/TriFunctionTest.java index 5af98922c..bddd33824 100644 --- a/functional/TriFunctionTest.java +++ b/functional/TriFunctionTest.java @@ -5,9 +5,18 @@ public class TriFunctionTest { static int f(int i, long l, double d) { return 99; } + + static long f(int i,int j,int k,int l) { + return (long) i +j +k+l; + } public static void main(String[] args) { TriFunction tf = TriFunctionTest::f; tf = (i, l, d) -> 12; + MyTriFunction mtf = TriFunctionTest::f; + +// mtf = (i,j,k,l) -> 100L; + Long apply = mtf.apply(1, 2, 4, 5); + System.out.println(apply); } } diff --git a/functional/UnboundMethodReference.java b/functional/UnboundMethodReference.java index 6c02b8b91..56369f196 100644 --- a/functional/UnboundMethodReference.java +++ b/functional/UnboundMethodReference.java @@ -18,7 +18,8 @@ interface TransformX { public class UnboundMethodReference { public static void main(String[] args) { - // MakeString ms = X::f; // [1] + MakeString ms1 = () -> new X().f(); +// MakeString ms = X::f; // [1] TransformX sp = X::f; X x = new X(); System.out.println(sp.transform(x)); // [2] diff --git a/generics/ArrayOfGeneric.java b/generics/ArrayOfGeneric.java index 68f7a5bdf..c4a63334a 100644 --- a/generics/ArrayOfGeneric.java +++ b/generics/ArrayOfGeneric.java @@ -17,9 +17,9 @@ public static void main(String[] args) { gia = (Generic[])new Generic[SIZE]; System.out.println(gia.getClass().getSimpleName()); gia[0] = new Generic<>(); - //- gia[1] = new Object(); // Compile-time error + // gia[1] = new Object(); // Compile-time error // Discovers type mismatch at compile time: - //- gia[2] = new Generic(); +// gia[2] = new Generic(); } } /* Output: diff --git a/generics/BasicBounds.java b/generics/BasicBounds.java index ca2c00dfa..6ebb0243e 100644 --- a/generics/BasicBounds.java +++ b/generics/BasicBounds.java @@ -3,60 +3,120 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. -interface HasColor { java.awt.Color getColor(); } +interface HasColor { + java.awt.Color getColor(); +} class WithColor { - T item; - WithColor(T item) { this.item = item; } - T getItem() { return item; } - // The bound allows you to call a method: - java.awt.Color color() { return item.getColor(); } + T item; + + WithColor(T item) { + this.item = item; + } + + T getItem() { + return item; + } + + // The bound allows you to call a method: + java.awt.Color color() { + return item.getColor(); + } } -class Coord { public int x, y, z; } +class Coord { + public int x, y, z; +} // This fails. Class must be first, then interfaces: // class WithColorCoord { // Multiple bounds: class WithColorCoord { - T item; - WithColorCoord(T item) { this.item = item; } - T getItem() { return item; } - java.awt.Color color() { return item.getColor(); } - int getX() { return item.x; } - int getY() { return item.y; } - int getZ() { return item.z; } + T item; + + WithColorCoord(T item) { + this.item = item; + } + + T getItem() { + return item; + } + + java.awt.Color color() { + return item.getColor(); + } + + int getX() { + return item.x; + } + + int getY() { + return item.y; + } + + int getZ() { + return item.z; + } } -interface Weight { int weight(); } +interface Weight { + int weight(); +} // As with inheritance, you can have only one // concrete class but multiple interfaces: class Solid { - T item; - Solid(T item) { this.item = item; } - T getItem() { return item; } - java.awt.Color color() { return item.getColor(); } - int getX() { return item.x; } - int getY() { return item.y; } - int getZ() { return item.z; } - int weight() { return item.weight(); } + T item; + + Solid(T item) { + this.item = item; + } + + T getItem() { + return item; + } + + java.awt.Color color() { + return item.getColor(); + } + + int getX() { + return item.x; + } + + int getY() { + return item.y; + } + + int getZ() { + return item.z; + } + + int weight() { + return item.weight(); + } } class Bounded -extends Coord implements HasColor, Weight { - @Override - public java.awt.Color getColor() { return null; } - @Override public int weight() { return 0; } + extends Coord implements HasColor, Weight { + @Override + public java.awt.Color getColor() { + return null; + } + + @Override + public int weight() { + return 0; + } } public class BasicBounds { - public static void main(String[] args) { - Solid solid = - new Solid<>(new Bounded()); - solid.color(); - solid.getY(); - solid.weight(); - } + public static void main(String[] args) { + Solid solid = + new Solid<>(new Bounded()); + solid.color(); + solid.getY(); + solid.weight(); + } } diff --git a/generics/BasicSupplierDemo.java b/generics/BasicSupplierDemo.java index bf754154a..6adf018e1 100644 --- a/generics/BasicSupplierDemo.java +++ b/generics/BasicSupplierDemo.java @@ -2,16 +2,18 @@ // (c)2021 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 java.util.stream.*; public class BasicSupplierDemo { - public static void main(String[] args) { - Stream.generate( - BasicSupplier.create(CountedObject.class)) - .limit(5) - .forEach(System.out::println); - } + public static void main(String[] args) { + Stream.generate( + BasicSupplier.create(CountedObject.class)) + .limit(5) + .forEach(System.out::println); + } } /* Output: CountedObject 0 diff --git a/generics/ByteSet.java b/generics/ByteSet.java index 860125b6a..4e881e2cd 100644 --- a/generics/ByteSet.java +++ b/generics/ByteSet.java @@ -9,6 +9,6 @@ public class ByteSet { Set mySet = new HashSet<>(Arrays.asList(possibles)); // But you can't do this: - // Set mySet2 = new HashSet<>( - // Arrays.asList(1,2,3,4,5,6,7,8,9)); +// Set mySet2 = new HashSet<>( +// Arrays.asList(1,2,3,4,5,6,7,8,9)); } diff --git a/generics/CheckedList.java b/generics/CheckedList.java index 71ebe3d0a..f4866f7ba 100644 --- a/generics/CheckedList.java +++ b/generics/CheckedList.java @@ -25,7 +25,7 @@ public static void main(String[] args) { List pets = Collections.checkedList( new ArrayList<>(), Pet.class); pets.add(new Dog()); - pets.add(new Cat()); +// pets.add(new Cat()); } } /* Output: diff --git a/generics/CountedObject.java b/generics/CountedObject.java index 287b480fb..574f133d9 100644 --- a/generics/CountedObject.java +++ b/generics/CountedObject.java @@ -4,10 +4,15 @@ // Visit http://OnJava8.com for more book information. public class CountedObject { - private static long counter = 0; - private final long id = counter++; - public long id() { return id; } - @Override public String toString() { - return "CountedObject " + id; - } + private static long counter = 0; + private final long id = counter++; + + public long id() { + return id; + } + + @Override + public String toString() { + return "CountedObject " + id; + } } diff --git a/generics/DynamicProxyMixin.java b/generics/DynamicProxyMixin.java index 906278fba..e825e25d4 100644 --- a/generics/DynamicProxyMixin.java +++ b/generics/DynamicProxyMixin.java @@ -2,10 +2,16 @@ // (c)2021 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.Tuple2; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.util.HashMap; +import java.util.Map; + +import static onjava.Tuple.tuple; class MixinProxy implements InvocationHandler { Map delegatesByMethod; diff --git a/generics/EpicBattle.java b/generics/EpicBattle.java index 716606608..4d0ee7af9 100644 --- a/generics/EpicBattle.java +++ b/generics/EpicBattle.java @@ -67,6 +67,6 @@ public static void main(String[] args) { // You can do this: List audioPeople; // But you can't do this: - // List dogPs; +// List dogPs; } } diff --git a/generics/Erased.java b/generics/Erased.java index 304385afb..c8c5ebb1d 100644 --- a/generics/Erased.java +++ b/generics/Erased.java @@ -1,24 +1,24 @@ -// generics/Erased.java -// (c)2021 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. -// {WillNotCompile} - -public class Erased { - private final int SIZE = 100; - public void f(Object arg) { - - // error: illegal generic type for instanceof - if(arg instanceof T) {} - - // error: unexpected type - T var = new T(); - - // error: generic array creation - T[] array = new T[SIZE]; - - // warning: [unchecked] unchecked cast - T[] array = (T[])new Object[SIZE]; - - } -} +//// generics/Erased.java +//// (c)2021 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. +//// {WillNotCompile} +// +//public class Erased { +// private final int SIZE = 100; +// public void f(Object arg) { +// +// // error: illegal generic type for instanceof +// if(arg instanceof T) {} +// +// // error: unexpected type +// T var = new T(); +// +// // error: generic array creation +// T[] array = new T[SIZE]; +// +// // warning: [unchecked] unchecked cast +// T[] array = (T[])new Object[SIZE]; +// +// } +//} diff --git a/generics/ErasureAndInheritance.java b/generics/ErasureAndInheritance.java index 4a2e2591c..87eafda5d 100644 --- a/generics/ErasureAndInheritance.java +++ b/generics/ErasureAndInheritance.java @@ -19,7 +19,7 @@ class Derived2 extends GenericBase {} // No warning // required: class or interface without bounds public class ErasureAndInheritance { - @SuppressWarnings("unchecked") +// @SuppressWarnings("unchecked") public static void main(String[] args) { Derived2 d2 = new Derived2(); Object obj = d2.get(); diff --git a/generics/Fibonacci.java b/generics/Fibonacci.java index c20bdf225..81bc494d5 100644 --- a/generics/Fibonacci.java +++ b/generics/Fibonacci.java @@ -3,23 +3,29 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Generate a Fibonacci sequence + import java.util.function.*; import java.util.stream.*; public class Fibonacci implements Supplier { - private int count = 0; - @Override - public Integer get() { return fib(count++); } - private int fib(int n) { - if(n < 2) return 1; - return fib(n-2) + fib(n-1); - } - public static void main(String[] args) { - Stream.generate(new Fibonacci()) - .limit(18) - .map(n -> n + " ") - .forEach(System.out::print); - } + private int count = 0; + + @Override + public Integer get() { + return fib(count++); + } + + private int fib(int n) { + if (n < 2) return 1; + return fib(n - 2) + fib(n - 1); + } + + public static void main(String[] args) { + Stream.generate(new Fibonacci()) + .limit(18) + .map(n -> n + " ") + .forEach(System.out::print); + } } /* Output: 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 diff --git a/generics/GenericArray.java b/generics/GenericArray.java index 39212feca..abe059bb5 100644 --- a/generics/GenericArray.java +++ b/generics/GenericArray.java @@ -4,27 +4,36 @@ // 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.out.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 diff --git a/generics/GenericCast.java b/generics/GenericCast.java index eb4fb651d..737ac6c5c 100644 --- a/generics/GenericCast.java +++ b/generics/GenericCast.java @@ -2,44 +2,50 @@ // (c)2021 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 FixedSizeStack { - private final int size; - private Object[] storage; - private int index = 0; - FixedSizeStack(int size) { - this.size = size; - storage = new Object[size]; - } - public void push(T item) { - if(index < size) - storage[index++] = item; - } - @SuppressWarnings("unchecked") - public T pop() { - return index == 0 ? null : (T)storage[--index]; - } - @SuppressWarnings("unchecked") - Stream stream() { - return (Stream)Arrays.stream(storage); - } + private final int size; + private Object[] storage; + private int index = 0; + + FixedSizeStack(int size) { + this.size = size; + storage = new Object[size]; + } + + public void push(T item) { + if (index < size) + storage[index++] = item; + } + + @SuppressWarnings("unchecked") + public T pop() { + return index == 0 ? null : (T) storage[--index]; + } + + @SuppressWarnings("unchecked") + Stream stream() { + return (Stream) Arrays.stream(storage); + } } public class GenericCast { - static String[] letters = - "ABCDEFGHIJKLMNOPQRS".split(""); - public static void main(String[] args) { - FixedSizeStack strings = - new FixedSizeStack<>(letters.length); - Arrays.stream("ABCDEFGHIJKLMNOPQRS".split("")) - .forEach(strings::push); - System.out.println(strings.pop()); - strings.stream() - .map(s -> s + " ") - .forEach(System.out::print); - } + static String[] letters = + "ABCDEFGHIJKLMNOPQRS".split(""); + + public static void main(String[] args) { + FixedSizeStack strings = + new FixedSizeStack<>(letters.length); + Arrays.stream("ABCDEFGHIJKLMNOPQRS".split("")) + .forEach(strings::push); + System.out.println(strings.pop()); + strings.stream() + .map(s -> s + " ") + .forEach(System.out::print); + } } /* Output: S diff --git a/generics/GenericMethods.java b/generics/GenericMethods.java index 3ec451f93..8864ad4aa 100644 --- a/generics/GenericMethods.java +++ b/generics/GenericMethods.java @@ -3,6 +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.Arrays; + public class GenericMethods { public void f(T x) { System.out.println(x.getClass().getName()); diff --git a/generics/GenericReading.java b/generics/GenericReading.java index a661798c5..8f4837971 100644 --- a/generics/GenericReading.java +++ b/generics/GenericReading.java @@ -2,45 +2,57 @@ // (c)2021 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 GenericReading { - static List apples = - Arrays.asList(new Apple()); - static List fruit = Arrays.asList(new Fruit()); - static T readExact(List list) { - return list.get(0); - } - // A static method adapts to each call: - static void f1() { - Apple a = readExact(apples); - Fruit f = readExact(fruit); - f = readExact(apples); - } - // A class type is established - // when the class is instantiated: - static class Reader { - T readExact(List list) { return list.get(0); } - } - 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 - } - static class CovariantReader { - T readCovariant(List list) { - return list.get(0); + static List apples = + Arrays.asList(new Apple()); + static List fruit = Arrays.asList(new Fruit()); + + static T readExact(List list) { + return list.get(0); + } + + // A static method adapts to each call: + static void f1() { + Apple a = readExact(apples); + Fruit f = readExact(fruit); + Fruit apple = readExact(apples); + } + + // A class type is established + // when the class is instantiated: + static class Reader { + T readExact(List list) { + return list.get(0); + } + } + + 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 + } + + static class CovariantReader { + T readCovariant(List list) { + return list.get(0); + } + } + + static void f3() { + CovariantReader fruitReader = + new CovariantReader<>(); + Fruit f = fruitReader.readCovariant(fruit); + Fruit a = fruitReader.readCovariant(apples); + } + + public static void main(String[] args) { + f1(); + f2(); + f3(); } - } - static void f3() { - CovariantReader fruitReader = - new CovariantReader<>(); - Fruit f = fruitReader.readCovariant(fruit); - Fruit a = fruitReader.readCovariant(apples); - } - public static void main(String[] args) { - f1(); f2(); f3(); - } } diff --git a/generics/GenericsAndCovariance.java b/generics/GenericsAndCovariance.java index 023bb8763..af1484489 100644 --- a/generics/GenericsAndCovariance.java +++ b/generics/GenericsAndCovariance.java @@ -9,9 +9,9 @@ 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 Fruit()); - // flist.add(new Object()); +// 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); diff --git a/generics/HijackedInterface.java b/generics/HijackedInterface.java index edf01b7b2..935ffa28c 100644 --- a/generics/HijackedInterface.java +++ b/generics/HijackedInterface.java @@ -4,8 +4,8 @@ // Visit http://OnJava8.com for more book information. // {WillNotCompile} -class Cat - extends ComparablePet implements Comparable{ +//class Cat extends ComparablePet implements Comparable{ +class Cat implements Comparable{ // error: Comparable cannot be inherited with // different arguments: and // class Cat diff --git a/generics/Holder.java b/generics/Holder.java index 50d22a3ca..ed4cae192 100644 --- a/generics/Holder.java +++ b/generics/Holder.java @@ -21,15 +21,15 @@ public static void main(String[] args) { Holder apple = new Holder<>(new Apple()); Apple d = apple.get(); apple.set(d); - // Holder Fruit = apple; // Cannot upcast +// Holder Fruit = apple; // Cannot upcast Holder fruit = apple; // OK Fruit p = fruit.get(); d = (Apple)fruit.get(); // Returns 'Object' try { Orange c = (Orange)fruit.get(); // No warning } catch(Exception e) { System.out.println(e); } - // fruit.set(new Apple()); // Cannot call set() - // fruit.set(new Fruit()); // Cannot call set() +// fruit.set(new Apple()); // Cannot call set() +// fruit.set(new Fruit()); // Cannot call set() System.out.println(fruit.equals(d)); // OK } } diff --git a/generics/InstantiateGenericType.java b/generics/InstantiateGenericType.java index 93c8d62a9..746d14eb2 100644 --- a/generics/InstantiateGenericType.java +++ b/generics/InstantiateGenericType.java @@ -3,7 +3,6 @@ // 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.lang.reflect.InvocationTargetException; class ClassAsFactory implements Supplier { Class kind; diff --git a/generics/IterableFibonacci.java b/generics/IterableFibonacci.java index 2b56b102a..9c5fa5bf1 100644 --- a/generics/IterableFibonacci.java +++ b/generics/IterableFibonacci.java @@ -3,30 +3,42 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Adapt the Fibonacci class to make it Iterable + import java.util.*; public class IterableFibonacci -extends Fibonacci implements Iterable { - private int n; - public IterableFibonacci(int count) { n = count; } - @Override public Iterator iterator() { - return new Iterator() { - @Override - public boolean hasNext() { return n > 0; } - @Override public Integer next() { - n--; - return IterableFibonacci.this.get(); - } - @Override - public void remove() { // Not implemented - throw new UnsupportedOperationException(); - } - }; - } - public static void main(String[] args) { - for(int i : new IterableFibonacci(18)) - System.out.print(i + " "); - } + extends Fibonacci implements Iterable { + private int n; + + public IterableFibonacci(int count) { + n = count; + } + + @Override + public Iterator iterator() { + return new Iterator() { + @Override + public boolean hasNext() { + return n > 0; + } + + @Override + public Integer next() { + n--; + return IterableFibonacci.this.get(); + } + + @Override + public void remove() { // Not implemented + throw new UnsupportedOperationException(); + } + }; + } + + public static void main(String[] args) { + for (int i : new IterableFibonacci(18)) + System.out.print(i + " "); + } } /* Output: 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 diff --git a/generics/ListMaker.java b/generics/ListMaker.java index f127e2dde..6733918af 100644 --- a/generics/ListMaker.java +++ b/generics/ListMaker.java @@ -7,7 +7,8 @@ public class ListMaker { List create() { return new ArrayList<>(); } public static void main(String[] args) { - ListMaker stringMaker = new ListMaker<>(); +// ListMaker stringMaker = new ListMaker<>(); + ListMaker stringMaker = new ListMaker(); List stringList = stringMaker.create(); } } diff --git a/generics/Manipulation.java b/generics/Manipulation.java index f3857515c..87e1a6bd7 100644 --- a/generics/Manipulation.java +++ b/generics/Manipulation.java @@ -8,7 +8,9 @@ class Manipulator { private T obj; Manipulator(T x) { obj = x; } // Error: cannot find symbol: method f(): - public void manipulate() { obj.f(); } + public void manipulate() { +// obj.f(); + } } public class Manipulation { @@ -18,4 +20,4 @@ public static void main(String[] args) { new Manipulator<>(hf); manipulator.manipulate(); } -} +} \ No newline at end of file diff --git a/generics/MultipleInterfaceVariants.java b/generics/MultipleInterfaceVariants.java index c8a58fdd0..adc8371d4 100644 --- a/generics/MultipleInterfaceVariants.java +++ b/generics/MultipleInterfaceVariants.java @@ -1,13 +1,13 @@ -// generics/MultipleInterfaceVariants.java -// (c)2021 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. -// {WillNotCompile} -package generics; - -interface Payable {} - -class Employee implements Payable {} - -class Hourly extends Employee -implements Payable {} +//// generics/MultipleInterfaceVariants.java +//// (c)2021 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. +//// {WillNotCompile} +//package generics; +// +//interface Payable {} +// +//class Employee implements Payable {} +// +//class Hourly extends Employee +//implements Payable {} diff --git a/generics/NeedCasting.java b/generics/NeedCasting.java index e8604e335..2c1ba40e0 100644 --- a/generics/NeedCasting.java +++ b/generics/NeedCasting.java @@ -6,7 +6,7 @@ import java.util.*; public class NeedCasting { - @SuppressWarnings("unchecked") +// @SuppressWarnings("unchecked") public void f(String[] args) throws Exception { ObjectInputStream in = new ObjectInputStream( new FileInputStream(args[0])); diff --git a/generics/NonCovariantGenerics.java b/generics/NonCovariantGenerics.java index 9b56a1d95..5570e763f 100644 --- a/generics/NonCovariantGenerics.java +++ b/generics/NonCovariantGenerics.java @@ -7,5 +7,5 @@ public class NonCovariantGenerics { // Compile Error: incompatible types: - List flist = new ArrayList(); +// List flist = new ArrayList(); } diff --git a/generics/OrdinaryArguments.java b/generics/OrdinaryArguments.java index 02f0d5e15..47cbcef10 100644 --- a/generics/OrdinaryArguments.java +++ b/generics/OrdinaryArguments.java @@ -10,6 +10,7 @@ void set(Base base) { } class DerivedSetter extends OrdinarySetter { +// @Override void set(Derived derived) { System.out.println("DerivedSetter.set(Derived)"); } diff --git a/generics/PrimitiveGenericTest.java b/generics/PrimitiveGenericTest.java index b745a8f72..6aca74c89 100644 --- a/generics/PrimitiveGenericTest.java +++ b/generics/PrimitiveGenericTest.java @@ -2,6 +2,7 @@ // (c)2021 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 java.util.*; import java.util.function.*; @@ -27,14 +28,14 @@ static double[] fill(double[] a, DoubleSupplier gen) { } 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)); - int[] integers = FillArray.fill( - new int[9], new Rand.Pint()); - System.out.println(Arrays.toString(integers)); - } + public static void main(String[] args) { + String[] strings = FillArray.fill( + new String[5], new Rand.String(9)); + System.out.println(Arrays.toString(strings)); + int[] integers = FillArray.fill( + new int[9], new Rand.Pint()); + System.out.println(Arrays.toString(integers)); + } } /* Output: [btpenpccu, xszgvgmei, nneeloztd, vewcippcy, gpoalkljl] diff --git a/generics/SelfBounding.java b/generics/SelfBounding.java index c0c509c3e..ec7ef21cf 100644 --- a/generics/SelfBounding.java +++ b/generics/SelfBounding.java @@ -4,19 +4,29 @@ // Visit http://OnJava8.com for more book information. class SelfBounded> { - T element; - SelfBounded set(T arg) { - element = arg; - return this; - } - T get() { return element; } + T element; + + SelfBounded set(T arg) { + element = arg; + return this; + } + + T get() { + return element; + } } -class A extends SelfBounded {} -class B extends SelfBounded {} // Also OK +class A extends SelfBounded { +} + +class B extends SelfBounded { +} // Also OK class C extends SelfBounded { - C setAndGet(C arg) { set(arg); return get(); } + C setAndGet(C arg) { + set(arg); + return get(); + } } class D {} @@ -26,15 +36,18 @@ class D {} // Type parameter D is not within its bound // Alas, you can do this, so you cannot force the idiom: -class F extends SelfBounded {} +class F extends SelfBounded { +} public class SelfBounding { - public static void main(String[] args) { - A a = new A(); - a.set(new A()); - a = a.set(new A()).get(); - a = a.get(); - C c = new C(); - c = c.setAndGet(new C()); - } + public static void main(String[] args) { + A a = new A(); + a.set(new A()); + a = a.set(new A()).get(); + a = a.get(); +// System.out.println(a.getClass().getSimpleName()); + C c = new C(); + System.out.println(c.getClass().getSimpleName()); + c = c.setAndGet(new C()); + } } diff --git a/generics/SelfBoundingAndCovariantArguments.java b/generics/SelfBoundingAndCovariantArguments.java index eefa864d1..7d0a34126 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/Store.java b/generics/Store.java index 921470845..499c9ad14 100644 --- a/generics/Store.java +++ b/generics/Store.java @@ -3,76 +3,93 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Building a complex model using generic collections + import java.util.*; import java.util.function.*; + import onjava.*; +//import onjava.Suppliers; class Product { - private final int id; - private String description; - private double price; - Product(int idNumber, String descr, double price) { - id = idNumber; - description = descr; - this.price = price; - System.out.println(toString()); - } - @Override public String toString() { - return id + ": " + description + - ", price: $" + price; - } - public void priceChange(double change) { - price += change; - } - public static Supplier generator = - new Supplier() { - private Random rand = new Random(47); - @Override public Product get() { - return new Product(rand.nextInt(1000), "Test", - Math.round( - rand.nextDouble() * 1000.0) + 0.99); - } - }; + private final int id; + private String description; + private double price; + + Product(int idNumber, String descr, double price) { + id = idNumber; + description = descr; + this.price = price; + System.out.println(toString()); + } + + @Override + public String toString() { + return id + ": " + description + + ", price: $" + price; + } + + public void priceChange(double change) { + price += change; + } + + public static Supplier generator = + new Supplier() { + private Random rand = new Random(47); + + @Override + public Product get() { + return new Product(rand.nextInt(1000), "Test", + Math.round( + rand.nextDouble() * 1000.0) + 0.99); + } + }; } class Shelf extends ArrayList { - Shelf(int nProducts) { - Suppliers.fill(this, Product.generator, nProducts); - } + Shelf(int nProducts) { + Suppliers.fill(this, Product.generator, nProducts); + } } class Aisle extends ArrayList { - Aisle(int nShelves, int nProducts) { - for(int i = 0; i < nShelves; i++) - add(new Shelf(nProducts)); - } + Aisle(int nShelves, int nProducts) { + for (int i = 0; i < nShelves; i++) + add(new Shelf(nProducts)); + } } -class CheckoutStand {} -class Office {} +class CheckoutStand { +} + +class Office { +} public class Store extends ArrayList { - private ArrayList checkouts = - new ArrayList<>(); - private Office office = new Office(); - public Store( - int nAisles, int nShelves, int nProducts) { - for(int i = 0; i < nAisles; i++) - add(new Aisle(nShelves, nProducts)); - } - @Override public String toString() { - StringBuilder result = new StringBuilder(); - for(Aisle a : this) - for(Shelf s : a) - for(Product p : s) { - result.append(p); - result.append("\n"); - } - return result.toString(); - } - public static void main(String[] args) { - System.out.println(new Store(5, 4, 3)); - } + private ArrayList checkouts = + new ArrayList<>(); + private Office office = new Office(); + + public Store( + int nAisles, int nShelves, int nProducts) { + for (int i = 0; i < nAisles; i++) + add(new Aisle(nShelves, nProducts)); + } + + @Override + public String toString() { + StringBuilder result = new StringBuilder(); + for (Aisle a : this) + for (Shelf s : a) + for (Product p : s) { + result.append(p); + result.append("\n"); + } + return result.toString(); + } + + public static void main(String[] args) { + System.out.println(new Store(5, 4, 3)); + } } /* Output: (First 8 Lines) 258: Test, price: $400.99 diff --git a/generics/ThrowGenericException.java b/generics/ThrowGenericException.java index 2a8ddb5e9..9c2a313d1 100644 --- a/generics/ThrowGenericException.java +++ b/generics/ThrowGenericException.java @@ -2,79 +2,82 @@ // (c)2021 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; -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(); - } + @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 { - if(count-- == 0) - resultCollector.add(47); - else { - resultCollector.add(11); + 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) + 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.out.println(runner.processAll()); + } catch (Failure1 e) { + System.out.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 { + System.out.println(runner2.processAll()); + } catch (Failure2 e) { + System.out.println(e); + } } - } } /* Output: [Hep!, Hep!, Ho!] diff --git a/generics/TupleList.java b/generics/TupleList.java index 896530b40..7e3167164 100644 --- a/generics/TupleList.java +++ b/generics/TupleList.java @@ -5,7 +5,6 @@ // Combining generic types to make complex generic types import java.util.*; import onjava.*; -import java.util.stream.*; public class TupleList extends ArrayList> { diff --git a/generics/TupleTest2.java b/generics/TupleTest2.java index f889d59f3..636e45200 100644 --- a/generics/TupleTest2.java +++ b/generics/TupleTest2.java @@ -2,36 +2,43 @@ // (c)2021 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.*; public class TupleTest2 { - static Tuple2 f() { - return tuple("hi", 47); - } - static Tuple2 f2() { return tuple("hi", 47); } - static Tuple3 g() { - return tuple(new Amphibian(), "hi", 47); - } - static - Tuple4 h() { - return tuple( - new Vehicle(), new Amphibian(), "hi", 47); - } - static - Tuple5 k() { - return 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()); - } + static Tuple2 f() { + return tuple("hi", 47); + } + + static Tuple2 f2() { + return tuple("hi", 47); + } + + static Tuple3 g() { + return tuple(new Amphibian(), "hi", 47); + } + + static Tuple4 h() { + return tuple( + new Vehicle(), new Amphibian(), "hi", 47); + } + + static Tuple5 k() { + return 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()); + } } /* Output: (hi, 47) diff --git a/generics/UnboundedWildcards1.java b/generics/UnboundedWildcards1.java index 7aada9a6c..4b4631f5c 100644 --- a/generics/UnboundedWildcards1.java +++ b/generics/UnboundedWildcards1.java @@ -11,9 +11,9 @@ public class UnboundedWildcards1 { static void assign1(List list) { list1 = list; list2 = list; - //- list3 = list; +// list3 = list; // warning: [unchecked] unchecked conversion - // list3 = list; +// list3 = list; // ^ // required: List // found: List @@ -31,7 +31,7 @@ static void assign3(List list) { public static void main(String[] args) { assign1(new ArrayList()); assign2(new ArrayList()); - //- assign3(new ArrayList()); + assign3(new ArrayList()); // warning: [unchecked] unchecked method invocation: // method assign3 in class UnboundedWildcards1 // is applied to given types diff --git a/generics/UnboundedWildcards2.java b/generics/UnboundedWildcards2.java index f1e17630e..e72c1e877 100644 --- a/generics/UnboundedWildcards2.java +++ b/generics/UnboundedWildcards2.java @@ -14,7 +14,7 @@ public class UnboundedWildcards2 { public static void main(String[] args) { assign1(new HashMap()); assign2(new HashMap()); - //- assign3(new HashMap()); +// assign3(new HashMap()); // warning: [unchecked] unchecked method invocation: // method assign3 in class UnboundedWildcards2 // is applied to given types diff --git a/generics/UseList.java b/generics/UseList.java index 3c9073aff..70c6cf4a4 100644 --- a/generics/UseList.java +++ b/generics/UseList.java @@ -7,5 +7,5 @@ public class UseList { void f(List v) {} - void f(List v) {} +// void f(List v) {} } diff --git a/generics/WatercolorSets.java b/generics/WatercolorSets.java index 2b285eaaa..5c962f6f7 100644 --- a/generics/WatercolorSets.java +++ b/generics/WatercolorSets.java @@ -2,31 +2,37 @@ // (c)2021 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 onjava.Sets.*; +//import static generics.watercolors.Watercolors.*; +//import static watercolors.Watercolors.BRILLIANT_RED; +import static com.google.common.collect.Sets.*; +import static watercolors.Watercolors.*; public class WatercolorSets { - public static void main(String[] args) { - Set set1 = - 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)); - } + public static void main(String[] args) { + Set set1 = + 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): " + + Sets.complement(set1, set2)); + } } /* Output: set1: [BRILLIANT_RED, CRIMSON, MAGENTA, ROSE_MADDER, diff --git a/generics/Wildcards.java b/generics/Wildcards.java index 7c854bb43..918f6972e 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(); @@ -25,7 +25,7 @@ static void rawArgs(Holder holder, Object arg) { // Like rawArgs(), but errors instead of warnings: static void unboundedArg(Holder holder, Object arg) { - //- holder.set(arg); +// holder.set(arg); // error: method set in class Holder // cannot be applied to given types; // holder.set(arg); @@ -41,7 +41,7 @@ static void rawArgs(Holder holder, Object arg) { // 1 error // 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(); @@ -55,7 +55,7 @@ static T exact2(Holder holder, T arg) { } static T wildSubtype(Holder holder, T arg) { - //- holder.set(arg); +//holder.set(arg); // error: method set in class Holder // cannot be applied to given types; // holder.set(arg); @@ -113,7 +113,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 +138,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 +161,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); @@ -179,7 +179,7 @@ public static void main(String[] args) { // CAP#1 extends Object from capture of ? // 1 error - //- Long r8 = exact2(bounded, lng); +// Long r8 = exact2(bounded, lng); // error: method exact2 in class Wildcards // cannot be applied to given types; // Long r8 = exact2(bounded, lng); @@ -198,7 +198,7 @@ public static void main(String[] args) { // capture of ? extends Long // 1 error - //- Long r9 = wildSubtype(raw, lng); + Long r9 = wildSubtype(raw, lng); // warning: [unchecked] unchecked method invocation: // method wildSubtype in class Wildcards // is applied to given types @@ -224,7 +224,7 @@ public static void main(String[] args) { Object r11 = wildSubtype(unbounded, lng); Long r12 = wildSubtype(bounded, lng); - //- wildSupertype(raw, lng); + wildSupertype(raw, lng); // warning: [unchecked] unchecked method invocation: // method wildSupertype in class Wildcards // is applied to given types @@ -247,7 +247,7 @@ public static void main(String[] args) { wildSupertype(qualified, lng); - //- wildSupertype(unbounded, lng); +// wildSupertype(unbounded, lng); // error: method wildSupertype in class Wildcards // cannot be applied to given types; // wildSupertype(unbounded, lng); @@ -264,7 +264,7 @@ public static void main(String[] args) { // CAP#1 extends Object from capture of ? // 1 error - //- wildSupertype(bounded, lng); +// wildSupertype(bounded, lng); // error: method wildSupertype in class Wildcards // cannot be applied to given types; // wildSupertype(bounded, lng); diff --git a/generics/coffee/Americano.java b/generics/coffee/Americano.java index 86c628288..c2fe745c7 100644 --- a/generics/coffee/Americano.java +++ b/generics/coffee/Americano.java @@ -1,6 +1,9 @@ -// generics/coffee/Americano.java +package coffee;// generics/coffee/Americano.java // (c)2021 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; -public class Americano extends Coffee {} +//package generics.coffee; + +import coffee.Coffee; + +public class Americano extends Coffee {} diff --git a/generics/coffee/Breve.java b/generics/coffee/Breve.java index 5afed481d..79c8e5b2e 100644 --- a/generics/coffee/Breve.java +++ b/generics/coffee/Breve.java @@ -1,6 +1,9 @@ -// generics/coffee/Breve.java +package coffee;// generics/coffee/Breve.java // (c)2021 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 generics.coffee; + +import coffee.Coffee; + public class Breve extends Coffee {} diff --git a/generics/coffee/Cappuccino.java b/generics/coffee/Cappuccino.java index f50486849..f10bddfe4 100644 --- a/generics/coffee/Cappuccino.java +++ b/generics/coffee/Cappuccino.java @@ -1,6 +1,9 @@ -// generics/coffee/Cappuccino.java +package coffee;// generics/coffee/Cappuccino.java // (c)2021 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 generics.coffee; + +import coffee.Coffee; + public class Cappuccino extends Coffee {} diff --git a/generics/coffee/Coffee.java b/generics/coffee/Coffee.java index 3c893cb48..230f607dc 100644 --- a/generics/coffee/Coffee.java +++ b/generics/coffee/Coffee.java @@ -1,8 +1,8 @@ -// generics/coffee/Coffee.java +package coffee;// generics/coffee/Coffee.java // (c)2021 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 generics.coffee; public class Coffee { private static long counter = 0; diff --git a/generics/coffee/CoffeeSupplier.java b/generics/coffee/CoffeeSupplier.java index 90df2e463..4e7604876 100644 --- a/generics/coffee/CoffeeSupplier.java +++ b/generics/coffee/CoffeeSupplier.java @@ -1,59 +1,79 @@ -// generics/coffee/CoffeeSupplier.java +package coffee;// generics/coffee/CoffeeSupplier.java // (c)2021 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; +//package generics.coffee; + +import coffee.Coffee; + import java.util.*; import java.util.function.*; import java.util.stream.*; import java.lang.reflect.InvocationTargetException; -public class CoffeeSupplier -implements Supplier, Iterable { - private Class[] types = { Latte.class, Mocha.class, - Cappuccino.class, Americano.class, Breve.class, }; - private static Random rand = new Random(47); - public CoffeeSupplier() {} - // For iteration: - private int size = 0; - public CoffeeSupplier(int sz) { size = sz; } - @Override public Coffee get() { - try { - return (Coffee) - types[rand.nextInt(types.length)] - .getConstructor().newInstance(); - // Report programmer errors at runtime: - } catch(InstantiationException | - NoSuchMethodException | - InvocationTargetException | - IllegalAccessException e) { - throw new RuntimeException(e); +public class CoffeeSupplier implements Supplier, Iterable { + private Class[] types = {coffee.Latte.class, coffee.Mocha.class, + coffee.Cappuccino.class, coffee.Americano.class, coffee.Breve.class,}; + private static Random rand = new Random(47); + + public CoffeeSupplier() { + } + + // For iteration: + private int size = 0; + + public CoffeeSupplier(int sz) { + size = sz; } - } - class CoffeeIterator implements Iterator { - int count = size; + @Override - public boolean hasNext() { return count > 0; } - @Override public Coffee next() { - count--; - return CoffeeSupplier.this.get(); + public Coffee get() { + try { + return (Coffee) + types[rand.nextInt(types.length)] + .getConstructor().newInstance(); + // Report programmer errors at runtime: + } catch (InstantiationException | + NoSuchMethodException | + InvocationTargetException | + IllegalAccessException e) { + throw new RuntimeException(e); + } } + + class CoffeeIterator implements Iterator { + int count = size; + + @Override + public boolean hasNext() { + return count > 0; + } + + @Override + public Coffee next() { + count--; + return CoffeeSupplier.this.get(); + } + + @Override + public void remove() { // Not implemented + throw new UnsupportedOperationException(); + } + } + @Override - public void remove() { // Not implemented - throw new UnsupportedOperationException(); + public Iterator iterator() { + return new CoffeeIterator(); + } + + public static void main(String[] args) { + Stream.generate(new CoffeeSupplier()) + .limit(5) + .forEach(System.out::println); + for (Coffee c : new CoffeeSupplier(5)) + System.out.println(c); } - } - @Override public Iterator iterator() { - return new CoffeeIterator(); - } - public static void main(String[] args) { - Stream.generate(new CoffeeSupplier()) - .limit(5) - .forEach(System.out::println); - for(Coffee c : new CoffeeSupplier(5)) - System.out.println(c); - } } /* Output: Americano 0 diff --git a/generics/coffee/Latte.java b/generics/coffee/Latte.java index bf4d25831..354da683c 100644 --- a/generics/coffee/Latte.java +++ b/generics/coffee/Latte.java @@ -1,6 +1,9 @@ -// generics/coffee/Latte.java +package coffee;// generics/coffee/Latte.java // (c)2021 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 generics.coffee; + +import coffee.Coffee; + public class Latte extends Coffee {} diff --git a/generics/coffee/Mocha.java b/generics/coffee/Mocha.java index e4eaa5a20..f0c8851e2 100644 --- a/generics/coffee/Mocha.java +++ b/generics/coffee/Mocha.java @@ -1,6 +1,10 @@ +package coffee; + +import coffee.Coffee; + // generics/coffee/Mocha.java // (c)2021 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 generics.coffee; public class Mocha extends Coffee {} diff --git a/generics/decorator/Decoration.java b/generics/decorator/Decoration.java index 07651bb35..4f77e7e43 100644 --- a/generics/decorator/Decoration.java +++ b/generics/decorator/Decoration.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 generics.decorator.Decoration} -package generics.decorator; +package decorator; import java.util.*; class Basic { @@ -42,7 +42,7 @@ public static void main(String[] args) { TimeStamped t = new TimeStamped(new Basic()); TimeStamped t2 = new TimeStamped( new SerialNumbered(new Basic())); - //- t2.getSerialNumber(); // Not available +// t2.getSerialNumber(); // Not available SerialNumbered s = new SerialNumbered(new Basic()); SerialNumbered s2 = new SerialNumbered( new TimeStamped(new Basic())); diff --git a/generics/watercolors/Watercolors.java b/generics/watercolors/Watercolors.java index 33922ba10..c49466b7a 100644 --- a/generics/watercolors/Watercolors.java +++ b/generics/watercolors/Watercolors.java @@ -1,8 +1,8 @@ -// generics/watercolors/Watercolors.java +package watercolors;// generics/watercolors/Watercolors.java // (c)2021 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 generics.watercolors; public enum Watercolors { ZINC, LEMON_YELLOW, MEDIUM_YELLOW, DEEP_YELLOW, diff --git a/gradle/java.gradle b/gradle/java.gradle index 99898c1d0..f4673c86a 100644 --- a/gradle/java.gradle +++ b/gradle/java.gradle @@ -1,7 +1,9 @@ apply plugin: 'java' -sourceCompatibility = '1.8' -targetCompatibility = '1.8' +//sourceCompatibility = '1.8' +sourceCompatibility = '17' +//targetCompatibility = '1.8' +targetCompatibility = '17' compileJava { options.compilerArgs << "-Xlint:unchecked" << "-Xlint:deprecation" diff --git a/innerclasses/AnonymousConstructor.java b/innerclasses/AnonymousConstructor.java index 10a6b6433..042c82824 100644 --- a/innerclasses/AnonymousConstructor.java +++ b/innerclasses/AnonymousConstructor.java @@ -14,7 +14,8 @@ abstract class Base { public class AnonymousConstructor { public static Base getBase(int i) { return new Base(i) { - { System.out.println( + { + System.out.println( "Inside instance initializer"); } @Override public void f() { System.out.println("In anonymous f()"); diff --git a/innerclasses/Callbacks.java b/innerclasses/Callbacks.java index 9031ea242..07429473a 100644 --- a/innerclasses/Callbacks.java +++ b/innerclasses/Callbacks.java @@ -4,7 +4,7 @@ // Visit http://OnJava8.com for more book information. // Using inner classes for callbacks // {java innerclasses.Callbacks} -package innerclasses; +// package innerclasses; interface Incrementable { void increment(); @@ -13,7 +13,8 @@ interface Incrementable { // Very simple to just implement the interface: class Callee1 implements Incrementable { private int i = 0; - @Override public void increment() { + @Override + public void increment() { i++; System.out.println(i); } @@ -28,7 +29,7 @@ public void increment() { // If your class must implement increment() in // some other way, you must use an inner class: -class Callee2 extends MyIncrement { +class Callee2 extends MyIncrement{ private int i = 0; @Override public void increment() { super.increment(); diff --git a/innerclasses/ClassInInterface.java b/innerclasses/ClassInInterface.java index b06042743..cca1b23fd 100644 --- a/innerclasses/ClassInInterface.java +++ b/innerclasses/ClassInInterface.java @@ -6,8 +6,9 @@ public interface ClassInInterface { void howdy(); - class Test implements ClassInInterface { - @Override public void howdy() { + public static class Test implements ClassInInterface { + @Override + public void howdy() { System.out.println("Howdy!"); } public static void main(String[] args) { diff --git a/innerclasses/DotNew.java b/innerclasses/DotNew.java index 3f77dc608..22f425907 100644 --- a/innerclasses/DotNew.java +++ b/innerclasses/DotNew.java @@ -8,6 +8,7 @@ public class DotNew { public class Inner {} public static void main(String[] args) { DotNew dn = new DotNew(); + DotNew.Inner test = dn.new Inner(); DotNew.Inner dni = dn.new Inner(); } } diff --git a/innerclasses/DotThis.java b/innerclasses/DotThis.java index 881ba9a9e..2bf566252 100644 --- a/innerclasses/DotThis.java +++ b/innerclasses/DotThis.java @@ -8,8 +8,9 @@ public class DotThis { void f() { System.out.println("DotThis.f()"); } public class Inner { public DotThis outer() { - return DotThis.this; +// return DotThis.this; // A plain "this" would be Inner's "this" + return DotThis.this; } } public Inner inner() { return new Inner(); } diff --git a/innerclasses/GreenhouseController.java b/innerclasses/GreenhouseController.java index 5ec13cab6..8d6a114ac 100644 --- a/innerclasses/GreenhouseController.java +++ b/innerclasses/GreenhouseController.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. // Configure and execute the greenhouse system -import innerclasses.controller.*; +//import innerclasses.controller.*; + +import controller.Event; public class GreenhouseController { public static void main(String[] args) { diff --git a/innerclasses/GreenhouseControls.java b/innerclasses/GreenhouseControls.java index 4836f8c5e..75cf9ecf2 100644 --- a/innerclasses/GreenhouseControls.java +++ b/innerclasses/GreenhouseControls.java @@ -6,7 +6,10 @@ // control system, all in a single class. Inner // classes allow you to encapsulate different // functionality for each type of event. -import innerclasses.controller.*; +//import innerclasses.controller.*; + +import controller.Controller; +import controller.Event; public class GreenhouseControls extends Controller { private boolean light = false; diff --git a/innerclasses/MultiImplementation.java b/innerclasses/MultiImplementation.java index d5e4869af..4443c6139 100644 --- a/innerclasses/MultiImplementation.java +++ b/innerclasses/MultiImplementation.java @@ -5,7 +5,7 @@ // For concrete or abstract classes, inner classes // produce "multiple implementation inheritance" // {java innerclasses.MultiImplementation} -package innerclasses; +/// package innerclasses; class D {} abstract class E {} diff --git a/innerclasses/Parcel6.java b/innerclasses/Parcel6.java index 4c4325ba9..351acecd2 100644 --- a/innerclasses/Parcel6.java +++ b/innerclasses/Parcel6.java @@ -16,9 +16,10 @@ class TrackingSlip { } TrackingSlip ts = new TrackingSlip("slip"); String s = ts.getSlip(); + System.out.println(s); } // Can't use it here! Out of scope: - //- TrackingSlip ts = new TrackingSlip("x"); + // TrackingSlip ts = new TrackingSlip("x"); } public void track() { internalTracking(true); } public static void main(String[] args) { diff --git a/innerclasses/Parcel9.java b/innerclasses/Parcel9.java index 53053cd16..576d7d409 100644 --- a/innerclasses/Parcel9.java +++ b/innerclasses/Parcel9.java @@ -10,7 +10,9 @@ public Destination destination(final String dest) { return new Destination() { private String label = dest; @Override - public String readLabel() { return label; } + public String readLabel() { + return label; + } }; } public static void main(String[] args) { diff --git a/innerclasses/TestParcel.java b/innerclasses/TestParcel.java index 76ec51bda..1771335b0 100644 --- a/innerclasses/TestParcel.java +++ b/innerclasses/TestParcel.java @@ -30,7 +30,8 @@ public static void main(String[] args) { Parcel4 p = new Parcel4(); Contents c = p.contents(); Destination d = p.destination("Tasmania"); + // Parcel4.PDestination pd = p.new PDestination(); // Illegal -- can't access private class: - //- Parcel4.PContents pc = p.new PContents(); +// Parcel4.PContents pc = p.new PContents(); } } diff --git a/innerclasses/controller/Controller.java b/innerclasses/controller/Controller.java index de766961a..d41f3b958 100644 --- a/innerclasses/controller/Controller.java +++ b/innerclasses/controller/Controller.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. // The reusable framework for control systems -package innerclasses.controller; +//package innerclasses.controller; +package controller; import java.util.*; public class Controller { diff --git a/innerclasses/controller/Event.java b/innerclasses/controller/Event.java index 247e4c90b..f3c7724d7 100644 --- a/innerclasses/controller/Event.java +++ b/innerclasses/controller/Event.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. // The common methods for any control event -package innerclasses.controller; +// package innerclasses.controller; +package controller; + import java.time.*; // Java 8 time classes public abstract class Event { diff --git a/learn.md b/learn.md new file mode 100644 index 000000000..df7ec6c08 --- /dev/null +++ b/learn.md @@ -0,0 +1,8 @@ +## 1 控制框架 +> controller.Event +> +> controller.Controller +> +> GreenhouseControls +> +> GreenhouseController \ No newline at end of file diff --git a/onjava/BasicSupplier.java b/onjava/BasicSupplier.java index 45bb58111..6dfee61bd 100644 --- a/onjava/BasicSupplier.java +++ b/onjava/BasicSupplier.java @@ -3,28 +3,33 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://OnJava8.com for more book information. // Supplier from a class with a zero-argument constructor -package onjava; +//package onjava; + import java.util.function.*; import java.lang.reflect.InvocationTargetException; public class BasicSupplier implements Supplier { - private Class type; - public BasicSupplier(Class type) { - this.type = type; - } - @Override public T get() { - try { - // Assumes type is a public class: - return type.getConstructor().newInstance(); - } catch(InstantiationException | - NoSuchMethodException | - InvocationTargetException | - IllegalAccessException e) { - throw new RuntimeException(e); + private Class type; + + public BasicSupplier(Class type) { + this.type = type; + } + + @Override + public T get() { + try { + // Assumes type is a public class: + return type.getConstructor().newInstance(); + } catch (InstantiationException | + NoSuchMethodException | + InvocationTargetException | + IllegalAccessException e) { + throw new RuntimeException(e); + } + } + + // Produce a default Supplier from a type token: + public static Supplier create(Class type) { + return new BasicSupplier<>(type); } - } - // Produce a default Supplier from a type token: - public static Supplier create(Class type) { - return new BasicSupplier<>(type); - } } diff --git a/onjava/CollectionMethodDifferences.java b/onjava/CollectionMethodDifferences.java index 43262312b..5f6d07165 100644 --- a/onjava/CollectionMethodDifferences.java +++ b/onjava/CollectionMethodDifferences.java @@ -3,57 +3,65 @@ // 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.*; public class CollectionMethodDifferences { - static Set methodSet(Class type) { - return Arrays.stream(type.getMethods()) - .map(Method::getName) - .collect(Collectors.toCollection(TreeSet::new)); - } - static void interfaces(Class type) { - System.out.print("Interfaces in " + - type.getSimpleName() + ": "); - System.out.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() + - " extends " + subset.getSimpleName() + - ", adds: "); - Set comp = Sets.difference( - methodSet(superset), methodSet(subset)); - comp.removeAll(object); // Ignore 'Object' methods - System.out.println(comp); - interfaces(superset); - } - public static void main(String[] args) { - System.out.println("Collection: " + - methodSet(Collection.class)); - interfaces(Collection.class); - difference(Set.class, Collection.class); - difference(HashSet.class, Set.class); - difference(LinkedHashSet.class, HashSet.class); - 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)); - difference(HashMap.class, Map.class); - difference(LinkedHashMap.class, HashMap.class); - difference(SortedMap.class, Map.class); - difference(TreeMap.class, Map.class); - } + static Set methodSet(Class type) { + return Arrays.stream(type.getMethods()) + .map(Method::getName) + .collect(Collectors.toCollection(TreeSet::new)); + } + + static void interfaces(Class type) { + System.out.print("Interfaces in " + + type.getSimpleName() + ": "); + System.out.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() + + " extends " + subset.getSimpleName() + + ", adds: "); + Set comp = Sets.difference( + methodSet(superset), methodSet(subset)); + comp.removeAll(object); // Ignore 'Object' methods + System.out.println(comp); + interfaces(superset); + } + + public static void main(String[] args) { + System.out.println("Collection: " + + methodSet(Collection.class)); + interfaces(Collection.class); + difference(Set.class, Collection.class); + difference(HashSet.class, Set.class); + difference(LinkedHashSet.class, HashSet.class); + 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)); + difference(HashMap.class, Map.class); + difference(LinkedHashMap.class, HashMap.class); + difference(SortedMap.class, Map.class); + difference(TreeMap.class, Map.class); + } } /* Output: Collection: [add, addAll, clear, contains, containsAll, diff --git a/onjava/Null.java b/onjava/Null.java index 9dfae5f2f..66df7013d 100644 --- a/onjava/Null.java +++ b/onjava/Null.java @@ -2,5 +2,5 @@ // (c)2021 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 interface Null {} diff --git a/onjava/Rand.java b/onjava/Rand.java index 1a589302e..08979fb1a 100644 --- a/onjava/Rand.java +++ b/onjava/Rand.java @@ -3,234 +3,309 @@ // 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 -package onjava; +//package onjava; + 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 Rand.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; - } - } + 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 Rand.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/onjava/Repeat.java b/onjava/Repeat.java index 11f4cacd8..8fadf717c 100644 --- a/onjava/Repeat.java +++ b/onjava/Repeat.java @@ -2,7 +2,7 @@ // (c)2021 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 static java.util.stream.IntStream.*; public class Repeat { diff --git a/onjava/RmDir.java b/onjava/RmDir.java index fa6d1a5e9..d65241082 100644 --- a/onjava/RmDir.java +++ b/onjava/RmDir.java @@ -2,7 +2,7 @@ // (c)2021 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; diff --git a/onjava/Sets.java b/onjava/Sets.java index 542f5bb30..82b1b3495 100644 --- a/onjava/Sets.java +++ b/onjava/Sets.java @@ -2,31 +2,38 @@ // (c)2021 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 { - 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)); - } + // 并集 + 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/onjava/SetsTest.java b/onjava/SetsTest.java new file mode 100644 index 000000000..6146bfd22 --- /dev/null +++ b/onjava/SetsTest.java @@ -0,0 +1,32 @@ +import java.util.HashSet; +import java.util.Set; + +public class SetsTest { + public static void main(String[] args) { + Set integerSet1 = new HashSet<>(); + integerSet1.add(1); + integerSet1.add(2); + integerSet1.add(3); + + Set integerSet2 = new HashSet<>(); + integerSet2.add(3); + integerSet2.add(4); + integerSet2.add(5); + + Set union = Sets.union(integerSet1, integerSet2); + Set intersection = Sets.intersection(integerSet1, integerSet2); + Set difference = Sets.difference(integerSet1, integerSet2); + Set complement = Sets.complement(integerSet1, integerSet2); + + System.out.println(union); + System.out.println(intersection); + System.out.println(difference); + System.out.println(complement); + } +} +/* Output: +[1, 2, 3, 4, 5] +[3] +[1, 2] +[1, 2, 4, 5] +*/ diff --git a/onjava/Stack.java b/onjava/Stack.java index 97dc454fa..f15089ba5 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 05ceafab2..938402286 100644 --- a/onjava/Suppliers.java +++ b/onjava/Suppliers.java @@ -3,34 +3,34 @@ // 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.*; 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; - } + // 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/onjava/Timer.java b/onjava/Timer.java index 44a24faed..c5496d53e 100644 --- a/onjava/Timer.java +++ b/onjava/Timer.java @@ -2,7 +2,7 @@ // (c)2021 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 static java.util.concurrent.TimeUnit.*; public class Timer { diff --git a/onjava/Tuple.java b/onjava/Tuple.java deleted file mode 100644 index d1d9b80cd..000000000 --- a/onjava/Tuple.java +++ /dev/null @@ -1,24 +0,0 @@ -// onjava/Tuple.java -// (c)2021 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/onjava/atunit/ClassNameFinder.java b/onjava/atunit/ClassNameFinder.java index 315a44c5f..5c3c04be0 100644 --- a/onjava/atunit/ClassNameFinder.java +++ b/onjava/atunit/ClassNameFinder.java @@ -171,10 +171,10 @@ public static String thisClass(byte[] classBytes) { onjava.Suppliers onjava.TimedAbort onjava.Timer -onjava.Tuple -onjava.Tuple2 -onjava.Tuple3 -onjava.Tuple4 -onjava.Tuple5 +onjava.onjava.Tuple +onjava.onjava.Tuple2 +onjava.onjava.Tuple3 +onjava.onjava.Tuple4 +onjava.onjava.Tuple5 onjava.TypeCounter */ diff --git a/onjava/ArrayShow.java b/onjava/onjava/ArrayShow.java similarity index 100% rename from onjava/ArrayShow.java rename to onjava/onjava/ArrayShow.java diff --git a/onjava/Count.java b/onjava/onjava/Count.java similarity index 100% rename from onjava/Count.java rename to onjava/onjava/Count.java diff --git a/onjava/Pair.java b/onjava/onjava/Pair.java similarity index 100% rename from onjava/Pair.java rename to onjava/onjava/Pair.java diff --git a/onjava/onjava/Tuple.java b/onjava/onjava/Tuple.java new file mode 100644 index 000000000..854bdd937 --- /dev/null +++ b/onjava/onjava/Tuple.java @@ -0,0 +1,27 @@ +package onjava;// onjava/onjava.Tuple.java +// (c)2021 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. +// onjava.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/onjava/Tuple2.java b/onjava/onjava/Tuple2.java similarity index 86% rename from onjava/Tuple2.java rename to onjava/onjava/Tuple2.java index 3e2874a90..330109992 100644 --- a/onjava/Tuple2.java +++ b/onjava/onjava/Tuple2.java @@ -1,8 +1,8 @@ -// onjava/Tuple2.java +package onjava;// onjava/onjava.Tuple2.java // (c)2021 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/onjava/Tuple3.java similarity index 85% rename from onjava/Tuple3.java rename to onjava/onjava/Tuple3.java index 117f4b668..e9b1094be 100644 --- a/onjava/Tuple3.java +++ b/onjava/onjava/Tuple3.java @@ -1,8 +1,8 @@ -// onjava/Tuple3.java +package onjava;// onjava/onjava.Tuple3.java // (c)2021 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/onjava/Tuple4.java similarity index 86% rename from onjava/Tuple4.java rename to onjava/onjava/Tuple4.java index 1a62db093..ea056d04c 100644 --- a/onjava/Tuple4.java +++ b/onjava/onjava/Tuple4.java @@ -1,8 +1,8 @@ -// onjava/Tuple4.java +package onjava;// onjava/onjava.Tuple4.java // (c)2021 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/onjava/Tuple5.java similarity index 86% rename from onjava/Tuple5.java rename to onjava/onjava/Tuple5.java index 85a3d2d06..7c1555792 100644 --- a/onjava/Tuple5.java +++ b/onjava/onjava/Tuple5.java @@ -1,8 +1,8 @@ -// onjava/Tuple5.java +package onjava;// onjava/onjava.Tuple5.java // (c)2021 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/onjava/TypeCounter.java similarity index 100% rename from onjava/TypeCounter.java rename to onjava/onjava/TypeCounter.java diff --git a/patterns/PaperScissorsRock.java b/patterns/PaperScissorsRock.java index 478ac6755..e3054d1e9 100644 --- a/patterns/PaperScissorsRock.java +++ b/patterns/PaperScissorsRock.java @@ -7,7 +7,6 @@ import java.util.function.*; import java.util.stream.*; import enums.Outcome; -import static enums.Outcome.*; import enums.Item; import enums.Paper; import enums.Scissors; diff --git a/reflection/InnerImplementation.java b/reflection/InnerImplementation.java deleted file mode 100644 index 248049c27..000000000 --- a/reflection/InnerImplementation.java +++ /dev/null @@ -1,49 +0,0 @@ -// reflection/InnerImplementation.java -// (c)2021 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 reflection.interfacea.*; - -class InnerA { - private static class C implements A { - @Override public void f() { - System.out.println("public C.f()"); - } - public void g() { - System.out.println("public C.g()"); - } - void u() { - System.out.println("package C.u()"); - } - protected void v() { - System.out.println("protected C.v()"); - } - private void w() { - System.out.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.out.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/reflection/ModifyingPrivateFields.java b/reflection/ModifyingPrivateFields.java deleted file mode 100644 index 99b929531..000000000 --- a/reflection/ModifyingPrivateFields.java +++ /dev/null @@ -1,48 +0,0 @@ -// reflection/ModifyingPrivateFields.java -// (c)2021 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.out.println(pf); - Field f = pf.getClass().getDeclaredField("i"); - f.setAccessible(true); - System.out.println( - "f.getInt(pf): " + f.getInt(pf)); - f.setInt(pf, 47); - System.out.println(pf); - f = pf.getClass().getDeclaredField("s"); - f.setAccessible(true); - System.out.println("f.get(pf): " + f.get(pf)); - f.set(pf, "No, you're not!"); - System.out.println(pf); - f = pf.getClass().getDeclaredField("s2"); - f.setAccessible(true); - System.out.println("f.get(pf): " + f.get(pf)); - f.set(pf, "No, you're not!"); - System.out.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/reflection/NullRobot.java b/reflection/NullRobot.java deleted file mode 100644 index c3e19659f..000000000 --- a/reflection/NullRobot.java +++ /dev/null @@ -1,61 +0,0 @@ -// reflection/NullRobot.java -// (c)2021 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.*; -import onjava.*; - -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 SnowRobot("SnowBee"), - newNullRobot(SnowRobot.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: SnowRobot NullRobot -Robot model: SnowRobot NullRobot -*/ diff --git a/reflection/SnowRobot.java b/reflection/SnowRobot.java deleted file mode 100644 index 227dcb49d..000000000 --- a/reflection/SnowRobot.java +++ /dev/null @@ -1,43 +0,0 @@ -// reflection/SnowRobot.java -// (c)2021 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 SnowRobot implements Robot { - private String name; - public SnowRobot(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.out.println( - name + " shoveling snow")), - new Operation( - () -> name + " can chip ice", - () -> System.out.println(name + " chipping ice")), - new Operation( - () -> name + " can clear the roof", - () -> System.out.println( - name + " clearing roof"))); - @Override - public List operations() { return ops; } - public static void main(String[] args) { - Robot.test(new SnowRobot("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/reflection/pets/Creator.java b/reflection/pets/Creator.java deleted file mode 100644 index f5f152fe8..000000000 --- a/reflection/pets/Creator.java +++ /dev/null @@ -1,38 +0,0 @@ -// reflection/pets/Creator.java -// (c)2021 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 Pets -package reflection.pets; -import java.util.*; -import java.util.function.*; -import java.util.stream.*; -import java.lang.reflect.InvocationTargetException; - -public abstract class Creator implements Supplier { - private Random rand = new Random(47); - // 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); - } - } - public Stream stream() { - return Stream.generate(this); - } - public Pet[] array(int size) { - return stream().limit(size).toArray(Pet[]::new); - } - public List list(int size) { - return stream().limit(size) - .collect(Collectors.toCollection(ArrayList::new)); - } -} diff --git a/reflection/pets/PetCreator.java b/reflection/pets/PetCreator.java deleted file mode 100644 index 1f01ceed3..000000000 --- a/reflection/pets/PetCreator.java +++ /dev/null @@ -1,42 +0,0 @@ -// reflection/pets/PetCreator.java -// (c)2021 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 reflection.pets.PetCreator} -package reflection.pets; -import java.util.*; - -public class PetCreator extends Creator { - // No try block needed. - 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.out.println(TYPES); - List pets = new PetCreator().list(7); - System.out.println(pets); - } -} -/* Output: -[class reflection.pets.Mutt, class reflection.pets.Pug, -class reflection.pets.EgyptianMau, class -reflection.pets.Manx, class reflection.pets.Cymric, class -reflection.pets.Rat, class reflection.pets.Mouse, class -reflection.pets.Hamster] -[Rat, Manx, Cymric, Mutt, Pug, Cymric, Pug] -*/ diff --git a/reflection/AnonymousImplementation.java b/reflection/reflection/AnonymousImplementation.java similarity index 95% rename from reflection/AnonymousImplementation.java rename to reflection/reflection/AnonymousImplementation.java index 290798bbf..d5bbd3e73 100644 --- a/reflection/AnonymousImplementation.java +++ b/reflection/reflection/AnonymousImplementation.java @@ -1,4 +1,4 @@ -// reflection/AnonymousImplementation.java +package reflection;// reflection/AnonymousImplementation.java // (c)2021 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. diff --git a/reflection/BoundedClassReferences.java b/reflection/reflection/BoundedClassReferences.java similarity index 86% rename from reflection/BoundedClassReferences.java rename to reflection/reflection/BoundedClassReferences.java index 6d2960591..b9cf3055e 100644 --- a/reflection/BoundedClassReferences.java +++ b/reflection/reflection/BoundedClassReferences.java @@ -1,4 +1,4 @@ -// reflection/BoundedClassReferences.java +package reflection;// reflection/BoundedClassReferences.java // (c)2021 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. diff --git a/reflection/ClassCasts.java b/reflection/reflection/ClassCasts.java similarity index 89% rename from reflection/ClassCasts.java rename to reflection/reflection/ClassCasts.java index 3efd64c39..2c7be8fbb 100644 --- a/reflection/ClassCasts.java +++ b/reflection/reflection/ClassCasts.java @@ -1,4 +1,4 @@ -// reflection/ClassCasts.java +package reflection;// reflection/ClassCasts.java // (c)2021 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. diff --git a/reflection/ClassInitialization.java b/reflection/reflection/ClassInitialization.java similarity index 92% rename from reflection/ClassInitialization.java rename to reflection/reflection/ClassInitialization.java index 21b711338..a0ccef1ce 100644 --- a/reflection/ClassInitialization.java +++ b/reflection/reflection/ClassInitialization.java @@ -1,4 +1,4 @@ -// reflection/ClassInitialization.java +package reflection;// reflection/ClassInitialization.java // (c)2021 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. @@ -39,7 +39,7 @@ public class ClassInitialization { System.out.println(Initable.STATIC_FINAL2); // Triggers initialization: System.out.println(Initable2.staticNonFinal); - Class initable3 = Class.forName("Initable3"); + Class initable3 = Class.forName("reflection.Initable3"); System.out.println("After creating Initable3 ref"); System.out.println(Initable3.staticNonFinal); } diff --git a/reflection/DynamicSupplier.java b/reflection/reflection/DynamicSupplier.java similarity index 84% rename from reflection/DynamicSupplier.java rename to reflection/reflection/DynamicSupplier.java index 910d12154..65dfa369b 100644 --- a/reflection/DynamicSupplier.java +++ b/reflection/reflection/DynamicSupplier.java @@ -1,7 +1,8 @@ -// reflection/DynamicSupplier.java +package reflection;// reflection/DynamicSupplier.java // (c)2021 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.List; import java.util.function.*; import java.util.stream.*; @@ -34,6 +35,7 @@ public static void main(String[] args) { .skip(10) .limit(5) .forEach(System.out::println); +// List collect = Stream.generate(new DynamicSupplier<>(ID.class)).collect(Collectors.toList()); } } /* Output: diff --git a/reflection/FamilyVsExactType.java b/reflection/reflection/FamilyVsExactType.java similarity index 100% rename from reflection/FamilyVsExactType.java rename to reflection/reflection/FamilyVsExactType.java diff --git a/reflection/GenericClassReferences.java b/reflection/reflection/GenericClassReferences.java similarity index 72% rename from reflection/GenericClassReferences.java rename to reflection/reflection/GenericClassReferences.java index 66601f93c..3c650b340 100644 --- a/reflection/GenericClassReferences.java +++ b/reflection/reflection/GenericClassReferences.java @@ -1,4 +1,4 @@ -// reflection/GenericClassReferences.java +package reflection;// reflection/GenericClassReferences.java // (c)2021 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. @@ -9,6 +9,7 @@ public static void main(String[] args) { intClass = double.class; Class genericIntClass = int.class; genericIntClass = Integer.class; // Same thing - // genericIntClass = double.class; // Illegal +// genericIntClass = double.class; // Illegal +// Class numberClass = int.class; } } diff --git a/reflection/HiddenImplementation.java b/reflection/reflection/HiddenImplementation.java similarity index 89% rename from reflection/HiddenImplementation.java rename to reflection/reflection/HiddenImplementation.java index 1d536d309..645a831d4 100644 --- a/reflection/HiddenImplementation.java +++ b/reflection/reflection/HiddenImplementation.java @@ -1,4 +1,4 @@ -// reflection/HiddenImplementation.java +package reflection;// reflection/HiddenImplementation.java // (c)2021 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. @@ -14,10 +14,10 @@ public class HiddenImplementation { a.f(); System.out.println(a.getClass().getName()); // Compile error: cannot find symbol 'C': - /* if(a instanceof C) { - C c = (C)a; - c.g(); - } */ +// 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! diff --git a/reflection/ID2.java b/reflection/reflection/ID2.java similarity index 93% rename from reflection/ID2.java rename to reflection/reflection/ID2.java index 6ff472af1..5bb1eb11c 100644 --- a/reflection/ID2.java +++ b/reflection/reflection/ID2.java @@ -1,4 +1,4 @@ -// reflection/ID2.java +package reflection;// reflection/ID2.java // (c)2021 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. diff --git a/reflection/reflection/InnerImplementation.java b/reflection/reflection/InnerImplementation.java new file mode 100644 index 000000000..7d58134c9 --- /dev/null +++ b/reflection/reflection/InnerImplementation.java @@ -0,0 +1,57 @@ +package reflection;// reflection/InnerImplementation.java +// (c)2021 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 reflection.interfacea.*; + +class InnerA { + private static class C implements A { + @Override + public void f() { + System.out.println("public C.f()"); + } + + public void g() { + System.out.println("public C.g()"); + } + + void u() { + System.out.println("package C.u()"); + } + + protected void v() { + System.out.println("protected C.v()"); + } + + private void w() { + System.out.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.out.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/reflection/InterfaceViolation.java b/reflection/reflection/InterfaceViolation.java similarity index 90% rename from reflection/InterfaceViolation.java rename to reflection/reflection/InterfaceViolation.java index ef8bfc954..30c95341a 100644 --- a/reflection/InterfaceViolation.java +++ b/reflection/reflection/InterfaceViolation.java @@ -1,4 +1,4 @@ -// reflection/InterfaceViolation.java +package reflection;// reflection/InterfaceViolation.java // (c)2021 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. diff --git a/reflection/reflection/ModifyingPrivateFields.java b/reflection/reflection/ModifyingPrivateFields.java new file mode 100644 index 000000000..8c35ce8a1 --- /dev/null +++ b/reflection/reflection/ModifyingPrivateFields.java @@ -0,0 +1,49 @@ +package reflection;// reflection/ModifyingPrivateFields.java +// (c)2021 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.out.println(pf); + Field f = pf.getClass().getDeclaredField("i"); + f.setAccessible(true); + System.out.println( + "f.getInt(pf): " + f.getInt(pf)); + f.setInt(pf, 47); + System.out.println(pf); + f = pf.getClass().getDeclaredField("s"); + f.setAccessible(true); + System.out.println("f.get(pf): " + f.get(pf)); + f.set(pf, "No, you're not!"); + System.out.println(pf); + f = pf.getClass().getDeclaredField("s2"); + f.setAccessible(true); + System.out.println("f.get(pf): " + f.get(pf)); + f.set(pf, "No, you're not!"); + System.out.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/reflection/reflection/Null.java b/reflection/reflection/Null.java new file mode 100644 index 000000000..10db494f2 --- /dev/null +++ b/reflection/reflection/Null.java @@ -0,0 +1,3 @@ +package reflection; + +public interface Null {} \ No newline at end of file diff --git a/reflection/reflection/NullRobot.java b/reflection/reflection/NullRobot.java new file mode 100644 index 000000000..120ec7e19 --- /dev/null +++ b/reflection/reflection/NullRobot.java @@ -0,0 +1,74 @@ +package reflection;// reflection/NullRobot.java +// (c)2021 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.*; + +import onjava.*; + +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 SnowRobot("SnowBee"), + newNullRobot(SnowRobot.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: SnowRobot NullRobot +Robot model: SnowRobot NullRobot +*/ diff --git a/reflection/Operation.java b/reflection/reflection/Operation.java similarity index 89% rename from reflection/Operation.java rename to reflection/reflection/Operation.java index 4b749e7d1..d98c9af1a 100644 --- a/reflection/Operation.java +++ b/reflection/reflection/Operation.java @@ -1,4 +1,4 @@ -// reflection/Operation.java +package reflection;// reflection/Operation.java // (c)2021 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. diff --git a/reflection/Person.java b/reflection/reflection/Person.java similarity index 95% rename from reflection/Person.java rename to reflection/reflection/Person.java index 070a2490f..c1e7e4ab8 100644 --- a/reflection/Person.java +++ b/reflection/reflection/Person.java @@ -1,9 +1,9 @@ -// reflection/Person.java +package reflection;// reflection/Person.java // (c)2021 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 onjava.*; +//import onjava.*; import java.util.*; class Person { diff --git a/reflection/PetCounter.java b/reflection/reflection/PetCounter.java similarity index 89% rename from reflection/PetCounter.java rename to reflection/reflection/PetCounter.java index 974880620..85f5c151a 100644 --- a/reflection/PetCounter.java +++ b/reflection/reflection/PetCounter.java @@ -1,4 +1,4 @@ -// reflection/PetCounter.java +package reflection;// reflection/PetCounter.java // (c)2021 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. @@ -52,7 +52,9 @@ public void count(Creator creator) { System.out.println(counter); } public static void main(String[] args) { - new PetCounter().count(new ForNamePetCreator()); + PetCounter petCounter = new PetCounter(); + ForNamePetCreator forNamePetCreator = new ForNamePetCreator(); + petCounter.count(forNamePetCreator); } } /* Output: diff --git a/reflection/PetCounter2.java b/reflection/reflection/PetCounter2.java similarity index 91% rename from reflection/PetCounter2.java rename to reflection/reflection/PetCounter2.java index ccac0b57f..b70e12b65 100644 --- a/reflection/PetCounter2.java +++ b/reflection/reflection/PetCounter2.java @@ -1,4 +1,4 @@ -// reflection/PetCounter2.java +package reflection;// reflection/PetCounter2.java // (c)2021 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. diff --git a/reflection/PetCounter3.java b/reflection/reflection/PetCounter3.java similarity index 94% rename from reflection/PetCounter3.java rename to reflection/reflection/PetCounter3.java index aec88ef0b..09423c133 100644 --- a/reflection/PetCounter3.java +++ b/reflection/reflection/PetCounter3.java @@ -1,11 +1,12 @@ -// reflection/PetCounter3.java +package reflection;// reflection/PetCounter3.java // (c)2021 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 java.util.*; import java.util.stream.*; -import onjava.*; +//import onjava.*; +import onjava.Pair; import reflection.pets.*; public class PetCounter3 { diff --git a/reflection/PetCounter4.java b/reflection/reflection/PetCounter4.java similarity index 93% rename from reflection/PetCounter4.java rename to reflection/reflection/PetCounter4.java index 9015e66c7..4973f49c4 100644 --- a/reflection/PetCounter4.java +++ b/reflection/reflection/PetCounter4.java @@ -1,4 +1,4 @@ -// reflection/PetCounter4.java +package reflection;// reflection/PetCounter4.java // (c)2021 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. diff --git a/reflection/Position.java b/reflection/reflection/Position.java similarity index 96% rename from reflection/Position.java rename to reflection/reflection/Position.java index ea07ca78f..d3f4ee492 100644 --- a/reflection/Position.java +++ b/reflection/reflection/Position.java @@ -1,4 +1,4 @@ -// reflection/Position.java +package reflection;// reflection/Position.java // (c)2021 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. diff --git a/reflection/RegisteredFactories.java b/reflection/reflection/RegisteredFactories.java similarity index 93% rename from reflection/RegisteredFactories.java rename to reflection/reflection/RegisteredFactories.java index 04267c425..7c08b3be5 100644 --- a/reflection/RegisteredFactories.java +++ b/reflection/reflection/RegisteredFactories.java @@ -1,4 +1,4 @@ -// reflection/RegisteredFactories.java +package reflection;// reflection/RegisteredFactories.java // (c)2021 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. @@ -8,7 +8,8 @@ import java.util.stream.*; class Part implements Supplier { - @Override public String toString() { + @Override + public String toString() { return getClass().getSimpleName(); } static List> prototypes = @@ -22,7 +23,8 @@ class Part implements Supplier { new GeneratorBelt() ); private static Random rand = new Random(47); - @Override public Part get() { + @Override + public Part get() { int n = rand.nextInt(prototypes.size()); return prototypes.get(n).get(); } diff --git a/reflection/Robot.java b/reflection/reflection/Robot.java similarity index 93% rename from reflection/Robot.java rename to reflection/reflection/Robot.java index 00818d378..1d6a4460c 100644 --- a/reflection/Robot.java +++ b/reflection/reflection/Robot.java @@ -1,4 +1,4 @@ -// reflection/Robot.java +package reflection;// reflection/Robot.java // (c)2021 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. diff --git a/reflection/SelectingMethods.java b/reflection/reflection/SelectingMethods.java similarity index 94% rename from reflection/SelectingMethods.java rename to reflection/reflection/SelectingMethods.java index 9002cf356..8cd5d4730 100644 --- a/reflection/SelectingMethods.java +++ b/reflection/reflection/SelectingMethods.java @@ -1,4 +1,4 @@ -// reflection/SelectingMethods.java +package reflection;// reflection/SelectingMethods.java // (c)2021 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. @@ -13,6 +13,7 @@ class MethodSelector implements InvocationHandler { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + System.out.println("invoke..."); if(method.getName().equals("interesting")) System.out.println( "Proxy detected the interesting method"); diff --git a/reflection/Shapes.java b/reflection/reflection/Shapes.java similarity index 94% rename from reflection/Shapes.java rename to reflection/reflection/Shapes.java index 05d15df5c..cac10b5ec 100644 --- a/reflection/Shapes.java +++ b/reflection/reflection/Shapes.java @@ -1,4 +1,4 @@ -// reflection/Shapes.java +package reflection;// reflection/Shapes.java // (c)2021 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. diff --git a/reflection/ShowMethods.java b/reflection/reflection/ShowMethods.java similarity index 94% rename from reflection/ShowMethods.java rename to reflection/reflection/ShowMethods.java index 48024cdc4..5104d5885 100644 --- a/reflection/ShowMethods.java +++ b/reflection/reflection/ShowMethods.java @@ -1,4 +1,4 @@ -// reflection/ShowMethods.java +package reflection;// reflection/ShowMethods.java // (c)2021 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. @@ -8,7 +8,7 @@ import java.lang.reflect.*; import java.util.regex.*; -public class ShowMethods { + class ShowMethods { private static String usage = "usage:\n" + "ShowMethods qualified.class.name\n" + @@ -17,6 +17,7 @@ public class ShowMethods { "To search for methods involving 'word'"; private static Pattern p = Pattern.compile("\\w+\\."); public static void main(String[] args) { + args = new String[]{"reflection.ShowMethods"}; if(args.length < 1) { System.out.println(usage); System.exit(0); diff --git a/reflection/SimpleDynamicProxy.java b/reflection/reflection/SimpleDynamicProxy.java similarity index 96% rename from reflection/SimpleDynamicProxy.java rename to reflection/reflection/SimpleDynamicProxy.java index 9eeb02926..fa7b9bbde 100644 --- a/reflection/SimpleDynamicProxy.java +++ b/reflection/reflection/SimpleDynamicProxy.java @@ -1,4 +1,4 @@ -// reflection/SimpleDynamicProxy.java +package reflection;// reflection/SimpleDynamicProxy.java // (c)2021 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. diff --git a/reflection/SimpleProxyDemo.java b/reflection/reflection/SimpleProxyDemo.java similarity index 95% rename from reflection/SimpleProxyDemo.java rename to reflection/reflection/SimpleProxyDemo.java index 24f7b0166..47e8f73b8 100644 --- a/reflection/SimpleProxyDemo.java +++ b/reflection/reflection/SimpleProxyDemo.java @@ -1,4 +1,4 @@ -// reflection/SimpleProxyDemo.java +package reflection;// reflection/SimpleProxyDemo.java // (c)2021 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. diff --git a/reflection/reflection/SnowRobot.java b/reflection/reflection/SnowRobot.java new file mode 100644 index 000000000..6d9dbb680 --- /dev/null +++ b/reflection/reflection/SnowRobot.java @@ -0,0 +1,56 @@ +package reflection;// reflection/SnowRobot.java +// (c)2021 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 SnowRobot implements Robot { + private String name; + + public SnowRobot(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.out.println( + name + " shoveling snow")), + new Operation( + () -> name + " can chip ice", + () -> System.out.println(name + " chipping ice")), + new Operation( + () -> name + " can clear the roof", + () -> System.out.println( + name + " clearing roof"))); + + @Override + public List operations() { + return ops; + } + + public static void main(String[] args) { + Robot.test(new SnowRobot("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/reflection/Staff.java b/reflection/reflection/Staff.java similarity index 98% rename from reflection/Staff.java rename to reflection/reflection/Staff.java index 8c3bb76e8..cf9ca990b 100644 --- a/reflection/Staff.java +++ b/reflection/reflection/Staff.java @@ -1,4 +1,4 @@ -// reflection/Staff.java +package reflection;// reflection/Staff.java // (c)2021 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. diff --git a/reflection/SweetShop.java b/reflection/reflection/SweetShop.java similarity index 95% rename from reflection/SweetShop.java rename to reflection/reflection/SweetShop.java index d5f964f0a..3ffe3933a 100644 --- a/reflection/SweetShop.java +++ b/reflection/reflection/SweetShop.java @@ -1,4 +1,4 @@ -// reflection/SweetShop.java +package reflection;// reflection/SweetShop.java // (c)2021 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. diff --git a/reflection/WildcardClassReferences.java b/reflection/reflection/WildcardClassReferences.java similarity index 83% rename from reflection/WildcardClassReferences.java rename to reflection/reflection/WildcardClassReferences.java index d7266f732..fe81de0bd 100644 --- a/reflection/WildcardClassReferences.java +++ b/reflection/reflection/WildcardClassReferences.java @@ -1,4 +1,4 @@ -// reflection/WildcardClassReferences.java +package reflection;// reflection/WildcardClassReferences.java // (c)2021 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. diff --git a/reflection/interfacea/A.java b/reflection/reflection/interfacea/A.java similarity index 100% rename from reflection/interfacea/A.java rename to reflection/reflection/interfacea/A.java diff --git a/reflection/packageaccess/HiddenC.java b/reflection/reflection/packageaccess/HiddenC.java similarity index 100% rename from reflection/packageaccess/HiddenC.java rename to reflection/reflection/packageaccess/HiddenC.java diff --git a/reflection/pets/Cat.java b/reflection/reflection/pets/Cat.java similarity index 100% rename from reflection/pets/Cat.java rename to reflection/reflection/pets/Cat.java diff --git a/reflection/reflection/pets/Creator.java b/reflection/reflection/pets/Creator.java new file mode 100644 index 000000000..2285b1d98 --- /dev/null +++ b/reflection/reflection/pets/Creator.java @@ -0,0 +1,45 @@ +// reflection/pets/Creator.java +// (c)2021 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 Pets +package reflection.pets; + +import java.util.*; +import java.util.function.*; +import java.util.stream.*; +import java.lang.reflect.InvocationTargetException; + +public abstract class Creator implements Supplier { + private Random rand = new Random(47); + + // 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); + } + } + + public Stream stream() { + return Stream.generate(this); + } + + public Pet[] array(int size) { + return stream().limit(size).toArray(Pet[]::new); + } + + public List list(int size) { + return stream().limit(size) + .collect(Collectors.toCollection(ArrayList::new)); + } +} diff --git a/reflection/pets/Cymric.java b/reflection/reflection/pets/Cymric.java similarity index 100% rename from reflection/pets/Cymric.java rename to reflection/reflection/pets/Cymric.java diff --git a/reflection/pets/Dog.java b/reflection/reflection/pets/Dog.java similarity index 100% rename from reflection/pets/Dog.java rename to reflection/reflection/pets/Dog.java diff --git a/reflection/pets/EgyptianMau.java b/reflection/reflection/pets/EgyptianMau.java similarity index 100% rename from reflection/pets/EgyptianMau.java rename to reflection/reflection/pets/EgyptianMau.java diff --git a/reflection/pets/ForNamePetCreator.java b/reflection/reflection/pets/ForNamePetCreator.java similarity index 94% rename from reflection/pets/ForNamePetCreator.java rename to reflection/reflection/pets/ForNamePetCreator.java index 92648db5d..3f34ac5c7 100644 --- a/reflection/pets/ForNamePetCreator.java +++ b/reflection/reflection/pets/ForNamePetCreator.java @@ -30,7 +30,8 @@ private static void loader() { } } static { loader(); } - @Override public List> types() { + @Override + public List> types() { return types; } } diff --git a/reflection/pets/Hamster.java b/reflection/reflection/pets/Hamster.java similarity index 100% rename from reflection/pets/Hamster.java rename to reflection/reflection/pets/Hamster.java diff --git a/reflection/pets/Individual.java b/reflection/reflection/pets/Individual.java similarity index 100% rename from reflection/pets/Individual.java rename to reflection/reflection/pets/Individual.java diff --git a/reflection/pets/Manx.java b/reflection/reflection/pets/Manx.java similarity index 100% rename from reflection/pets/Manx.java rename to reflection/reflection/pets/Manx.java diff --git a/reflection/pets/Mouse.java b/reflection/reflection/pets/Mouse.java similarity index 100% rename from reflection/pets/Mouse.java rename to reflection/reflection/pets/Mouse.java diff --git a/reflection/pets/Mutt.java b/reflection/reflection/pets/Mutt.java similarity index 100% rename from reflection/pets/Mutt.java rename to reflection/reflection/pets/Mutt.java diff --git a/reflection/pets/Person.java b/reflection/reflection/pets/Person.java similarity index 100% rename from reflection/pets/Person.java rename to reflection/reflection/pets/Person.java diff --git a/reflection/pets/Pet.java b/reflection/reflection/pets/Pet.java similarity index 100% rename from reflection/pets/Pet.java rename to reflection/reflection/pets/Pet.java diff --git a/reflection/reflection/pets/PetCreator.java b/reflection/reflection/pets/PetCreator.java new file mode 100644 index 000000000..9fc7a8e67 --- /dev/null +++ b/reflection/reflection/pets/PetCreator.java @@ -0,0 +1,45 @@ +// reflection/pets/PetCreator.java +// (c)2021 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 reflection.pets.PetCreator} +package reflection.pets; + +import java.util.*; + +public class PetCreator extends Creator { + // No try block needed. + 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.out.println(TYPES); + List pets = new PetCreator().list(7); + System.out.println(pets); + } +} +/* Output: +[class reflection.pets.Mutt, class reflection.pets.Pug, +class reflection.pets.EgyptianMau, class +reflection.pets.Manx, class reflection.pets.Cymric, class +reflection.pets.Rat, class reflection.pets.Mouse, class +reflection.pets.Hamster] +[Rat, Manx, Cymric, Mutt, Pug, Cymric, Pug] +*/ diff --git a/reflection/pets/Pug.java b/reflection/reflection/pets/Pug.java similarity index 100% rename from reflection/pets/Pug.java rename to reflection/reflection/pets/Pug.java diff --git a/reflection/pets/Rat.java b/reflection/reflection/pets/Rat.java similarity index 100% rename from reflection/pets/Rat.java rename to reflection/reflection/pets/Rat.java diff --git a/reflection/pets/Rodent.java b/reflection/reflection/pets/Rodent.java similarity index 100% rename from reflection/pets/Rodent.java rename to reflection/reflection/pets/Rodent.java diff --git a/reflection/toys/GenericToyTest.java b/reflection/reflection/toys/GenericToyTest.java similarity index 93% rename from reflection/toys/GenericToyTest.java rename to reflection/reflection/toys/GenericToyTest.java index 3332bcd64..1cd78aa3c 100644 --- a/reflection/toys/GenericToyTest.java +++ b/reflection/reflection/toys/GenericToyTest.java @@ -15,7 +15,7 @@ public class GenericToyTest { ftc.getConstructor().newInstance(); Class up = ftc.getSuperclass(); // This won't compile: - // Class up2 = ftc.getSuperclass(); +// Class up2 = ftc.getSuperclass(); // Only produces Object: Object obj = up.getConstructor().newInstance(); } diff --git a/reflection/toys/ToyTest.java b/reflection/reflection/toys/ToyTest.java similarity index 96% rename from reflection/toys/ToyTest.java rename to reflection/reflection/toys/ToyTest.java index e81e64b7e..30cab0195 100644 --- a/reflection/toys/ToyTest.java +++ b/reflection/reflection/toys/ToyTest.java @@ -45,6 +45,8 @@ public static void main(String[] args) { for(Class face : c.getInterfaces()) printInfo(face); Class up = c.getSuperclass(); +// Class integerClass = int.class; +// Class type = Integer.TYPE; Object obj = null; try { // Requires public zero-argument constructor: diff --git a/reuse/Hide.java b/reuse/Hide.java index e4122091b..ee4f5af26 100644 --- a/reuse/Hide.java +++ b/reuse/Hide.java @@ -5,7 +5,7 @@ // Overloading a base-class method name in a derived // class does not hide the base-class versions -class Homer { +abstract class Homer { char doh(char c) { System.out.println("doh(char)"); return 'd'; @@ -14,6 +14,8 @@ float doh(float f) { System.out.println("doh(float)"); return 1.0f; } + + abstract void doh(Milhouse m); } class Milhouse {} diff --git a/streams/Fibonacci.java b/streams/Fibonacci.java index 0fb47d3f3..26e42f70b 100644 --- a/streams/Fibonacci.java +++ b/streams/Fibonacci.java @@ -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/FileToWordsBuilder.java b/streams/FileToWordsBuilder.java index 5e830b8bb..e8bac187b 100644 --- a/streams/FileToWordsBuilder.java +++ b/streams/FileToWordsBuilder.java @@ -2,29 +2,51 @@ // (c)2021 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.io.*; import java.nio.file.*; import java.util.stream.*; public class FileToWordsBuilder { - Stream.Builder builder = Stream.builder(); - public FileToWordsBuilder(String filePath) - throws Exception { - Files.lines(Paths.get(filePath)) - .skip(1) // Skip the comment line at the beginning - .forEach(line -> { - for(String w : line.split("[ .?,]+")) - builder.add(w); - }); - } - Stream stream() { return builder.build(); } - public static void - main(String[] args) throws Exception { - new FileToWordsBuilder("Cheese.dat").stream() - .limit(7) - .map(w -> w + " ") - .forEach(System.out::print); - } + Stream.Builder builder = Stream.builder(); + + boolean build = false; + + public FileToWordsBuilder(String filePath) throws Exception { + Files.lines(Paths.get(filePath)) + .skip(1) // Skip the comment line at the beginning + .forEach(line -> { + for (String w : line.split("[ .?,]+")) + builder.add(w); + }); + } + + void addStr(String str) { + if (build) { + throw new RuntimeException("already build"); + } + for (String w : str.split("[ .?,]+")) + builder.add(w); + } + + Stream stream() { + build = true; + return builder.build(); + } + + public static void + main(String[] args) throws Exception { + new FileToWordsBuilder("/Users/zss/Projects/OnJava8-Examples/streams/Cheese.dat").stream() + .limit(7) + .map(w -> w + " ") + .forEach(System.out::print); + System.out.println("-------"); + FileToWordsBuilder fileToWordsBuilder = new FileToWordsBuilder("/Users/zss/Projects/OnJava8-Examples/streams/Cheese.dat"); + fileToWordsBuilder.addStr("hello java"); + fileToWordsBuilder.stream().forEach(System.out::println); + + fileToWordsBuilder.addStr("test already build add string"); + } } /* Output: Not much of a cheese shop really diff --git a/streams/FileToWordsRegexp.java b/streams/FileToWordsRegexp.java index f01c853aa..5ce664c5a 100644 --- a/streams/FileToWordsRegexp.java +++ b/streams/FileToWordsRegexp.java @@ -22,7 +22,7 @@ public Stream stream() { public static void main(String[] args) throws Exception { FileToWordsRegexp fw = - new FileToWordsRegexp("Cheese.dat"); + new FileToWordsRegexp("/Users/zss/Projects/OnJava8-Examples/streams/Cheese.dat"); fw.stream() .limit(7) .map(w -> w + " ") diff --git a/streams/FileToWordsTest.java b/streams/FileToWordsTest.java index 7c95bebd5..a10e90e41 100644 --- a/streams/FileToWordsTest.java +++ b/streams/FileToWordsTest.java @@ -7,11 +7,11 @@ public class FileToWordsTest { public static void main(String[] args) throws Exception { - FileToWords.stream("Cheese.dat") + FileToWords.stream("/Users/zss/Projects/OnJava8-Examples/streams/Cheese.dat") .limit(7) .forEach(s -> System.out.format("%s ", s)); System.out.println(); - FileToWords.stream("Cheese.dat") + FileToWords.stream("/Users/zss/Projects/OnJava8-Examples/streams/Cheese.dat") .skip(7) .limit(2) .forEach(s -> System.out.format("%s ", s)); diff --git a/streams/Looping.java b/streams/Looping.java index bfb49d031..986759777 100644 --- a/streams/Looping.java +++ b/streams/Looping.java @@ -2,7 +2,9 @@ // (c)2021 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 onjava.Repeat.*; +//import static onjava.Repeat.*; + +import static java.util.stream.IntStream.range; public class Looping { static void hi() { System.out.println("Hi!"); } @@ -10,6 +12,10 @@ public static void main(String[] args) { repeat(3, () -> System.out.println("Looping!")); repeat(2, Looping::hi); } + + public static void repeat(int n, Runnable action) { + range(0, n).forEach(i -> action.run()); + } } /* Output: Looping! diff --git a/streams/Matching.java b/streams/Matching.java index 4aa6280f5..cabde6032 100644 --- a/streams/Matching.java +++ b/streams/Matching.java @@ -20,6 +20,7 @@ static void show(Matcher match, int val) { n -> n < val)); } public static void main(String[] args) { + show(Stream::allMatch, 10); show(Stream::allMatch, 4); show(Stream::anyMatch, 2); diff --git a/streams/NumericStreamInfo.java b/streams/NumericStreamInfo.java index 3cc6c88e3..7e0e5ae4a 100644 --- a/streams/NumericStreamInfo.java +++ b/streams/NumericStreamInfo.java @@ -22,3 +22,5 @@ public static void main(String[] args) { IntSummaryStatistics{count=100, sum=50794, min=8, average=507.940000, max=998} */ + + diff --git a/streams/Peeking.java b/streams/Peeking.java index 75dcb3467..601df61ff 100644 --- a/streams/Peeking.java +++ b/streams/Peeking.java @@ -6,7 +6,7 @@ class Peeking { public static void main(String[] args) throws Exception { - FileToWords.stream("Cheese.dat") + FileToWords.stream("/Users/zss/Projects/OnJava8-Examples/streams/Cheese.dat") .skip(21) .limit(4) .map(w -> w + " ") diff --git a/streams/RandomWords.java b/streams/RandomWords.java index 6f2df4edc..eb89aab08 100644 --- a/streams/RandomWords.java +++ b/streams/RandomWords.java @@ -19,6 +19,7 @@ public class RandomWords implements Supplier { for(String word : line.split("[ .?,]+")) words.add(word.toLowerCase()); } + System.out.println("111"); } @Override public String get() { return words.get(rand.nextInt(words.size())); @@ -30,7 +31,8 @@ public class RandomWords implements Supplier { public static void main(String[] args) throws Exception { System.out.println( - Stream.generate(new RandomWords("Cheese.dat")) + // /Users/zss/Projects/OnJava8-Examples/streams/Cheese.dat + Stream.generate(new RandomWords("/Users/zss/Projects/OnJava8-Examples/streams/Cheese.dat")) .limit(10) .collect(Collectors.joining(" "))); } diff --git a/streams/Randoms.java b/streams/Randoms.java index 52e05df05..ae5bc1777 100644 --- a/streams/Randoms.java +++ b/streams/Randoms.java @@ -12,6 +12,13 @@ public static void main(String[] args) { .limit(7) .sorted() .forEach(System.out::println); + System.out.println(); + new Random(10) + .ints(10,20) + .distinct() + .limit(5) + .sorted() + .forEach(System.out::println); } } /* Output: diff --git a/streams/SortedComparator.java b/streams/SortedComparator.java index 4d60a6486..32cc0986a 100644 --- a/streams/SortedComparator.java +++ b/streams/SortedComparator.java @@ -2,18 +2,27 @@ // (c)2021 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 SortedComparator { - public static void - main(String[] args) throws Exception { - FileToWords.stream("Cheese.dat") - .skip(10) - .limit(10) - .sorted(Comparator.reverseOrder()) - .map(w -> w + " ") - .forEach(System.out::print); - } + public static void + main(String[] args) throws Exception { + FileToWords.stream("/Users/zss/Projects/OnJava8-Examples/streams/Cheese.dat") + .skip(10) + .limit(10) + .sorted(Comparator.reverseOrder()) + .map(w -> w + " ") + .forEach(System.out::print); + System.out.println(); + FileToWords.stream("/Users/zss/Projects/OnJava8-Examples/streams/Cheese.dat") + .skip(10) + .limit(10) + .sorted(String::compareTo + ) + .map(w -> w + " ") + .forEach(System.out::print); + } } /* Output: you what to the that sir leads in district And diff --git a/streams/SpecialCollector.java b/streams/SpecialCollector.java index 36068bf7b..925ba1022 100644 --- a/streams/SpecialCollector.java +++ b/streams/SpecialCollector.java @@ -9,10 +9,13 @@ public class SpecialCollector { public static void main(String[] args) throws Exception { ArrayList words = - FileToWords.stream("Cheese.dat") - .collect(ArrayList::new, + FileToWords.stream("/Users/zss/Projects/OnJava8-Examples/streams/Cheese.dat") + .collect( + ArrayList::new, ArrayList::add, - ArrayList::addAll); + ArrayList::addAll + ); + System.out.println(words); words.stream() .filter(s -> s.equals("cheese")) .forEach(System.out::println); diff --git a/streams/TreeSetOfWords.java b/streams/TreeSetOfWords.java index 93405f74e..bd7fc75eb 100644 --- a/streams/TreeSetOfWords.java +++ b/streams/TreeSetOfWords.java @@ -10,7 +10,7 @@ public class TreeSetOfWords { public static void main(String[] args) throws Exception { Set words2 = - Files.lines(Paths.get("TreeSetOfWords.java")) + Files.lines(Paths.get("/Users/zss/Projects/OnJava8-Examples/streams/TreeSetOfWords.java")) .flatMap(s -> Arrays.stream(s.split("\\W+"))) .filter(s -> !s.matches("\\d+")) // No numbers .map(String::trim) diff --git a/strings/ArrayListDisplay.java b/strings/ArrayListDisplay.java index 586f013a2..3dc0ff749 100644 --- a/strings/ArrayListDisplay.java +++ b/strings/ArrayListDisplay.java @@ -2,13 +2,15 @@ // (c)2021 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 coffee.CoffeeSupplier; + import java.util.*; import java.util.stream.*; -import generics.coffee.*; +//import generics.coffee.*; public class ArrayListDisplay { public static void main(String[] args) { - List coffees = + List coffees = Stream.generate(new CoffeeSupplier()) .limit(10) .collect(Collectors.toList()); diff --git a/strings/Conversion.java b/strings/Conversion.java index c417c875c..52aeb3178 100644 --- a/strings/Conversion.java +++ b/strings/Conversion.java @@ -15,7 +15,7 @@ public static void main(String[] args) { // f.format("d: %d%n", u); f.format("c: %c%n", u); f.format("b: %b%n", u); - // f.format("f: %f%n", u); +// f.format("f: %f%n", u); // f.format("e: %e%n", u); // f.format("x: %x%n", u); f.format("h: %h%n", u); diff --git a/strings/Hex.java b/strings/Hex.java index 47f05b80f..e33eb18d6 100644 --- a/strings/Hex.java +++ b/strings/Hex.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.Hex} -package onjava; +//package onjava; import java.io.*; import java.nio.file.*; @@ -27,7 +27,7 @@ public static String format(byte[] data) { // Test by displaying this class file: System.out.println(format( Files.readAllBytes(Paths.get( - "build/classes/java/main/onjava/Hex.class")))); + "/Users/zss/Projects/OnJava8-Examples/strings/out/production/classes/Hex.class")))); else System.out.println(format( Files.readAllBytes(Paths.get(args[0])))); diff --git a/strings/InfiniteRecursion.java b/strings/InfiniteRecursion.java index cc523ec88..942742fc4 100644 --- a/strings/InfiniteRecursion.java +++ b/strings/InfiniteRecursion.java @@ -11,7 +11,7 @@ public class InfiniteRecursion { @Override public String toString() { return - " InfiniteRecursion address: " + this + "\n"; + " InfiniteRecursion address: " + super.toString() + "\n"; } public static void main(String[] args) { Stream.generate(InfiniteRecursion::new) diff --git a/strings/TheReplacements.java b/strings/TheReplacements.java index cd543ab59..d8d2ec451 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("/Users/zss/Projects/OnJava8-Examples/strings/TheReplacements.java")) .collect(Collectors.joining("\n")); // Match specially commented block of text above: Matcher mInput = Pattern.compile( diff --git a/validating/BadMicroBenchmark.java b/validating/BadMicroBenchmark.java index 5e1ddbd7c..0f61cb072 100644 --- a/validating/BadMicroBenchmark.java +++ b/validating/BadMicroBenchmark.java @@ -4,7 +4,7 @@ // Visit http://OnJava8.com for more book information. // {ExcludeFromTravisCI} import java.util.*; -import onjava.Timer; +//import onjava.Timer; public class BadMicroBenchmark { static final int SIZE = 250_000_000; diff --git a/validating/BadMicroBenchmark2.java b/validating/BadMicroBenchmark2.java index aab204bfb..a9462cd24 100644 --- a/validating/BadMicroBenchmark2.java +++ b/validating/BadMicroBenchmark2.java @@ -4,7 +4,7 @@ // 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: diff --git a/validating/CircularQueue.java b/validating/CircularQueue.java index b42509cf9..f9fa62ca2 100644 --- a/validating/CircularQueue.java +++ b/validating/CircularQueue.java @@ -3,89 +3,102 @@ // 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; +//package validating; + import java.util.*; 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; + 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(); } - 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; + + 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); } - 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/CircularQueueException.java b/validating/CircularQueueException.java index c30710df0..655e326ac 100644 --- a/validating/CircularQueueException.java +++ b/validating/CircularQueueException.java @@ -2,11 +2,11 @@ // (c)2021 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 { - public CircularQueueException(String why) { - super(why); - } + public CircularQueueException(String why) { + super(why); + } } diff --git a/validating/CountedList.java b/validating/CountedList.java index 30de1acc5..6015c495a 100644 --- a/validating/CountedList.java +++ b/validating/CountedList.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. // Keeps track of how many of itself are created. -package validating; +//package validating; import java.util.*; public class CountedList extends ArrayList { diff --git a/validating/GuavaAssertions.java b/validating/GuavaAssertions.java index 85c724f6f..b8e81f19f 100644 --- a/validating/GuavaAssertions.java +++ b/validating/GuavaAssertions.java @@ -1,49 +1,54 @@ -// validating/GuavaAssertions.java -// (c)2021 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. -// Assertions that are always enabled. -import com.google.common.base.*; -import static com.google.common.base.Verify.*; - -public class GuavaAssertions { - public static void main(String[] args) { - verify(2 + 2 == 4); - try { - verify(1 + 2 == 4); - } catch(VerifyException e) { - System.out.println(e); - } - try { - verify(1 + 2 == 4, "Bad math"); - } catch(VerifyException e) { - System.out.println(e.getMessage()); - } - try { - verify(1 + 2 == 4, "Bad math: %s", "not 4"); - } catch(VerifyException e) { - System.out.println(e.getMessage()); - } - String s = ""; - s = verifyNotNull(s); - s = null; - try { - verifyNotNull(s); - } catch(VerifyException e) { - System.out.println(e.getMessage()); - } - try { - verifyNotNull( - s, "Shouldn't be null: %s", "arg s"); - } catch(VerifyException e) { - System.out.println(e.getMessage()); - } - } -} -/* Output: -com.google.common.base.VerifyException -Bad math -Bad math: not 4 -expected a non-null reference -Shouldn't be null: arg s -*/ +//// validating/GuavaAssertions.java +//// (c)2021 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. +//// Assertions that are always enabled. +////import com.google.common.base.*; +////import static com.google.common.base.Verify.*; +// +//import org.gradle.internal.impldep.com.google.common.base.VerifyException; +// +//import static org.gradle.internal.impldep.com.google.common.base.Verify.verify; +//import static org.gradle.internal.impldep.com.google.common.base.Verify.verifyNotNull; +// +//public class GuavaAssertions { +// public static void main(String[] args) { +// verify(2 + 2 == 4); +// try { +// verify(1 + 2 == 4); +// } catch(VerifyException e) { +// System.out.println(e); +// } +// try { +// verify(1 + 2 == 4, "Bad math"); +// } catch(VerifyException e) { +// System.out.println(e.getMessage()); +// } +// try { +// verify(1 + 2 == 4, "Bad math: %s", "not 4"); +// } catch(VerifyException e) { +// System.out.println(e.getMessage()); +// } +// String s = ""; +// s = verifyNotNull(s); +// s = null; +// try { +// verifyNotNull(s); +// } catch(VerifyException e) { +// System.out.println(e.getMessage()); +// } +// try { +// verifyNotNull( +// s, "Shouldn't be null: %s", "arg s"); +// } catch(VerifyException e) { +// System.out.println(e.getMessage()); +// } +// } +//} +///* Output: +//com.google.common.base.VerifyException +//Bad math +//Bad math: not 4 +//expected a non-null reference +//Shouldn't be null: arg s +//*/ diff --git a/validating/GuavaPreconditions.java b/validating/GuavaPreconditions.java index f8f9c702a..ea8d11cae 100644 --- a/validating/GuavaPreconditions.java +++ b/validating/GuavaPreconditions.java @@ -4,7 +4,9 @@ // Visit http://OnJava8.com for more book information. // Demonstrating Guava Preconditions import java.util.function.*; -import static com.google.common.base.Preconditions.*; + +import static org.gradle.internal.impldep.com.google.common.base.Preconditions.*; +//import static com.google.common.base.Preconditions.*; public class GuavaPreconditions { static void test(Consumer c, String s) { diff --git a/validating/SLF4JLogging.java b/validating/SLF4JLogging.java index f8eeb696c..41c3e7a22 100644 --- a/validating/SLF4JLogging.java +++ b/validating/SLF4JLogging.java @@ -2,7 +2,10 @@ // (c)2021 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 org.slf4j.*; +//import org.slf4j.*; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class SLF4JLogging { private static Logger log = diff --git a/validating/jmh/JMH1.java b/validating/jmh/JMH1.java index 63657c3fa..5ae367d5a 100644 --- a/validating/jmh/JMH1.java +++ b/validating/jmh/JMH1.java @@ -1,8 +1,8 @@ -// validating/jmh/JMH1.java +package jmh;// validating/jmh/JMH1.java // (c)2021 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.jmh; +//package validating.jmh; import java.util.*; import org.openjdk.jmh.annotations.*; import java.util.concurrent.TimeUnit; diff --git a/validating/jmh/JMH2.java b/validating/jmh/JMH2.java index 5010b00ed..4caaa0e9e 100644 --- a/validating/jmh/JMH2.java +++ b/validating/jmh/JMH2.java @@ -1,8 +1,8 @@ -// validating/jmh/JMH2.java +package jmh;// validating/jmh/JMH2.java // (c)2021 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.jmh; +//package validating.jmh; import java.util.*; import org.openjdk.jmh.annotations.*; import java.util.concurrent.TimeUnit; diff --git a/validating/jmh/JMH3.java b/validating/jmh/JMH3.java index 7bf22de11..9e9a7b4d8 100644 --- a/validating/jmh/JMH3.java +++ b/validating/jmh/JMH3.java @@ -1,8 +1,8 @@ -// validating/jmh/JMH3.java +package jmh;// validating/jmh/JMH3.java // (c)2021 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.jmh; +//package validating.jmh; import java.util.*; import org.openjdk.jmh.annotations.*; import java.util.concurrent.TimeUnit; diff --git a/validating/tests/CircularQueueTest.java b/validating/tests/CircularQueueTest.java index 920b459be..ac3380f1b 100644 --- a/validating/tests/CircularQueueTest.java +++ b/validating/tests/CircularQueueTest.java @@ -2,7 +2,7 @@ // (c)2021 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.*; diff --git a/validating/tests/CountedListTest.java b/validating/tests/CountedListTest.java index 74a29b376..086176cdd 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.*;