Format/Streamify

This commit is contained in:
Bruce Eckel 2017-01-20 21:30:44 -08:00
parent 18ade9f18e
commit f3ef6ec758
52 changed files with 332 additions and 180 deletions

View File

@ -23,7 +23,9 @@ public class AtUnitExample1 {
@Test private boolean m3() { return true; } @Test private boolean m3() { return true; }
// Shows output for failure: // Shows output for failure:
@Test boolean failureTest() { return false; } @Test boolean failureTest() { return false; }
@Test boolean anotherDisappointment() { return false; } @Test boolean anotherDisappointment() {
return false;
}
} }
/* Output: /* Output:
annotations.AtUnitExample1 annotations.AtUnitExample1

View File

@ -15,11 +15,14 @@ public class AtUnitExample4 {
"middle, and then thin again at the far end."; "middle, and then thin again at the far end.";
private String word; private String word;
private Random rand = new Random(); // Time-based seed private Random rand = new Random(); // Time-based seed
public AtUnitExample4(String word) { this.word = word; } public AtUnitExample4(String word) {
this.word = word;
}
public String getWord() { return word; } public String getWord() { return word; }
public String scrambleWord() { public String scrambleWord() {
List<Character> chars = List<Character> chars =
Arrays.asList(ConvertTo.boxed(word.toCharArray())); Arrays.asList(
ConvertTo.boxed(word.toCharArray()));
Collections.shuffle(chars, rand); Collections.shuffle(chars, rand);
StringBuilder result = new StringBuilder(); StringBuilder result = new StringBuilder();
for(char ch : chars) for(char ch : chars)
@ -41,7 +44,7 @@ public class AtUnitExample4 {
return getWord().equals("are"); return getWord().equals("are");
} }
@Test boolean scramble1() { @Test boolean scramble1() {
// Change to specific seed to get verifiable results: // Use specific seed to get verifiable results:
rand = new Random(47); rand = new Random(47);
System.out.println("'" + getWord() + "'"); System.out.println("'" + getWord() + "'");
String scrambled = scrambleWord(); String scrambled = scrambleWord();

View File

@ -11,7 +11,9 @@ import onjava.*;
public class AtUnitExample5 { public class AtUnitExample5 {
private String text; private String text;
public AtUnitExample5(String text) { this.text = text; } public AtUnitExample5(String text) {
this.text = text;
}
@Override @Override
public String toString() { return text; } public String toString() { return text; }
@TestProperty static PrintWriter output; @TestProperty static PrintWriter output;

View File

@ -9,11 +9,14 @@ package annotations;
import onjava.atunit.*; import onjava.atunit.*;
import onjava.*; import onjava.*;
public class AtUnitExternalTest extends AtUnitExample1 { public class
AtUnitExternalTest extends AtUnitExample1 {
@Test boolean tMethodOne() { @Test boolean tMethodOne() {
return methodOne().equals("This is methodOne"); return methodOne().equals("This is methodOne");
} }
@Test boolean tMethodTwo() { return methodTwo() == 2; } @Test boolean tMethodTwo() {
return methodTwo() == 2;
}
} }
/* Output: /* Output:
annotations.AtUnitExternalTest annotations.AtUnitExternalTest

View File

@ -12,7 +12,8 @@ public class PasswordUtils {
} }
@UseCase(id = 48) @UseCase(id = 48)
public String encryptPassword(String passwd) { public String encryptPassword(String passwd) {
return new StringBuilder(passwd).reverse().toString(); return new StringBuilder(passwd)
.reverse().toString();
} }
@UseCase(id = 49, description = @UseCase(id = 49, description =
"New passwords can't equal previously used ones") "New passwords can't equal previously used ones")

View File

@ -9,7 +9,8 @@ package annotations;
import onjava.atunit.*; import onjava.atunit.*;
import onjava.*; import onjava.*;
public class StackLStringTest extends StackL<String> { public class
StackLStringTest extends StackL<String> {
@Test void tPush() { @Test void tPush() {
push("one"); push("one");
assert top().equals("one"); assert top().equals("one");

View File

@ -9,7 +9,7 @@ import static onjava.ArrayShow.*;
public class ArrayOptions { public class ArrayOptions {
public static void main(String[] args) { public static void main(String[] args) {
// Arrays of objects: // Arrays of objects:
BerylliumSphere[] a; // Local uninitialized variable BerylliumSphere[] a; // Uninitialized local
BerylliumSphere[] b = new BerylliumSphere[5]; BerylliumSphere[] b = new BerylliumSphere[5];
// The references inside the array are // The references inside the array are

View File

@ -10,12 +10,15 @@ class BerylliumSphere {
private static long counter; private static long counter;
private final long id = counter++; private final long id = counter++;
@Override @Override
public String toString() { return "Sphere " + id; } public String toString() {
return "Sphere " + id;
}
} }
public class CollectionComparison { public class CollectionComparison {
public static void main(String[] args) { public static void main(String[] args) {
BerylliumSphere[] spheres = new BerylliumSphere[10]; BerylliumSphere[] spheres =
new BerylliumSphere[10];
for(int i = 0; i < 5; i++) for(int i = 0; i < 5; i++)
spheres[i] = new BerylliumSphere(); spheres[i] = new BerylliumSphere();
show(spheres); show(spheres);

View File

@ -20,7 +20,8 @@ public class TestCount {
show(a1); show(a1);
a1 = new Count.Boolean().array(SZ + 2); a1 = new Count.Boolean().array(SZ + 2);
show(a1); show(a1);
boolean[] a1b = new Count.Pboolean().array(SZ + 3); boolean[] a1b =
new Count.Pboolean().array(SZ + 3);
show(a1b); show(a1b);
System.out.println("Byte"); System.out.println("Byte");
@ -63,8 +64,9 @@ public class TestCount {
int[] a5 = new int[SZ]; int[] a5 = new int[SZ];
Arrays.setAll(a5, new Count.Integer()::get); Arrays.setAll(a5, new Count.Integer()::get);
show(a5); show(a5);
Integer[] a5b = Stream.generate(new Count.Integer()) Integer[] a5b =
.limit(SZ + 1).toArray(Integer[]::new); Stream.generate(new Count.Integer())
.limit(SZ + 1).toArray(Integer[]::new);
show(a5b); show(a5b);
a5b = new Count.Integer().array(SZ + 2); a5b = new Count.Integer().array(SZ + 2);
show(a5b); show(a5b);
@ -105,8 +107,9 @@ public class TestCount {
double[] a8 = new double[SZ]; double[] a8 = new double[SZ];
Arrays.setAll(a8, new Count.Double()::get); Arrays.setAll(a8, new Count.Double()::get);
show(a8); show(a8);
Double[] a8b = Stream.generate(new Count.Double()) Double[] a8b =
.limit(SZ + 1).toArray(Double[]::new); Stream.generate(new Count.Double())
.limit(SZ + 1).toArray(Double[]::new);
show(a8b); show(a8b);
a8b = new Count.Double().array(SZ + 2); a8b = new Count.Double().array(SZ + 2);
show(a8b); show(a8b);

View File

@ -20,7 +20,8 @@ public class TestRand {
show(a1); show(a1);
a1 = new Rand.Boolean().array(SZ + 2); a1 = new Rand.Boolean().array(SZ + 2);
show(a1); show(a1);
boolean[] a1b = new Rand.Pboolean().array(SZ + 3); boolean[] a1b =
new Rand.Pboolean().array(SZ + 3);
show(a1b); show(a1b);
System.out.println("Byte"); System.out.println("Byte");
@ -63,8 +64,9 @@ public class TestRand {
int[] a5 = new int[SZ]; int[] a5 = new int[SZ];
Arrays.setAll(a5, new Rand.Integer()::get); Arrays.setAll(a5, new Rand.Integer()::get);
show(a5); show(a5);
Integer[] a5b = Stream.generate(new Rand.Integer()) Integer[] a5b =
.limit(SZ + 1).toArray(Integer[]::new); Stream.generate(new Rand.Integer())
.limit(SZ + 1).toArray(Integer[]::new);
show(a5b); show(a5b);
a5b = new Rand.Integer().array(SZ + 2); a5b = new Rand.Integer().array(SZ + 2);
show(a5b); show(a5b);
@ -105,8 +107,9 @@ public class TestRand {
double[] a8 = new double[SZ]; double[] a8 = new double[SZ];
Arrays.setAll(a8, new Rand.Double()::get); Arrays.setAll(a8, new Rand.Double()::get);
show(a8); show(a8);
Double[] a8b = Stream.generate(new Rand.Double()) Double[] a8b =
.limit(SZ + 1).toArray(Double[]::new); Stream.generate(new Rand.Double())
.limit(SZ + 1).toArray(Double[]::new);
show(a8b); show(a8b);
a8b = new Rand.Double().array(SZ + 2); a8b = new Rand.Double().array(SZ + 2);
show(a8b); show(a8b);

View File

@ -52,13 +52,17 @@ public class CarWash {
} }
EnumSet<Cycle> cycles = EnumSet<Cycle> cycles =
EnumSet.of(Cycle.BASIC, Cycle.RINSE); EnumSet.of(Cycle.BASIC, Cycle.RINSE);
public void add(Cycle cycle) { cycles.add(cycle); } public void add(Cycle cycle) {
cycles.add(cycle);
}
public void washCar() { public void washCar() {
for(Cycle c : cycles) for(Cycle c : cycles)
c.action(); c.action();
} }
@Override @Override
public String toString() { return cycles.toString(); } public String toString() {
return cycles.toString();
}
public static void main(String[] args) { public static void main(String[] args) {
CarWash wash = new CarWash(); CarWash wash = new CarWash();
System.out.println(wash); System.out.println(wash);

View File

@ -10,7 +10,8 @@ public enum ConstantSpecificMethod {
@Override @Override
String getInfo() { String getInfo() {
return return
DateFormat.getDateInstance().format(new Date()); DateFormat.getDateInstance()
.format(new Date());
} }
}, },
CLASSPATH { CLASSPATH {

View File

@ -11,15 +11,18 @@ import static enums.AlarmPoints.*;
public class EnumSets { public class EnumSets {
public static void main(String[] args) { public static void main(String[] args) {
EnumSet<AlarmPoints> points = EnumSet<AlarmPoints> points =
EnumSet.noneOf(AlarmPoints.class); // Empty set EnumSet.noneOf(AlarmPoints.class); // Empty
points.add(BATHROOM); points.add(BATHROOM);
System.out.println(points); System.out.println(points);
points.addAll(EnumSet.of(STAIR1, STAIR2, KITCHEN)); points.addAll(
EnumSet.of(STAIR1, STAIR2, KITCHEN));
System.out.println(points); System.out.println(points);
points = EnumSet.allOf(AlarmPoints.class); points = EnumSet.allOf(AlarmPoints.class);
points.removeAll(EnumSet.of(STAIR1, STAIR2, KITCHEN)); points.removeAll(
EnumSet.of(STAIR1, STAIR2, KITCHEN));
System.out.println(points); System.out.println(points);
points.removeAll(EnumSet.range(OFFICE1, OFFICE4)); points.removeAll(
EnumSet.range(OFFICE1, OFFICE4));
System.out.println(points); System.out.println(points);
points = EnumSet.complementOf(points); points = EnumSet.complementOf(points);
System.out.println(points); System.out.println(points);

View File

@ -16,16 +16,18 @@ public enum Input {
STOP { // This must be the last instance. STOP { // This must be the last instance.
@Override @Override
public int amount() { // Disallow public int amount() { // Disallow
throw new RuntimeException("SHUT_DOWN.amount()"); throw new
RuntimeException("SHUT_DOWN.amount()");
} }
}; };
int value; // In cents int value; // In cents
Input(int value) { this.value = value; } Input(int value) { this.value = value; }
Input() {} Input() {}
int amount() { return value; }; // In cents int amount() { return value; }; // In cents
static SplittableRandom rand = new SplittableRandom(47); static Random rand = new Random(47);
public static Input randomSelection() { public static Input randomSelection() {
// Don't include STOP: // Don't include STOP:
return values()[rand.nextInt(values().length - 1)]; return
values()[rand.nextInt(values().length - 1)];
} }
} }

View File

@ -7,15 +7,21 @@
enum LikeClasses { enum LikeClasses {
WINKEN { WINKEN {
@Override @Override
void behavior() { System.out.println("Behavior1"); } void behavior() {
System.out.println("Behavior1");
}
}, },
BLINKEN { BLINKEN {
@Override @Override
void behavior() { System.out.println("Behavior2"); } void behavior() {
System.out.println("Behavior2");
}
}, },
NOD { NOD {
@Override @Override
void behavior() { System.out.println("Behavior3"); } void behavior() {
System.out.println("Behavior3");
}
}; };
abstract void behavior(); abstract void behavior();
} }

View File

@ -7,9 +7,13 @@ public enum OverrideConstantSpecific {
NUT, BOLT, NUT, BOLT,
WASHER { WASHER {
@Override @Override
void f() { System.out.println("Overridden method"); } void f() {
System.out.println("Overridden method");
}
}; };
void f() { System.out.println("default behavior"); } void f() {
System.out.println("default behavior");
}
public static void main(String[] args) { public static void main(String[] args) {
for(OverrideConstantSpecific ocs : values()) { for(OverrideConstantSpecific ocs : values()) {
System.out.print(ocs + ": "); System.out.print(ocs + ": ");

View File

@ -7,7 +7,7 @@ import java.util.*;
import onjava.*; import onjava.*;
class Mail { class Mail {
// The NO's lower the probability of random selection: // The NO's reduce probability of random selection:
enum GeneralDelivery {YES,NO1,NO2,NO3,NO4,NO5} enum GeneralDelivery {YES,NO1,NO2,NO3,NO4,NO5}
enum Scannability {UNSCANNABLE,YES1,YES2,YES3,YES4} enum Scannability {UNSCANNABLE,YES1,YES2,YES3,YES4}
enum Readability {ILLEGIBLE,YES1,YES2,YES3,YES4} enum Readability {ILLEGIBLE,YES1,YES2,YES3,YES4}
@ -35,10 +35,13 @@ class Mail {
Mail m = new Mail(); Mail m = new Mail();
m.generalDelivery = m.generalDelivery =
Enums.random(GeneralDelivery.class); Enums.random(GeneralDelivery.class);
m.scannability = Enums.random(Scannability.class); m.scannability =
m.readability = Enums.random(Readability.class); Enums.random(Scannability.class);
m.readability =
Enums.random(Readability.class);
m.address = Enums.random(Address.class); m.address = Enums.random(Address.class);
m.returnAddress = Enums.random(ReturnAddress.class); m.returnAddress =
Enums.random(ReturnAddress.class);
return m; return m;
} }
public static public static
@ -49,9 +52,13 @@ class Mail {
public Iterator<Mail> iterator() { public Iterator<Mail> iterator() {
return new Iterator<Mail>() { return new Iterator<Mail>() {
@Override @Override
public boolean hasNext() { return n-- > 0; } public boolean hasNext() {
return n-- > 0;
}
@Override @Override
public Mail next() { return randomMail(); } public Mail next() {
return randomMail();
}
@Override @Override
public void remove() { // Not implemented public void remove() { // Not implemented
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();

View File

@ -26,15 +26,18 @@ public class Reflection {
return methods; return methods;
} }
public static void main(String[] args) { public static void main(String[] args) {
Set<String> exploreMethods = analyze(Explore.class); Set<String> exploreMethods =
analyze(Explore.class);
Set<String> enumMethods = analyze(Enum.class); Set<String> enumMethods = analyze(Enum.class);
System.out.println("Explore.containsAll(Enum)? " + System.out.println(
"Explore.containsAll(Enum)? " +
exploreMethods.containsAll(enumMethods)); exploreMethods.containsAll(enumMethods));
System.out.print("Explore.removeAll(Enum): "); System.out.print("Explore.removeAll(Enum): ");
exploreMethods.removeAll(enumMethods); exploreMethods.removeAll(enumMethods);
System.out.println(exploreMethods); System.out.println(exploreMethods);
// Decompile the code for the enum: // Decompile the code for the enum:
OSExecute.command("javap -cp build/classes/main Explore"); OSExecute.command(
"javap -cp build/classes/main Explore");
} }
} }
/* Output: /* Output:

View File

@ -62,7 +62,7 @@ class Rock implements Item {
public class RoShamBo1 { public class RoShamBo1 {
static final int SIZE = 20; static final int SIZE = 20;
private static SplittableRandom rand = new SplittableRandom(47); private static Random rand = new Random(47);
public static Item newItem() { public static Item newItem() {
switch(rand.nextInt(3)) { switch(rand.nextInt(3)) {
default: default:

View File

@ -6,14 +6,19 @@
import onjava.*; import onjava.*;
enum SecurityCategory { enum SecurityCategory {
STOCK(Security.Stock.class), BOND(Security.Bond.class); STOCK(Security.Stock.class),
BOND(Security.Bond.class);
Security[] values; Security[] values;
SecurityCategory(Class<? extends Security> kind) { SecurityCategory(Class<? extends Security> kind) {
values = kind.getEnumConstants(); values = kind.getEnumConstants();
} }
interface Security { interface Security {
enum Stock implements Security { SHORT, LONG, MARGIN } enum Stock implements Security {
enum Bond implements Security { MUNICIPAL, JUNK } SHORT, LONG, MARGIN
}
enum Bond implements Security {
MUNICIPAL, JUNK
}
} }
public Security randomSelection() { public Security randomSelection() {
return Enums.random(values); return Enums.random(values);

View File

@ -14,7 +14,8 @@ public enum SpaceShip {
return id.charAt(0) + lower; return id.charAt(0) + lower;
} }
public static void main(String[] args) { public static void main(String[] args) {
Stream.of(values()).forEach(System.out::println); Stream.of(values())
.forEach(System.out::println);
} }
} }
/* Output: /* Output:

View File

@ -125,7 +125,9 @@ public class VendingMachine {
// For a basic sanity check: // For a basic sanity check:
class RandomInputSupplier implements Supplier<Input> { class RandomInputSupplier implements Supplier<Input> {
@Override @Override
public Input get() { return Input.randomSelection(); } public Input get() {
return Input.randomSelection();
}
} }
// Create Inputs from a file of ';'-separated strings: // Create Inputs from a file of ';'-separated strings:
@ -147,7 +149,8 @@ class FileInputSupplier implements Supplier<Input> {
public Input get() { public Input get() {
if(!input.hasNext()) if(!input.hasNext())
return null; return null;
return Enum.valueOf(Input.class, input.next().trim()); return Enum.valueOf(
Input.class, input.next().trim());
} }
} }
/* Output: /* Output:

View File

@ -10,8 +10,10 @@ import java.util.function.*;
enum CartoonCharacter enum CartoonCharacter
implements Supplier<CartoonCharacter> { implements Supplier<CartoonCharacter> {
SLAPPY, SPANKY, PUNCHY, SILLY, BOUNCY, NUTTY, BOB; SLAPPY, SPANKY, PUNCHY,
private SplittableRandom rand = new SplittableRandom(47); SILLY, BOUNCY, NUTTY, BOB;
private Random rand =
new Random(47);
@Override @Override
public CartoonCharacter get() { public CartoonCharacter get() {
return values()[rand.nextInt(values().length)]; return values()[rand.nextInt(values().length)];

View File

@ -8,15 +8,13 @@ import java.nio.file.*;
public class ListOfLines { public class ListOfLines {
public static void public static void
main(String[] args) throws Exception { main(String[] args) throws Exception {
List<String> lines = Files.readAllLines( Files.readAllLines(
Paths.get("../streams/Cheese.dat")); Paths.get("../streams/Cheese.dat"))
for(String line : lines) { .stream()
if(line.startsWith("//")) .filter(line -> !line.startsWith("//"))
continue; .map(line ->
System.out.println( line.substring(0, line.length()/2))
line.substring(0, line.length()/2)); .forEach(System.out::println);
}
} }
} }
/* Output: /* Output:

View File

@ -10,19 +10,26 @@ class Customer {
private static long counter = 1; private static long counter = 1;
private final long id = counter++; private final long id = counter++;
@Override @Override
public String toString() { return "Customer " + id; } public String toString() {
return "Customer " + id;
}
} }
class Teller { class Teller {
private static long counter = 1; private static long counter = 1;
private final long id = counter++; private final long id = counter++;
@Override @Override
public String toString() { return "Teller " + id; } public String toString() {
return "Teller " + id;
}
} }
class Bank { class Bank {
private List<BankTeller> tellers = new ArrayList<>(); private List<BankTeller> tellers =
public void put(BankTeller bt) { tellers.add(bt); } new ArrayList<>();
public void put(BankTeller bt) {
tellers.add(bt);
}
} }
public class BankTeller { public class BankTeller {
@ -32,17 +39,20 @@ public class BankTeller {
public static void main(String[] args) { public static void main(String[] args) {
// Demonstrate create(): // Demonstrate create():
RandomList<Teller> tellers = RandomList<Teller> tellers =
Suppliers.create(RandomList::new, Teller::new, 4); Suppliers.create(
RandomList::new, Teller::new, 4);
// Demonstrate fill(): // Demonstrate fill():
List<Customer> customers = Suppliers.fill( List<Customer> customers = Suppliers.fill(
new ArrayList<>(), Customer::new, 12); new ArrayList<>(), Customer::new, 12);
customers.forEach(c -> serve(tellers.select(), c)); customers.forEach(c ->
serve(tellers.select(), c));
// Demonstrate assisted latent typing: // Demonstrate assisted latent typing:
Bank bank = Suppliers.fill( Bank bank = Suppliers.fill(
new Bank(), Bank::put, BankTeller::new, 3); new Bank(), Bank::put, BankTeller::new, 3);
// Can also use second version of fill(): // Can also use second version of fill():
List<Customer> customers2 = Suppliers.fill( List<Customer> customers2 = Suppliers.fill(
new ArrayList<>(), List::add, Customer::new, 12); new ArrayList<>(),
List::add, Customer::new, 12);
} }
} }
/* Output: /* Output:

View File

@ -7,7 +7,9 @@ class Subtype extends BasicHolder<Subtype> {}
public class CRGWithBasicHolder { public class CRGWithBasicHolder {
public static void main(String[] args) { public static void main(String[] args) {
Subtype st1 = new Subtype(), st2 = new Subtype(); Subtype
st1 = new Subtype(),
st2 = new Subtype();
st1.set(st2); st1.set(st2);
Subtype st3 = st1.get(); Subtype st3 = st1.get();
st1.f(); st1.f();

View File

@ -6,5 +6,7 @@
public class ComparablePet public class ComparablePet
implements Comparable<ComparablePet> { implements Comparable<ComparablePet> {
@Override @Override
public int compareTo(ComparablePet arg) { return 0; } public int compareTo(ComparablePet arg) {
return 0;
}
} }

View File

@ -11,7 +11,7 @@ interface OrdinaryGetter {
} }
interface DerivedGetter extends OrdinaryGetter { interface DerivedGetter extends OrdinaryGetter {
// Return type of overridden method is allowed to vary: // Overridden method return type can vary:
@Override @Override
Derived get(); Derived get();
} }

View File

@ -2,30 +2,46 @@
// (c)2017 MindView LLC: see Copyright.txt // (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information. // Visit http://OnJava8.com for more book information.
import java.util.*;
import java.util.stream.*; import java.util.stream.*;
class FixedSizeStack<T> { class FixedSizeStack<T> {
private int index = 0; private final int size;
private Object[] storage; private Object[] storage;
private int index = 0;
public FixedSizeStack(int size) { public FixedSizeStack(int size) {
this.size = size;
storage = new Object[size]; storage = new Object[size];
} }
public void push(T item) { storage[index++] = item; } public void push(T item) {
if(index < size)
storage[index++] = item;
}
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public T pop() { return (T)storage[--index]; } public T pop() {
return index == 0 ? null : (T)storage[--index];
}
@SuppressWarnings("unchecked")
Stream<T> stream() {
return (Stream<T>)Arrays.stream(storage);
}
} }
public class GenericCast { public class GenericCast {
public static final int SIZE = 10; static String[] letters =
"ABCDEFGHIJKLMNOPQRS".split("");
public static void main(String[] args) { public static void main(String[] args) {
FixedSizeStack<String> strings = FixedSizeStack<String> strings =
new FixedSizeStack<>(SIZE); new FixedSizeStack<>(letters.length);
Stream.of("A B C D E F G H I J".split(" ")) Arrays.stream("ABCDEFGHIJKLMNOPQRS".split(""))
.forEach(s -> strings.push(s)); .forEach(strings::push);
for(int i = 0; i < SIZE; i++) System.out.println(strings.pop());
System.out.print(strings.pop() + " "); strings.stream()
.map(s -> s + " ")
.forEach(System.out::print);
} }
} }
/* Output: /* Output:
J I H G F E D C B A S
A B C D E F G H I J K L M N O P Q R S
*/ */

