Skip to content

Commit 2a2a201

Browse files
author
jim.deng
committed
2020年12月23日17:33:13
1 parent 45b8c81 commit 2a2a201

26 files changed

Lines changed: 404 additions & 123 deletions

collectiontopics/Suppliers.java

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
// onjava/Suppliers.java
2+
// (c)2020 MindView LLC: see Copyright.txt
3+
// We make no guarantees that this code is fit for any purpose.
4+
// Visit http://OnJava8.com for more book information.
5+
// A utility to use with Suppliers
6+
//package onjava;
7+
8+
import java.util.Collection;
9+
import java.util.function.BiConsumer;
10+
import java.util.function.Supplier;
11+
import java.util.stream.Stream;
12+
13+
public class Suppliers {
14+
// Create a collection and fill it:
15+
public static <T, C extends Collection<T>> C
16+
create(Supplier<C> factory, Supplier<T> gen, int n) {
17+
return Stream.generate(gen)
18+
.limit(n)
19+
.collect(factory, C::add, C::addAll);
20+
}
21+
// Fill an existing collection:
22+
public static <T, C extends Collection<T>>
23+
C fill(C coll, Supplier<T> gen, int n) {
24+
Stream.generate(gen)
25+
.limit(n)
26+
.forEach(coll::add);
27+
return coll;
28+
}
29+
// Use an unbound method reference to
30+
// produce a more general method:
31+
public static <H, A> H fill(H holder,
32+
BiConsumer<H, A> adder, Supplier<A> gen, int n) {
33+
Stream.generate(gen)
34+
.limit(n)
35+
.forEach(a -> adder.accept(holder, a));
36+
return holder;
37+
}
38+
}

