From 14e318827514e3dfa65b46974404629f154fac02 Mon Sep 17 00:00:00 2001 From: caozhixin Date: Wed, 29 Jun 2022 17:48:59 +0800 Subject: [PATCH 1/3] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/effectivejava/chapter5/item26/Raw.java | 6 +- .../chapter5/item28/Chooser.java | 5 ++ .../chapter5/item28/GenericTest.java | 83 +++++++++++++++++++ .../item30/GenericSingletonFactory.java | 2 +- .../chapter5/item30/RecursiveTypeBound.java | 2 +- .../chapter5/item30/TypeParameterTest.java | 76 +++++++++++++++++ src/effectivejava/chapter5/item30/Union.java | 6 ++ .../chapter5/item33/PrintAnnotation.java | 4 +- .../chapter6/item34/Inverse.java | 4 +- .../chapter6/item34/Operation.java | 4 +- .../chapter6/item34/WeightTable.java | 2 +- src/effectivejava/chapter6/item37/Plant.java | 22 ++--- .../chapter6/item38/ExtendedOperation.java | 4 +- .../annotationwithparameter/RunTests.java | 13 ++- .../item39/markerannotation/RunTests.java | 4 +- 15 files changed, 208 insertions(+), 29 deletions(-) create mode 100644 src/effectivejava/chapter5/item28/GenericTest.java create mode 100644 src/effectivejava/chapter5/item30/TypeParameterTest.java diff --git a/src/effectivejava/chapter5/item26/Raw.java b/src/effectivejava/chapter5/item26/Raw.java index 5cb1d9092..5e733a37c 100644 --- a/src/effectivejava/chapter5/item26/Raw.java +++ b/src/effectivejava/chapter5/item26/Raw.java @@ -4,9 +4,9 @@ // Fails at runtime - unsafeAdd method uses a raw type (List)! (Page 119) public class Raw { public static void main(String[] args) { - List strings = new ArrayList<>(); - unsafeAdd(strings, Integer.valueOf(42)); - String s = strings.get(0); // Has compiler-generated cast +// List strings = new ArrayList<>(); +// unsafeAdd(strings, Integer.valueOf(42)); +// String s = strings.get(0); // Has compiler-generated cast } private static void unsafeAdd(List list, Object o) { diff --git a/src/effectivejava/chapter5/item28/Chooser.java b/src/effectivejava/chapter5/item28/Chooser.java index 259ab2649..e2718c32a 100644 --- a/src/effectivejava/chapter5/item28/Chooser.java +++ b/src/effectivejava/chapter5/item28/Chooser.java @@ -20,6 +20,11 @@ public T choose() { } public static void main(String[] args) { +// Object[] objects = new Long[1]; +// objects[0] = "I don't fit in"; + +// List objects = new ArrayList<>(); + List intList = List.of(1, 2, 3, 4, 5, 6); Chooser chooser = new Chooser<>(intList); diff --git a/src/effectivejava/chapter5/item28/GenericTest.java b/src/effectivejava/chapter5/item28/GenericTest.java new file mode 100644 index 000000000..b9c6c1b9c --- /dev/null +++ b/src/effectivejava/chapter5/item28/GenericTest.java @@ -0,0 +1,83 @@ +package effectivejava.chapter5.item28; + +/** + * @author caozhixin + * @date 2022/6/28 14:54 + */ +public class GenericTest { + public static void main(String[] args) { +// Orchard orchard = new Orchard(); +// Orchard orchard = new Orchard(); +// orchard.get(); + // 无法知道输入的是Apple或者是Banana,若Banana合法,上面Apple定义就会报错 +// orchard.set(new Apple()); +// orchard.set(new Banana()); +// Orchard orchard2 = new Orchard(); +// Shop shopA = new Shop(); + // 下面做法,可以限制Banana的输入 +// Shop shopB = new Shop(); +// shopB.set(new Apple()); +// shopB.set(new RedApple()); +// shopB.get(); +// shopB.set(new Banana()); + // 下面做法,无法限制Banana的输入 +// Shop shopC = new Shop(); +// shopC.set(new Apple()); +// shopC.set(new Banana()); + } + + interface Generator { + public T next(); + } + + class FruitGenerator implements Generator { + @Override + public T next() { + return null; + } + } + + class FruitGenerator2 implements Generator { + @Override + public String next() { + return null; + } + } + + static class Orchard { + T t; + public void set(T t) { + this.t = t; + } + public T get() { + return t; + } + } + + static class Shop { + T t; + public void set(T t) { + this.t = t; + } + public T get() { + return t; + } + } + + static class Fruit { + + } + + static class Apple extends Fruit { + + } + + static class Banana extends Fruit { + + } + + static class RedApple extends Apple { + + } + +} diff --git a/src/effectivejava/chapter5/item30/GenericSingletonFactory.java b/src/effectivejava/chapter5/item30/GenericSingletonFactory.java index 6f27af8bc..529f9a21f 100644 --- a/src/effectivejava/chapter5/item30/GenericSingletonFactory.java +++ b/src/effectivejava/chapter5/item30/GenericSingletonFactory.java @@ -5,7 +5,7 @@ // Generic singleton factory pattern (Page 136-7) public class GenericSingletonFactory { // Generic singleton factory pattern - private static UnaryOperator IDENTITY_FN = (t) -> t; + private static UnaryOperator IDENTITY_FN = (t) -> t + "1"; @SuppressWarnings("unchecked") public static UnaryOperator identityFunction() { diff --git a/src/effectivejava/chapter5/item30/RecursiveTypeBound.java b/src/effectivejava/chapter5/item30/RecursiveTypeBound.java index e3419dfc2..8d83c4981 100644 --- a/src/effectivejava/chapter5/item30/RecursiveTypeBound.java +++ b/src/effectivejava/chapter5/item30/RecursiveTypeBound.java @@ -17,7 +17,7 @@ public static > E max(Collection c) { } public static void main(String[] args) { - List argList = Arrays.asList(args); + List argList = Arrays.asList("1", "2", "3"); System.out.println(max(argList)); } } \ No newline at end of file diff --git a/src/effectivejava/chapter5/item30/TypeParameterTest.java b/src/effectivejava/chapter5/item30/TypeParameterTest.java new file mode 100644 index 000000000..bcb245840 --- /dev/null +++ b/src/effectivejava/chapter5/item30/TypeParameterTest.java @@ -0,0 +1,76 @@ +package effectivejava.chapter5.item30; + +/** + * @author caozhixin + * @date 2022/6/28 17:07 + */ +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class TypeParameterTest { + //第一种声明:简单,灵活性低 + public static > void mySort1(List list) { + Collections.sort(list); + } + + //第二种声明:复杂,灵活性高 + public static > void mySort2(List list) { + Collections.sort(list); + } + +// public static void main(String[] args) { +// //在这个方法中要创建一个 Animal List 和一个 Dog List,然后分别调用两个排序方法。 +// // 创建一个 Animal List +// List animals = new ArrayList<>(); +// animals.add(new Animal(25)); +// animals.add(new Dog(35)); +// +// // 创建一个 Dog List +// List dogs = new ArrayList<>(); +// dogs.add(new Dog(5)); +// dogs.add(new Dog(18)); +// +// // 测试 mySort1() 方法 +// mySort1(animals); +//// mySort1(dogs); +// } + + public static void main(String[] args) { + // 创建一个 Animal List + List animals = new ArrayList<>(); + animals.add(new Animal(25)); + animals.add(new Dog(35)); + + // 创建一个 Dog List + List dogs = new ArrayList<>(); + dogs.add(new Dog(5)); + dogs.add(new Dog(18)); + + // 测试 mySort2() 方法 + mySort2(animals); + mySort2(dogs); + } +} + + +class Animal implements Comparable { + protected int age; + + public Animal(int age) { + this.age = age; + } + + //使用年龄与另一实例比较大小 + @Override + public int compareTo(Animal other) { + return this.age - other.age; + + } +} + +class Dog extends Animal { + public Dog(int age) { + super(age); + } +} \ No newline at end of file diff --git a/src/effectivejava/chapter5/item30/Union.java b/src/effectivejava/chapter5/item30/Union.java index 5ecb202fa..bd5158fcb 100644 --- a/src/effectivejava/chapter5/item30/Union.java +++ b/src/effectivejava/chapter5/item30/Union.java @@ -11,6 +11,12 @@ public static Set union(Set s1, Set s2) { return result; } +// public static Set union(Set s1, Set s2) { +// Set result = new HashSet(s1); +// result.addAll(s2); +// return result; +// } + // Simple program to exercise generic method public static void main(String[] args) { Set guys = Set.of("Tom", "Dick", "Harry"); diff --git a/src/effectivejava/chapter5/item33/PrintAnnotation.java b/src/effectivejava/chapter5/item33/PrintAnnotation.java index bbd3d13cb..436ef7469 100644 --- a/src/effectivejava/chapter5/item33/PrintAnnotation.java +++ b/src/effectivejava/chapter5/item33/PrintAnnotation.java @@ -1,8 +1,10 @@ package effectivejava.chapter5.item33; import java.lang.annotation.*; import java.lang.reflect.*; +import java.util.ArrayList; // Use of asSubclass to safely cast to a bounded type token (Page 155) +@Deprecated(since = "print") public class PrintAnnotation { static Annotation getAnnotation(AnnotatedElement element, String annotationTypeName) { @@ -24,7 +26,7 @@ public static void main(String[] args) throws Exception { System.exit(1); } String className = args[0]; - String annotationTypeName = args[1]; + String annotationTypeName = args[1]; Class klass = Class.forName(className); System.out.println(getAnnotation(klass, annotationTypeName)); } diff --git a/src/effectivejava/chapter6/item34/Inverse.java b/src/effectivejava/chapter6/item34/Inverse.java index cced10807..24ea8b469 100644 --- a/src/effectivejava/chapter6/item34/Inverse.java +++ b/src/effectivejava/chapter6/item34/Inverse.java @@ -14,8 +14,8 @@ public static Operation inverse(Operation op) { } public static void main(String[] args) { - double x = Double.parseDouble(args[0]); - double y = Double.parseDouble(args[1]); + double x = Double.parseDouble("1.1"); + double y = Double.parseDouble("1.2"); for (Operation op : Operation.values()) { Operation invOp = inverse(op); System.out.printf("%f %s %f %s %f = %f%n", diff --git a/src/effectivejava/chapter6/item34/Operation.java b/src/effectivejava/chapter6/item34/Operation.java index ba89c8f95..587013b63 100644 --- a/src/effectivejava/chapter6/item34/Operation.java +++ b/src/effectivejava/chapter6/item34/Operation.java @@ -38,8 +38,8 @@ public static Optional fromString(String symbol) { } public static void main(String[] args) { - double x = Double.parseDouble(args[0]); - double y = Double.parseDouble(args[1]); + double x = Double.parseDouble("2"); + double y = Double.parseDouble("4"); for (Operation op : Operation.values()) System.out.printf("%f %s %f = %f%n", x, op, y, op.apply(x, y)); diff --git a/src/effectivejava/chapter6/item34/WeightTable.java b/src/effectivejava/chapter6/item34/WeightTable.java index 948c2e37a..ffbd21330 100644 --- a/src/effectivejava/chapter6/item34/WeightTable.java +++ b/src/effectivejava/chapter6/item34/WeightTable.java @@ -3,7 +3,7 @@ // Takes earth-weight and prints table of weights on all planets (Page 160) public class WeightTable { public static void main(String[] args) { - double earthWeight = Double.parseDouble(args[0]); + double earthWeight = Double.parseDouble("185"); double mass = earthWeight / Planet.EARTH.surfaceGravity(); for (Planet p : Planet.values()) System.out.printf("Weight on %s is %f%n", diff --git a/src/effectivejava/chapter6/item37/Plant.java b/src/effectivejava/chapter6/item37/Plant.java index 8e8fc1cf1..1e6bd4173 100644 --- a/src/effectivejava/chapter6/item37/Plant.java +++ b/src/effectivejava/chapter6/item37/Plant.java @@ -32,17 +32,17 @@ public static void main(String[] args) { }; // Using ordinal() to index into an array - DON'T DO THIS! (Page 171) - Set[] plantsByLifeCycleArr = - (Set[]) new Set[Plant.LifeCycle.values().length]; - for (int i = 0; i < plantsByLifeCycleArr.length; i++) - plantsByLifeCycleArr[i] = new HashSet<>(); - for (Plant p : garden) - plantsByLifeCycleArr[p.lifeCycle.ordinal()].add(p); - // Print the results - for (int i = 0; i < plantsByLifeCycleArr.length; i++) { - System.out.printf("%s: %s%n", - Plant.LifeCycle.values()[i], plantsByLifeCycleArr[i]); - } +// Set[] plantsByLifeCycleArr = +// (Set[]) new Set[Plant.LifeCycle.values().length]; +// for (int i = 0; i < plantsByLifeCycleArr.length; i++) +// plantsByLifeCycleArr[i] = new HashSet<>(); +// for (Plant p : garden) +// plantsByLifeCycleArr[p.lifeCycle.ordinal()].add(p); +// // Print the results +// for (int i = 0; i < plantsByLifeCycleArr.length; i++) { +// System.out.printf("%s: %s%n", +// Plant.LifeCycle.values()[i], plantsByLifeCycleArr[i]); +// } // Using an EnumMap to associate data with an enum (Page 172) Map> plantsByLifeCycle = diff --git a/src/effectivejava/chapter6/item38/ExtendedOperation.java b/src/effectivejava/chapter6/item38/ExtendedOperation.java index 86a019fb7..b03d020b9 100644 --- a/src/effectivejava/chapter6/item38/ExtendedOperation.java +++ b/src/effectivejava/chapter6/item38/ExtendedOperation.java @@ -36,8 +36,8 @@ public double apply(double x, double y) { // Using a collection instance to represent a collection of extended enums (page 178) public static void main(String[] args) { - double x = Double.parseDouble(args[0]); - double y = Double.parseDouble(args[1]); + double x = Double.parseDouble("4"); + double y = Double.parseDouble("2"); test(Arrays.asList(ExtendedOperation.values()), x, y); } private static void test(Collection opSet, diff --git a/src/effectivejava/chapter6/item39/annotationwithparameter/RunTests.java b/src/effectivejava/chapter6/item39/annotationwithparameter/RunTests.java index 867f7dcf0..de1a31c0f 100644 --- a/src/effectivejava/chapter6/item39/annotationwithparameter/RunTests.java +++ b/src/effectivejava/chapter6/item39/annotationwithparameter/RunTests.java @@ -1,6 +1,8 @@ package effectivejava.chapter6.item39.annotationwithparameter; import effectivejava.chapter6.item39.markerannotation.Test; + +import java.awt.event.TextEvent; import java.lang.reflect.*; // Program to process marker annotations and annotations with a parameter (Page 184) @@ -8,15 +10,20 @@ public class RunTests { public static void main(String[] args) throws Exception { int tests = 0; int passed = 0; - Class testClass = Class.forName(args[0]); + Class testClass = Class.forName("effectivejava.chapter6.item39.annotationwithparameter.Sample2"); for (Method m : testClass.getDeclaredMethods()) { - if (m.isAnnotationPresent(Test.class)) { + if (m.isAnnotationPresent(ExceptionTest.class)) { tests++; try { m.invoke(null); - passed++; + System.out.printf("Test %s failed: no exception%n", m); } catch (InvocationTargetException wrappedExc) { Throwable exc = wrappedExc.getCause(); + Class excType = + m.getAnnotation(ExceptionTest.class).value(); + if (excType.isInstance(exc)) { + + } System.out.println(m + " failed: " + exc); } catch (Exception exc) { System.out.println("Invalid @Test: " + m); diff --git a/src/effectivejava/chapter6/item39/markerannotation/RunTests.java b/src/effectivejava/chapter6/item39/markerannotation/RunTests.java index 7dd09961a..6e4d93762 100644 --- a/src/effectivejava/chapter6/item39/markerannotation/RunTests.java +++ b/src/effectivejava/chapter6/item39/markerannotation/RunTests.java @@ -8,7 +8,7 @@ public class RunTests { public static void main(String[] args) throws Exception { int tests = 0; int passed = 0; - Class testClass = Class.forName(args[0]); + Class testClass = Class.forName("effectivejava.chapter6.item39.markerannotation.Sample"); for (Method m : testClass.getDeclaredMethods()) { if (m.isAnnotationPresent(Test.class)) { tests++; @@ -19,7 +19,7 @@ public static void main(String[] args) throws Exception { Throwable exc = wrappedExc.getCause(); System.out.println(m + " failed: " + exc); } catch (Exception exc) { - System.out.println("Invalid @Test: " + m); + System.out.println("Invalid @Test: " + m + "-" + exc); } } } From 1db2da4a31737de75ff6452525ffdc93ea81dc2b Mon Sep 17 00:00:00 2001 From: caozhixin Date: Wed, 29 Jun 2022 19:15:21 +0800 Subject: [PATCH 2/3] fix --- .../item39/annotationwithparameter/RunTests.java | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/src/effectivejava/chapter6/item39/annotationwithparameter/RunTests.java b/src/effectivejava/chapter6/item39/annotationwithparameter/RunTests.java index de1a31c0f..7ff1ed155 100644 --- a/src/effectivejava/chapter6/item39/annotationwithparameter/RunTests.java +++ b/src/effectivejava/chapter6/item39/annotationwithparameter/RunTests.java @@ -1,8 +1,6 @@ package effectivejava.chapter6.item39.annotationwithparameter; import effectivejava.chapter6.item39.markerannotation.Test; - -import java.awt.event.TextEvent; import java.lang.reflect.*; // Program to process marker annotations and annotations with a parameter (Page 184) @@ -12,18 +10,13 @@ public static void main(String[] args) throws Exception { int passed = 0; Class testClass = Class.forName("effectivejava.chapter6.item39.annotationwithparameter.Sample2"); for (Method m : testClass.getDeclaredMethods()) { - if (m.isAnnotationPresent(ExceptionTest.class)) { + if (m.isAnnotationPresent(Test.class)) { tests++; try { m.invoke(null); - System.out.printf("Test %s failed: no exception%n", m); + passed++; } catch (InvocationTargetException wrappedExc) { Throwable exc = wrappedExc.getCause(); - Class excType = - m.getAnnotation(ExceptionTest.class).value(); - if (excType.isInstance(exc)) { - - } System.out.println(m + " failed: " + exc); } catch (Exception exc) { System.out.println("Invalid @Test: " + m); From c0f6cb77b4326de8d25520c0f4d4b4ed6396e09c Mon Sep 17 00:00:00 2001 From: caozhixin Date: Wed, 29 Jun 2022 20:46:37 +0800 Subject: [PATCH 3/3] fix --- .../item39/annotationwitharrayparameter/RunTests.java | 5 +++-- .../chapter6/item39/repeatableannotation/RunTests.java | 2 +- src/effectivejava/chapter7/item42/Operation.java | 4 ++-- src/effectivejava/chapter7/item42/SortFourWays.java | 2 +- src/effectivejava/chapter7/item43/Freq.java | 9 ++++++--- 5 files changed, 13 insertions(+), 9 deletions(-) diff --git a/src/effectivejava/chapter6/item39/annotationwitharrayparameter/RunTests.java b/src/effectivejava/chapter6/item39/annotationwitharrayparameter/RunTests.java index 91855d8cc..5ea7c89ba 100644 --- a/src/effectivejava/chapter6/item39/annotationwitharrayparameter/RunTests.java +++ b/src/effectivejava/chapter6/item39/annotationwitharrayparameter/RunTests.java @@ -8,7 +8,7 @@ public class RunTests { public static void main(String[] args) throws Exception { int tests = 0; int passed = 0; - Class testClass = Class.forName(args[0]); + Class testClass = Class.forName("effectivejava.chapter6.item39.annotationwitharrayparameter.Sample3"); for (Method m : testClass.getDeclaredMethods()) { if (m.isAnnotationPresent(Test.class)) { tests++; @@ -40,7 +40,8 @@ public static void main(String[] args) throws Exception { break; } } - if (passed == oldPassed) + // oldPassed = 0 + if (passed != oldPassed) System.out.printf("Test %s failed: %s %n", m, exc); } } diff --git a/src/effectivejava/chapter6/item39/repeatableannotation/RunTests.java b/src/effectivejava/chapter6/item39/repeatableannotation/RunTests.java index e2ef183e7..ce09e33e2 100644 --- a/src/effectivejava/chapter6/item39/repeatableannotation/RunTests.java +++ b/src/effectivejava/chapter6/item39/repeatableannotation/RunTests.java @@ -43,7 +43,7 @@ public static void main(String[] args) throws Exception { break; } } - if (passed == oldPassed) + if (passed != oldPassed) System.out.printf("Test %s failed: %s %n", m, exc); } } diff --git a/src/effectivejava/chapter7/item42/Operation.java b/src/effectivejava/chapter7/item42/Operation.java index 2a568812c..5daa65a6b 100644 --- a/src/effectivejava/chapter7/item42/Operation.java +++ b/src/effectivejava/chapter7/item42/Operation.java @@ -25,8 +25,8 @@ public double apply(double x, double y) { // Main method from Item 34 (Page 163) public static void main(String[] args) { - double x = Double.parseDouble(args[0]); - double y = Double.parseDouble(args[1]); + double x = Double.parseDouble("12"); + double y = Double.parseDouble("6"); for (Operation op : Operation.values()) System.out.printf("%f %s %f = %f%n", x, op, y, op.apply(x, y)); diff --git a/src/effectivejava/chapter7/item42/SortFourWays.java b/src/effectivejava/chapter7/item42/SortFourWays.java index 84b773719..422d8d580 100644 --- a/src/effectivejava/chapter7/item42/SortFourWays.java +++ b/src/effectivejava/chapter7/item42/SortFourWays.java @@ -11,7 +11,7 @@ // Sorting with function objects (Pages 193-4) public class SortFourWays { public static void main(String[] args) { - List words = Arrays.asList(args); + List words = Arrays.asList("bbc", "aadd", "ccddede"); // Anonymous class instance as a function object - obsolete! (Page 193) Collections.sort(words, new Comparator() { diff --git a/src/effectivejava/chapter7/item43/Freq.java b/src/effectivejava/chapter7/item43/Freq.java index fb949ad94..30eff6dfe 100644 --- a/src/effectivejava/chapter7/item43/Freq.java +++ b/src/effectivejava/chapter7/item43/Freq.java @@ -1,5 +1,6 @@ package effectivejava.chapter7.item43; +import java.util.List; import java.util.Map; import java.util.TreeMap; @@ -7,13 +8,15 @@ public class Freq { public static void main(String[] args) { Map frequencyTable = new TreeMap<>(); - - for (String s : args) + + List arg = List.of("1", "2", "3", "2", "3", "3"); + + for (String s : arg) frequencyTable.merge(s, 1, (count, incr) -> count + incr); // Lambda System.out.println(frequencyTable); frequencyTable.clear(); - for (String s : args) + for (String s : arg) frequencyTable.merge(s, 1, Integer::sum); // Method reference System.out.println(frequencyTable);