View File

@ -4,5 +4,7 @@
// Visit http://OnJava8.com for more book information. // Visit http://OnJava8.com for more book information.
public class HasF { public class HasF {
public void f() { System.out.println("HasF.f()"); } public void f() {
System.out.println("HasF.f()");
}
} }

View File

@ -9,23 +9,19 @@ import java.util.function.*;
// Fill an array using a generator: // Fill an array using a generator:
interface FillArray { interface FillArray {
static <T> T[] fill(T[] a, Supplier<T> gen) { static <T> T[] fill(T[] a, Supplier<T> gen) {
for(int i = 0; i < a.length; i++) Arrays.setAll(a, n -> gen.get());
a[i] = gen.get();
return a; return a;
} }
static int[] fill(int[] a, IntSupplier gen) { static int[] fill(int[] a, IntSupplier gen) {
for(int i = 0; i < a.length; i++) Arrays.setAll(a, n -> gen.getAsInt());
a[i] = gen.getAsInt();
return a; return a;
} }
static long[] fill(long[] a, LongSupplier gen) { static long[] fill(long[] a, LongSupplier gen) {
for(int i = 0; i < a.length; i++) Arrays.setAll(a, n -> gen.getAsLong());
a[i] = gen.getAsLong();
return a; return a;
} }
static double[] fill(double[] a, DoubleSupplier gen) { static double[] fill(double[] a, DoubleSupplier gen) {
for(int i = 0; i < a.length; i++) Arrays.setAll(a, n -> gen.getAsDouble());
a[i] = gen.getAsDouble();
return a; return a;
} }
} }