generics/ArrayOfGeneric.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,11 @@ public static void main(String[] args) {
1111
try {
1212
gia = (Generic<Integer>[])new Object[SIZE];
1313
} catch(ClassCastException e) {
14-
System.err.println(e.getMessage());
14+
System.err.println("异常1:"+e.getMessage());
1515
}
1616
// Runtime type is the raw (erased) type:
1717
gia = (Generic<Integer>[])new Generic[SIZE];
18-
System.err.println(gia.getClass().getSimpleName());
18+
System.err.println("222: "+gia.getClass().getSimpleName());
1919
gia[0] = new Generic<>();
2020
//- gia[1] = new Object(); // Compile-time error
2121
// Discovers type mismatch at compile time:

generics/BasicBounds.java

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@ class Coord { public int x, y, z; }
1717

1818
// This fails. Class must be first, then interfaces:
1919
// class WithColorCoord<T extends HasColor & Coord> {
20+
//
21+
// }
2022

2123
// Multiple bounds:
2224
class WithColorCoord<T extends Coord & HasColor> {
@@ -44,8 +46,11 @@ class Solid<T extends Coord & HasColor & Weight> {
4446
int weight() { return item.weight(); }
4547
}
4648

47-
class Bounded
48-
extends Coord implements HasColor, Weight {
49+
class Bounded extends Coord implements HasColor, Weight {
50+
public Bounded() {
51+
System.err.println("Bounded 构造器");
52+
}
53+
4954
@Override
5055
public java.awt.Color getColor() { return null; }
5156
@Override

generics/CovariantArrays.java

Lines changed: 29 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -3,26 +3,37 @@
33
// We make no guarantees that this code is fit for any purpose.
44
// Visit http://OnJava8.com for more book information.
55

6-
class Fruit {}
7-
class Apple extends Fruit {}
8-
class Jonathan extends Apple {}
9-
class Orange extends Fruit {}
6+
class Fruit {
7+
}
8+
9+
class Apple extends Fruit {
10+
}
11+
12+
class Jonathan extends Apple {
13+
}
14+
15+
class Orange extends Fruit {
16+
}
1017

1118
public class CovariantArrays {
12-
public static void main(String[] args) {
13-
Fruit[] fruit = new Apple[10];
14-
fruit[0] = new Apple(); // OK
15-
fruit[1] = new Jonathan(); // OK
16-
// Runtime type is Apple[], not Fruit[] or Orange[]:
17-
try {
18-
// Compiler allows you to add Fruit:
19-
fruit[0] = new Fruit(); // ArrayStoreException
20-
} catch(Exception e) { System.err.println(e); }
21-
try {
22-
// Compiler allows you to add Oranges:
23-
fruit[0] = new Orange(); // ArrayStoreException
24-
} catch(Exception e) { System.err.println(e); }
25-
}
19+
public static void main(String[] args) {
20+
Fruit[] fruit = new Apple[10];
21+
fruit[0] = new Apple(); // OK
22+
fruit[1] = new Jonathan(); // OK
23+
// Runtime type is Apple[], not Fruit[] or Orange[]:
24+
try {
25+
// Compiler allows you to add Fruit:
26+
fruit[0] = new Fruit(); // ArrayStoreException
27+
} catch (Exception e) {
28+
System.err.println(e);
29+
}
30+
try {
31+
// Compiler allows you to add Oranges:
32+
fruit[0] = new Orange(); // ArrayStoreException
33+
} catch (Exception e) {
34+
System.err.println(e);
35+
}
36+
}
2637
}
2738
/* Output:
2839
java.lang.ArrayStoreException: Fruit

generics/DynamicProxyMixin.java

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,9 @@
44
// Visit http://OnJava8.com for more book information.
55
import java.lang.reflect.*;
66
import java.util.*;
7-
import onjava.*;
8-
import static onjava.Tuple.*;
9-
7+
//import onjava.*;
8+
//import static onjava.Tuple.*;
9+
//import static Tuple.tuple.*;
1010
class MixinProxy implements InvocationHandler {
1111
Map<String, Object> delegatesByMethod;
1212
@SuppressWarnings("unchecked")
@@ -46,9 +46,9 @@ public class DynamicProxyMixin {
4646
public static void main(String[] args) {
4747
@SuppressWarnings("unchecked")
4848
Object mixin = MixinProxy.newInstance(
49-
tuple(new BasicImp(), Basic.class),
50-
tuple(new TimeStampedImp(), TimeStamped.class),
51-
tuple(new SerialNumberedImp(),
49+
Tuple.tuple(new BasicImp(), Basic.class),
50+
Tuple.tuple(new TimeStampedImp(), TimeStamped.class),
51+
Tuple.tuple(new SerialNumberedImp(),
5252
SerialNumbered.class));
5353
Basic b = (Basic)mixin;
5454
TimeStamped t = (TimeStamped)mixin;

generics/EpicBattle.java

Lines changed: 67 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -3,72 +3,97 @@
33
// We make no guarantees that this code is fit for any purpose.
44
// Visit http://OnJava8.com for more book information.
55
// Bounds in Java generics
6+
67
import java.util.*;
78

8-
interface SuperPower {}
9+
interface SuperPower {
10+
}
911

1012
interface XRayVision extends SuperPower {
11-
void seeThroughWalls();
13+
void seeThroughWalls();
1214
}
1315

1416
interface SuperHearing extends SuperPower {
15-
void hearSubtleNoises();
17+
void hearSubtleNoises();
1618
}
1719

1820
interface SuperSmell extends SuperPower {
19-
void trackBySmell();
21+
void trackBySmell();
2022
}
2123

2224
class SuperHero<POWER extends SuperPower> {
23-
POWER power;
24-
SuperHero(POWER power) { this.power = power; }
25-
POWER getPower() { return power; }
25+
POWER power;
26+
27+
SuperHero(POWER power) {
28+
this.power = power;
29+
}
30+
31+
POWER getPower() {
32+
return power;
33+
}
2634
}
2735

28-
class SuperSleuth<POWER extends XRayVision>
29-
extends SuperHero<POWER> {
30-
SuperSleuth(POWER power) { super(power); }
31-
void see() { power.seeThroughWalls(); }
36+
class SuperSleuth<POWER extends XRayVision> extends SuperHero<POWER> {
37+
SuperSleuth(POWER power) {
38+
super(power);
39+
}
40+
41+
void see() {
42+
power.seeThroughWalls();
43+
}
3244
}
3345

3446
class
35-
CanineHero<POWER extends SuperHearing & SuperSmell>
36-
extends SuperHero<POWER> {
37-
CanineHero(POWER power) { super(power); }
38-
void hear() { power.hearSubtleNoises(); }
39-
void smell() { power.trackBySmell(); }
47+
CanineHero<POWER extends SuperHearing & SuperSmell> extends SuperHero<POWER> {
48+
CanineHero(POWER power) {
49+
super(power);
50+
}
51+
52+
void hear() {
53+
power.hearSubtleNoises();
54+
}
55+
56+
void smell() {
57+
power.trackBySmell();
58+
}
4059
}
4160

42-
class SuperHearSmell
43-
implements SuperHearing, SuperSmell {
44-
@Override
45-
public void hearSubtleNoises() {}
46-
@Override
47-
public void trackBySmell() {}
61+
class SuperHearSmell implements SuperHearing, SuperSmell {
62+
@Override
63+
public void hearSubtleNoises() {
64+
}
65+
66+
@Override
67+
public void trackBySmell() {
68+
}
4869
}
4970

5071
class DogPerson extends CanineHero<SuperHearSmell> {
51-
DogPerson() { super(new SuperHearSmell()); }
72+
DogPerson() {
73+
super(new SuperHearSmell());
74+
}
5275
}
5376

5477
public class EpicBattle {
55-
// Bounds in generic methods:
56-
static <POWER extends SuperHearing>
57-
void useSuperHearing(SuperHero<POWER> hero) {
58-
hero.getPower().hearSubtleNoises();
59-
}
60-
static <POWER extends SuperHearing & SuperSmell>
61-
void superFind(SuperHero<POWER> hero) {
62-
hero.getPower().hearSubtleNoises();
63-
hero.getPower().trackBySmell();
64-
}
65-
public static void main(String[] args) {
66-
DogPerson dogPerson = new DogPerson();
67-
useSuperHearing(dogPerson);
68-
superFind(dogPerson);
69-
// You can do this:
70-
List<? extends SuperHearing> audioPeople;
71-
// But you can't do this:
72-
// List<? extends SuperHearing & SuperSmell> dogPs;
73-
}
78+
// Bounds in generic methods:
79+
static <POWER extends SuperHearing>
80+
void useSuperHearing(SuperHero<POWER> hero) {
81+
hero.getPower().hearSubtleNoises();
82+
}
83+
84+
static <POWER extends SuperHearing & SuperSmell>
85+
void superFind(SuperHero<POWER> hero) {
86+
hero.getPower().hearSubtleNoises();
87+
hero.getPower().trackBySmell();
88+
}
89+
90+
public static void main(String[] args) {
91+
DogPerson dogPerson = new DogPerson();
92+
useSuperHearing(dogPerson);
93+
superFind(dogPerson);
94+
// You can do this:
95+
List<? extends SuperHearing> audioPeople;
96+
// But you can't do this:
97+
// List<? extends SuperHearing & SuperSmell> dogPs;
98+
}
7499
}

generics/ErasureAndInheritance.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ class Derived2 extends GenericBase {} // No warning
1919
// required: class or interface without bounds
2020

2121
public class ErasureAndInheritance {
22-
// @SuppressWarnings("unchecked")
22+
@SuppressWarnings("unchecked")
2323
public static void main(String[] args) {
2424
Derived2 d2 = new Derived2();
2525
Object obj = d2.get();

generics/FactoryConstraint.java

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,7 @@ class Widget {
2121
public String toString() {
2222
return "Widget " + id;
2323
}
24-
public static
25-
class Factory implements Supplier<Widget> {
24+
public static class Factory implements Supplier<Widget> {
2625
private int i = 0;
2726
@Override
2827
public Widget get() { return new Widget(++i); }
@@ -32,6 +31,14 @@ class Factory implements Supplier<Widget> {
3231
class Fudge {
3332
private static int count = 1;
3433
private int n = count++;
34+
public Fudge() {
35+
System.err.println("构造器启用");
36+
}
37+
38+
public Fudge(int n) {
39+
this.n = n;
40+
}
41+
3542
@Override
3643
public String toString() { return "Fudge " + n; }
3744
}

generics/GenericArray.java

Lines changed: 30 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -4,29 +4,37 @@
44
// Visit http://OnJava8.com for more book information.
55

66
public class GenericArray<T> {
7-
private T[] array;
8-
@SuppressWarnings("unchecked")
9-
public GenericArray(int sz) {
10-
array = (T[])new Object[sz];
11-
}
12-
public void put(int index, T item) {
13-
array[index] = item;
14-
}
15-
public T get(int index) { return array[index]; }
16-
// Method that exposes the underlying representation:
17-
public T[] rep() { return array; }
18-
public static void main(String[] args) {
19-
GenericArray<Integer> gai = new GenericArray<>(10);
20-
try {
21-
Integer[] ia = gai.rep();
22-
} catch(ClassCastException e) {
23-
System.err.println(e.getMessage());
7+
private T[] array;
8+
9+
// @SuppressWarnings("unchecked")
10+
public GenericArray(int sz) {
11+
array = (T[]) new Object[sz];
12+
}
13+
14+
public void put(int index, T item) {
15+
array[index] = item;
16+
}
17+
18+
public T get(int index) {
19+
return array[index];
20+
}
21+
22+
// Method that exposes the underlying representation:
23+
public T[] rep() {
24+
return array;
25+
}
26+
27+
public static void main(String[] args) {
28+
GenericArray<Integer> gai = new GenericArray<>(10);
29+
try {
30+
Integer[] ia = gai.rep();
31+
} catch (ClassCastException e) {
32+
System.err.println(e.getMessage());
33+
}
34+
// This is OK:
35+
Object[] oa = gai.rep();
2436
}
25-
// This is OK:
26-
Object[] oa = gai.rep();
27-
}
2837
}
2938
/* Output:
30-
[Ljava.lang.Object; cannot be cast to
31-
[Ljava.lang.Integer;
39+
[Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer;
3240
*/

0 commit comments

Comments
 (0)