View File

@ -5,11 +5,15 @@
class Hamster extends ComparablePet class Hamster extends ComparablePet
implements Comparable<ComparablePet> { implements Comparable<ComparablePet> {
public int compareTo(ComparablePet arg) { return 0; } public int compareTo(ComparablePet arg) {
return 0;
}
} }
// Or just: // Or just:
class Gecko extends ComparablePet { class Gecko extends ComparablePet {
public int compareTo(ComparablePet arg) { return 0; } public int compareTo(ComparablePet arg) {
return 0;
}
} }

View File

@ -35,7 +35,7 @@ public class SimpleClient2 implements Runnable {
// Enable auto-flush: // Enable auto-flush:
socket.getOutputStream())), true) socket.getOutputStream())), true)
) { ) {
for (int i = 0; i < 25; i++) { for(int i = 0; i < 25; i++) {
out.println("Client " + id + ": " + i); out.println("Client " + id + ": " + i);
String str = in.readLine(); String str = in.readLine();
System.out.println(str); System.out.println(str);

View File

@ -17,7 +17,9 @@ public interface Count {
b = !b; b = !b;
return java.lang.Boolean.valueOf(b); return java.lang.Boolean.valueOf(b);
} }
public java.lang.Boolean get(int n) { return get(); } public java.lang.Boolean get(int n) {
return get();
}
public java.lang.Boolean[] array(int sz) { public java.lang.Boolean[] array(int sz) {
java.lang.Boolean[] result = java.lang.Boolean[] result =
new java.lang.Boolean[sz]; new java.lang.Boolean[sz];
@ -41,9 +43,12 @@ public interface Count {
private byte b; private byte b;
@Override @Override
public java.lang.Byte get() { return b++; } public java.lang.Byte get() { return b++; }
public java.lang.Byte get(int n) { return get(); } public java.lang.Byte get(int n) {
return get();
}
public java.lang.Byte[] array(int sz) { public java.lang.Byte[] array(int sz) {
java.lang.Byte[] result = new java.lang.Byte[sz]; java.lang.Byte[] result =
new java.lang.Byte[sz];
Arrays.setAll(result, n -> get()); Arrays.setAll(result, n -> get());
return result; return result;
} }
@ -92,9 +97,12 @@ public interface Count {
short s; short s;
@Override @Override
public java.lang.Short get() { return s++; } public java.lang.Short get() { return s++; }
public java.lang.Short get(int n) { return get(); } public java.lang.Short get(int n) {
return get();
}
public java.lang.Short[] array(int sz) { public java.lang.Short[] array(int sz) {
java.lang.Short[] result = new java.lang.Short[sz]; java.lang.Short[] result =
new java.lang.Short[sz];
Arrays.setAll(result, n -> get()); Arrays.setAll(result, n -> get());
return result; return result;
} }
@ -112,7 +120,9 @@ public interface Count {
int i; int i;
@Override @Override
public java.lang.Integer get() { return i++; } public java.lang.Integer get() { return i++; }
public java.lang.Integer get(int n) { return get(); } public java.lang.Integer get(int n) {
return get();
}
public java.lang.Integer[] array(int sz) { public java.lang.Integer[] array(int sz) {
java.lang.Integer[] result = java.lang.Integer[] result =
new java.lang.Integer[sz]; new java.lang.Integer[sz];
@ -135,14 +145,18 @@ public interface Count {
private long l; private long l;
@Override @Override
public java.lang.Long get() { return l++; } public java.lang.Long get() { return l++; }
public java.lang.Long get(int n) { return get(); } public java.lang.Long get(int n) {
return get();
}
public java.lang.Long[] array(int sz) { public java.lang.Long[] array(int sz) {
java.lang.Long[] result = new java.lang.Long[sz]; java.lang.Long[] result =
new java.lang.Long[sz];
Arrays.setAll(result, n -> get()); Arrays.setAll(result, n -> get());
return result; return result;
} }
} }
public static class Plong implements LongSupplier { public static
class Plong implements LongSupplier {
private long l; private long l;
public long get() { return l++; } public long get() { return l++; }
public long get(int n) { return get(); } public long get(int n) { return get(); }
@ -159,9 +173,12 @@ public interface Count {
public java.lang.Float get() { public java.lang.Float get() {
return java.lang.Float.valueOf(i++); return java.lang.Float.valueOf(i++);
} }
public java.lang.Float get(int n) { return get(); } public java.lang.Float get(int n) {
return get();
}
public java.lang.Float[] array(int sz) { public java.lang.Float[] array(int sz) {
java.lang.Float[] result = new java.lang.Float[sz]; java.lang.Float[] result =
new java.lang.Float[sz];
Arrays.setAll(result, n -> get()); Arrays.setAll(result, n -> get());
return result; return result;
} }
@ -181,7 +198,9 @@ public interface Count {
public java.lang.Double get() { public java.lang.Double get() {
return java.lang.Double.valueOf(i++); return java.lang.Double.valueOf(i++);
} }
public java.lang.Double get(int n) { return get(); } public java.lang.Double get(int n) {
return get();
}
public java.lang.Double[] array(int sz) { public java.lang.Double[] array(int sz) {
java.lang.Double[] result = java.lang.Double[] result =
new java.lang.Double[sz]; new java.lang.Double[sz];

View File

@ -6,7 +6,7 @@ package onjava;
import java.util.*; import java.util.*;
public class Enums { public class Enums {
private static SplittableRandom rand = new SplittableRandom(47); private static Random rand = new Random(47);
public static public static
<T extends Enum<T>> T random(Class<T> ec) { <T extends Enum<T>> T random(Class<T> ec) {
return random(ec.getEnumConstants()); return random(ec.getEnumConstants());

View File

@ -39,9 +39,12 @@ public interface Rand {
public java.lang.Byte get() { public java.lang.Byte get() {
return (byte)r.nextInt(MOD); return (byte)r.nextInt(MOD);
} }
public java.lang.Byte get(int n) { return get(); } public java.lang.Byte get(int n) {
return get();
}
public java.lang.Byte[] array(int sz) { public java.lang.Byte[] array(int sz) {
java.lang.Byte[] result = new java.lang.Byte[sz]; java.lang.Byte[] result =
new java.lang.Byte[sz];
Arrays.setAll(result, n -> get()); Arrays.setAll(result, n -> get());
return result; return result;
} }
@ -80,9 +83,12 @@ public interface Rand {
public java.lang.Short get() { public java.lang.Short get() {
return (short)r.nextInt(MOD); return (short)r.nextInt(MOD);
} }
public java.lang.Short get(int n) { return get(); } public java.lang.Short get(int n) {
return get();
}
public java.lang.Short[] array(int sz) { public java.lang.Short[] array(int sz) {
java.lang.Short[] result = new java.lang.Short[sz]; java.lang.Short[] result =
new java.lang.Short[sz];
Arrays.setAll(result, n -> get()); Arrays.setAll(result, n -> get());
return result; return result;
} }
@ -99,7 +105,9 @@ public interface Rand {
public java.lang.Integer get() { public java.lang.Integer get() {
return r.nextInt(MOD); return r.nextInt(MOD);
} }
public java.lang.Integer get(int n) { return get(); } public java.lang.Integer get(int n) {
return get();
}
public java.lang.Integer[] array(int sz) { public java.lang.Integer[] array(int sz) {
int[] primitive = new Pint().array(sz); int[] primitive = new Pint().array(sz);
java.lang.Integer[] result = java.lang.Integer[] result =
@ -112,7 +120,9 @@ public interface Rand {
public static class Pint implements IntSupplier { public static class Pint implements IntSupplier {
SplittableRandom r = new SplittableRandom(47); SplittableRandom r = new SplittableRandom(47);
@Override @Override
public int getAsInt() { return r.nextInt(MOD); } public int getAsInt() {
return r.nextInt(MOD);
}
public int get(int n) { return getAsInt(); } public int get(int n) { return getAsInt(); }
public int[] array(int sz) { public int[] array(int sz) {
return r.ints(sz, 0, MOD).toArray(); return r.ints(sz, 0, MOD).toArray();
@ -125,16 +135,20 @@ public interface Rand {
public java.lang.Long get() { public java.lang.Long get() {
return r.nextLong(MOD); return r.nextLong(MOD);
} }
public java.lang.Long get(int n) { return get(); } public java.lang.Long get(int n) {
return get();
}
public java.lang.Long[] array(int sz) { public java.lang.Long[] array(int sz) {
long[] primitive = new Plong().array(sz); long[] primitive = new Plong().array(sz);
java.lang.Long[] result = new java.lang.Long[sz]; java.lang.Long[] result =
new java.lang.Long[sz];
for(int i = 0; i < sz; i++) for(int i = 0; i < sz; i++)
result[i] = primitive[i]; result[i] = primitive[i];
return result; return result;
} }
} }
public static class Plong implements LongSupplier { public static
class Plong implements LongSupplier {
SplittableRandom r = new SplittableRandom(47); SplittableRandom r = new SplittableRandom(47);
@Override @Override
public long getAsLong() { public long getAsLong() {
@ -152,9 +166,12 @@ public interface Rand {
public java.lang.Float get() { public java.lang.Float get() {
return (float)trim(r.nextDouble()); return (float)trim(r.nextDouble());
} }
public java.lang.Float get(int n) { return get(); } public java.lang.Float get(int n) {
return get();
}
public java.lang.Float[] array(int sz) { public java.lang.Float[] array(int sz) {
java.lang.Float[] result = new java.lang.Float[sz]; java.lang.Float[] result =
new java.lang.Float[sz];
Arrays.setAll(result, n -> get()); Arrays.setAll(result, n -> get());
return result; return result;
} }
@ -165,7 +182,8 @@ public interface Rand {
} }
} }
static double trim(double d) { static double trim(double d) {
return ((double)Math.round(d * 1000.0)) / 100.0; return
((double)Math.round(d * 1000.0)) / 100.0;
} }
public static class Double public static class Double
implements Supplier<java.lang.Double> { implements Supplier<java.lang.Double> {
@ -174,9 +192,12 @@ public interface Rand {
public java.lang.Double get() { public java.lang.Double get() {
return trim(r.nextDouble()); return trim(r.nextDouble());
} }
public java.lang.Double get(int n) { return get(); } public java.lang.Double get(int n) {
return get();
}
public java.lang.Double[] array(int sz) { public java.lang.Double[] array(int sz) {
double[] primitive = new Rand.Pdouble().array(sz); double[] primitive =
new Rand.Pdouble().array(sz);
java.lang.Double[] result = java.lang.Double[] result =
new java.lang.Double[sz]; new java.lang.Double[sz];
for(int i = 0; i < sz; i++) for(int i = 0; i < sz; i++)
@ -184,13 +205,16 @@ public interface Rand {
return result; return result;
} }
} }
public static class Pdouble implements DoubleSupplier { public static
class Pdouble implements DoubleSupplier {
SplittableRandom r = new SplittableRandom(47); SplittableRandom r = new SplittableRandom(47);
@Override @Override
public double getAsDouble() { public double getAsDouble() {
return trim(r.nextDouble()); return trim(r.nextDouble());
} }
public double get(int n) { return getAsDouble(); } public double get(int n) {
return getAsDouble();
}
public double[] array(int sz) { public double[] array(int sz) {
double[] result = r.doubles(sz).toArray(); double[] result = r.doubles(sz).toArray();
Arrays.setAll(result, Arrays.setAll(result,
@ -201,7 +225,7 @@ public interface Rand {
public static class String public static class String
implements Supplier<java.lang.String> { implements Supplier<java.lang.String> {
SplittableRandom r = new SplittableRandom(47); SplittableRandom r = new SplittableRandom(47);
private int strlen = 7; // Default string length private int strlen = 7; // Default length
public String() {} public String() {}
public String(int strLength) { public String(int strLength) {
strlen = strLength; strlen = strLength;
@ -213,7 +237,9 @@ public interface Rand {
StringBuilder::appendCodePoint, StringBuilder::appendCodePoint,
StringBuilder::append).toString(); StringBuilder::append).toString();
} }
public java.lang.String get(int n) { return get(); } public java.lang.String get(int n) {
return get();
}
public java.lang.String[] array(int sz) { public java.lang.String[] array(int sz) {
java.lang.String[] result = java.lang.String[] result =
new java.lang.String[sz]; new java.lang.String[sz];

View File

@ -5,6 +5,7 @@
// Counts instances of a type family // Counts instances of a type family
package onjava; package onjava;
import java.util.*; import java.util.*;
import java.util.stream.*;
public class public class
TypeCounter extends HashMap<Class<?>, Integer> { TypeCounter extends HashMap<Class<?>, Integer> {
@ -30,15 +31,11 @@ TypeCounter extends HashMap<Class<?>, Integer> {
} }
@Override @Override
public String toString() { public String toString() {
StringBuilder result = new StringBuilder("{"); String result = entrySet().stream()
for(Map.Entry<Class<?>, Integer> pair : entrySet()) { .map(pair -> String.format("%s=%s",
result.append(pair.getKey().getSimpleName()); pair.getKey().getSimpleName(),
result.append("="); pair.getValue()))
result.append(pair.getValue()); .collect(Collectors.joining(", "));
result.append(", "); return "{" + result + "}";
}
result.delete(result.length() - 2, result.length());
result.append("}");
return result.toString();
} }
} }

View File

@ -12,6 +12,7 @@ public class Aluminum extends patterns.trash.Aluminum
public Aluminum(double wt) { super(wt); } public Aluminum(double wt) { super(wt); }
@Override @Override
public boolean addToBin(List<TypedBin> tbins) { public boolean addToBin(List<TypedBin> tbins) {
return tbins.stream().anyMatch(tb -> tb.add(this)); return tbins.stream()
.anyMatch(tb -> tb.add(this));
} }
} }

View File

@ -12,6 +12,7 @@ public class Cardboard extends patterns.trash.Cardboard
public Cardboard(double wt) { super(wt); } public Cardboard(double wt) { super(wt); }
@Override @Override
public boolean addToBin(List<TypedBin> tbins) { public boolean addToBin(List<TypedBin> tbins) {
return tbins.stream().anyMatch(tb -> tb.add(this)); return tbins.stream()
.anyMatch(tb -> tb.add(this));
} }
} }

View File

@ -65,7 +65,8 @@ public class DoubleDispatch {
// individually-typed bins: // individually-typed bins:
bins.sortIntoBins(bin); bins.sortIntoBins(bin);
// Perform sumValue for each bin... // Perform sumValue for each bin...
bins.binSet().forEach(tb -> Trash.sumValue(tb.v)); bins.binSet()
.forEach(tb -> Trash.sumValue(tb.v));
// ... and for the master bin // ... and for the master bin
Trash.sumValue(bin); Trash.sumValue(bin);
} }

View File

@ -12,6 +12,7 @@ public class Glass extends patterns.trash.Glass
public Glass(double wt) { super(wt); } public Glass(double wt) { super(wt); }
@Override @Override
public boolean addToBin(List<TypedBin> tbins) { public boolean addToBin(List<TypedBin> tbins) {
return tbins.stream().anyMatch(tb -> tb.add(this)); return tbins.stream()
.anyMatch(tb -> tb.add(this));
} }
} }

View File

@ -12,6 +12,7 @@ public class Paper extends patterns.trash.Paper
public Paper(double wt) { super(wt); } public Paper(double wt) { super(wt); }
@Override @Override
public boolean addToBin(List<TypedBin> tbins) { public boolean addToBin(List<TypedBin> tbins) {
return tbins.stream().anyMatch(tb -> tb.add(this)); return tbins.stream()
.anyMatch(tb -> tb.add(this));
} }
} }

View File

@ -7,7 +7,7 @@ package patterns.doubledispatch;
import patterns.trash.*; import patterns.trash.*;
import java.util.*; import java.util.*;
public abstract class TypedBin { public class TypedBin {
List<Trash> v = new ArrayList<>(); List<Trash> v = new ArrayList<>();
protected boolean addIt(Trash t) { protected boolean addIt(Trash t) {
v.add(t); v.add(t);

View File

@ -26,14 +26,14 @@ class Tbin<T extends Trash> extends ArrayList<T> {
} }
class TbinList<T extends Trash> class TbinList<T extends Trash>
extends ArrayList<Tbin<? extends T>> { // [*1*] extends ArrayList<Tbin<? extends T>> { // [1]
boolean sort(T t) { boolean sort(T t) {
for(Tbin<? extends T> ts : this) for(Tbin<? extends T> ts : this)
if(ts.grab(t)) if(ts.grab(t))
return true; return true;
return false; // bin not found for t return false; // bin not found for t
} }
void sortBin(Tbin<T> bin) { // [*2*] void sortBin(Tbin<T> bin) { // [2]
for(T aBin : bin) for(T aBin : bin)
if(!sort(aBin)) if(!sort(aBin))
System.err.println("Bin not found"); System.err.println("Bin not found");
@ -53,7 +53,7 @@ public class RecycleC {
// add one line here: [*3*] // add one line here: [*3*]
trashBins.add(new Tbin<>(Cardboard.class)); trashBins.add(new Tbin<>(Cardboard.class));
trashBins.sortBin(bin); // [*4*] trashBins.sortBin(bin); // [4]
trashBins.forEach(Trash::sumValue); trashBins.forEach(Trash::sumValue);
Trash.sumValue(bin); Trash.sumValue(bin);

View File

@ -13,9 +13,9 @@ public class SpecialCollector {
.collect(ArrayList::new, .collect(ArrayList::new,
ArrayList::add, ArrayList::add,
ArrayList::addAll); ArrayList::addAll);
for(String s : words) words.stream()
if(s.equals("cheese")) .filter(s -> s.equals("cheese"))
System.out.println(s); .forEach(System.out::println);
} }
} }
/* Output: /* Output:

View File

@ -7,7 +7,8 @@ import java.util.regex.*;
public class Finding { public class Finding {
public static void main(String[] args) { public static void main(String[] args) {
Matcher m = Pattern.compile("\\w+") Matcher m = Pattern.compile("\\w+")
.matcher("Evening is full of the linnet's wings"); .matcher(
"Evening is full of the linnet's wings");
while(m.find()) while(m.find())
System.out.print(m.group() + " "); System.out.print(m.group() + " ");
System.out.println(); System.out.println();

View File

@ -1,4 +1,4 @@
// onjava/Hex.java // strings/Hex.java
// (c)2017 MindView LLC: see Copyright.txt // (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information. // Visit http://OnJava8.com for more book information.

View File

@ -3,11 +3,11 @@
// We make no guarantees that this code is fit for any purpose. // We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information. // Visit http://OnJava8.com for more book information.
import java.util.*; import java.util.*;
import java.util.stream.*;
public class UsingStringBuilder { public class UsingStringBuilder {
public static Random rand = new Random(47); public static String string1() {
@Override Random rand = new Random(47);
public String toString() {
StringBuilder result = new StringBuilder("["); StringBuilder result = new StringBuilder("[");
for(int i = 0; i < 25; i++) { for(int i = 0; i < 25; i++) {
result.append(rand.nextInt(100)); result.append(rand.nextInt(100));
@ -17,12 +17,21 @@ public class UsingStringBuilder {
result.append("]"); result.append("]");
return result.toString(); return result.toString();
} }
public static String string2() {
String result = new Random(47)
.ints(25, 0, 100)
.mapToObj(Integer::toString)
.collect(Collectors.joining(", "));
return "[" + result + "]";
}
public static void main(String[] args) { public static void main(String[] args) {
UsingStringBuilder usb = new UsingStringBuilder(); System.out.println(string1());
System.out.println(usb); System.out.println(string2());
} }
} }
/* Output: /* Output:
[58, 55, 93, 61, 61, 29, 68, 0, 22, 7, 88, 28, 51, 89, 9, [58, 55, 93, 61, 61, 29, 68, 0, 22, 7, 88, 28, 51, 89, 9,
78, 98, 61, 20, 58, 16, 40, 11, 22, 4] 78, 98, 61, 20, 58, 16, 40, 11, 22, 4]
[58, 55, 93, 61, 61, 29, 68, 0, 22, 7, 88, 28, 51, 89, 9,
78, 98, 61, 20, 58, 16, 40, 11, 22, 4]
*/ */

View File

@ -22,7 +22,8 @@ public class ModifyingPrivateFields {
System.out.println(pf); System.out.println(pf);
Field f = pf.getClass().getDeclaredField("i"); Field f = pf.getClass().getDeclaredField("i");
f.setAccessible(true); f.setAccessible(true);
System.out.println("f.getInt(pf): " + f.getInt(pf)); System.out.println(
"f.getInt(pf): " + f.getInt(pf));
f.setInt(pf, 47); f.setInt(pf, 47);
System.out.println(pf); System.out.println(pf);
f = pf.getClass().getDeclaredField("s"); f = pf.getClass().getDeclaredField("s");

View File

@ -9,8 +9,8 @@ import onjava.*;
import typeinfo.pets.*; import typeinfo.pets.*;
public class PetCount3 { public class PetCount3 {
static class Counter static class Counter extends
extends LinkedHashMap<Class<? extends Pet>, Integer> { LinkedHashMap<Class<? extends Pet>, Integer> {
public Counter() { public Counter() {
super(LiteralPetCreator.ALL_TYPES.stream() super(LiteralPetCreator.ALL_TYPES.stream()
.map(lpc -> Pair.make(lpc, 0)) .map(lpc -> Pair.make(lpc, 0))
@ -19,24 +19,19 @@ public class PetCount3 {
} }
public void count(Pet pet) { public void count(Pet pet) {
// Class.isInstance() eliminates instanceofs: // Class.isInstance() eliminates instanceofs:
for(Map.Entry<Class<? extends Pet>, Integer> entrySet().stream()
pair : entrySet()) .filter(pair -> pair.getKey().isInstance(pet))
if(pair.getKey().isInstance(pet)) .forEach(pair ->
put(pair.getKey(), pair.getValue() + 1); put(pair.getKey(), pair.getValue() + 1));
} }
@Override @Override
public String toString() { public String toString() {
StringBuilder result = new StringBuilder("{"); String result = entrySet().stream()
for(Map.Entry<Class<? extends Pet>, Integer> .map(pair -> String.format("%s=%s",
pair : entrySet()) { pair.getKey().getSimpleName(),
result.append(pair.getKey().getSimpleName()); pair.getValue()))
result.append("="); .collect(Collectors.joining(", "));
result.append(pair.getValue()); return "{" + result + "}";
result.append(", ");
}
result.delete(result.length() - 2, result.length());
result.append("}");
return result.toString();
} }
} }
public static void main(String[] args) { public static void main(String[] args) {

View File

@ -25,12 +25,13 @@ class Position {
public Person getPerson() { return person; } public Person getPerson() { return person; }
public void setPerson(Person newPerson) { public void setPerson(Person newPerson) {
// Uses empty Person if newPerson is null: // Uses empty Person if newPerson is null:
person = person = Optional.ofNullable(newPerson)
Optional.ofNullable(newPerson).orElse(new Person()); .orElse(new Person());
} }
@Override @Override
public String toString() { public String toString() {
return "Position: " + title + ", Employee: " + person; return "Position: " + title +
", Employee: " + person;
} }
public static void main(String[] args) { public static void main(String[] args) {
System.out.println(new Position("CEO")); System.out.println(new Position("CEO"));

View File

@ -30,15 +30,21 @@ interface SomeMethods {
class Implementation implements SomeMethods { class Implementation implements SomeMethods {
@Override @Override
public void boring1() { System.out.println("boring1"); } public void boring1() {
System.out.println("boring1");
}
@Override @Override
public void boring2() { System.out.println("boring2"); } public void boring2() {
System.out.println("boring2");
}
@Override @Override
public void interesting(String arg) { public void interesting(String arg) {
System.out.println("interesting " + arg); System.out.println("interesting " + arg);
} }
@Override @Override
public void boring3() { System.out.println("boring3"); } public void boring3() {
System.out.println("boring3");
}
} }
class SelectingMethods { class SelectingMethods {