From 82d3446d8f10677529091726f5408fa5947da3d1 Mon Sep 17 00:00:00 2001 From: wangyongtao Date: Fri, 1 Feb 2019 13:57:46 +0800 Subject: [PATCH] fommat. --- .../item2/builder/NutritionFacts.java | 99 ++++++++++--------- .../item2/hierarchicalbuilder/Calzone.java | 43 ++++---- .../item2/hierarchicalbuilder/NyPizza.java | 44 +++++---- .../item2/hierarchicalbuilder/Pizza.java | 42 ++++---- .../item2/hierarchicalbuilder/PizzaTest.java | 18 ++-- .../item2/javabeans/NutritionFacts.java | 69 ++++++++----- .../NutritionFacts.java | 68 ++++++------- .../chapter2/item3/enumtype/Elvis.java | 18 ++-- .../chapter2/item3/field/Elvis.java | 22 ++--- .../chapter2/item3/staticfactory/Elvis.java | 26 ++--- .../chapter2/item4/UtilityClass.java | 10 +- .../chapter2/item6/RomanNumerals.java | 55 +++++------ src/effectivejava/chapter2/item6/Sum.java | 38 ++++--- .../chapter2/item7/EmptyStackException.java | 3 +- src/effectivejava/chapter2/item7/Stack.java | 87 ++++++++-------- src/effectivejava/chapter2/item8/Adult.java | 8 +- src/effectivejava/chapter2/item8/Room.java | 48 ++++----- .../chapter2/item8/Teenager.java | 12 +-- .../chapter2/item9/tryfinally/Copy.java | 43 ++++---- .../chapter2/item9/tryfinally/TopLine.java | 24 ++--- .../chapter2/item9/trywithresources/Copy.java | 29 +++--- .../item9/trywithresources/TopLine.java | 20 ++-- .../trywithresources/TopLineWithDefault.java | 24 +++-- 23 files changed, 443 insertions(+), 407 deletions(-) diff --git a/src/effectivejava/chapter2/item2/builder/NutritionFacts.java b/src/effectivejava/chapter2/item2/builder/NutritionFacts.java index 0c630099..340ef14f 100644 --- a/src/effectivejava/chapter2/item2/builder/NutritionFacts.java +++ b/src/effectivejava/chapter2/item2/builder/NutritionFacts.java @@ -2,54 +2,65 @@ // Builder Pattern (Page 13) public class NutritionFacts { + private final int servingSize; + private final int servings; + private final int calories; + private final int fat; + private final int sodium; + private final int carbohydrate; + + public static class Builder { + // Required parameters private final int servingSize; private final int servings; - private final int calories; - private final int fat; - private final int sodium; - private final int carbohydrate; - - public static class Builder { - // Required parameters - private final int servingSize; - private final int servings; - - // Optional parameters - initialized to default values - private int calories = 0; - private int fat = 0; - private int sodium = 0; - private int carbohydrate = 0; - - public Builder(int servingSize, int servings) { - this.servingSize = servingSize; - this.servings = servings; - } - - public Builder calories(int val) - { calories = val; return this; } - public Builder fat(int val) - { fat = val; return this; } - public Builder sodium(int val) - { sodium = val; return this; } - public Builder carbohydrate(int val) - { carbohydrate = val; return this; } - - public NutritionFacts build() { - return new NutritionFacts(this); - } + + // Optional parameters - initialized to default values + private int calories = 0; + private int fat = 0; + private int sodium = 0; + private int carbohydrate = 0; + + public Builder(int servingSize, int servings) { + this.servingSize = servingSize; + this.servings = servings; } - private NutritionFacts(Builder builder) { - servingSize = builder.servingSize; - servings = builder.servings; - calories = builder.calories; - fat = builder.fat; - sodium = builder.sodium; - carbohydrate = builder.carbohydrate; + public Builder calories(int val) { + calories = val; + return this; } - public static void main(String[] args) { - NutritionFacts cocaCola = new NutritionFacts.Builder(240, 8) - .calories(100).sodium(35).carbohydrate(27).build(); + public Builder fat(int val) { + fat = val; + return this; } -} \ No newline at end of file + + public Builder sodium(int val) { + sodium = val; + return this; + } + + public Builder carbohydrate(int val) { + carbohydrate = val; + return this; + } + + public NutritionFacts build() { + return new NutritionFacts(this); + } + } + + private NutritionFacts(Builder builder) { + servingSize = builder.servingSize; + servings = builder.servings; + calories = builder.calories; + fat = builder.fat; + sodium = builder.sodium; + carbohydrate = builder.carbohydrate; + } + + public static void main(String[] args) { + NutritionFacts cocaCola = + new NutritionFacts.Builder(240, 8).calories(100).sodium(35).carbohydrate(27).build(); + } +} diff --git a/src/effectivejava/chapter2/item2/hierarchicalbuilder/Calzone.java b/src/effectivejava/chapter2/item2/hierarchicalbuilder/Calzone.java index b26ab600..807e2672 100644 --- a/src/effectivejava/chapter2/item2/hierarchicalbuilder/Calzone.java +++ b/src/effectivejava/chapter2/item2/hierarchicalbuilder/Calzone.java @@ -2,30 +2,35 @@ // Subclass with hierarchical builder (Page 15) public class Calzone extends Pizza { - private final boolean sauceInside; + private final boolean sauceInside; - public static class Builder extends Pizza.Builder { - private boolean sauceInside = false; // Default + public static class Builder extends Pizza.Builder { + private boolean sauceInside = false; // Default - public Builder sauceInside() { - sauceInside = true; - return this; - } - - @Override public Calzone build() { - return new Calzone(this); - } - - @Override protected Builder self() { return this; } + public Builder sauceInside() { + sauceInside = true; + return this; } - private Calzone(Builder builder) { - super(builder); - sauceInside = builder.sauceInside; + @Override + public Calzone build() { + return new Calzone(this); } - @Override public String toString() { - return String.format("Calzone with %s and sauce on the %s", - toppings, sauceInside ? "inside" : "outside"); + @Override + protected Builder self() { + return this; } + } + + private Calzone(Builder builder) { + super(builder); + sauceInside = builder.sauceInside; + } + + @Override + public String toString() { + return String.format( + "Calzone with %s and sauce on the %s", toppings, sauceInside ? "inside" : "outside"); + } } diff --git a/src/effectivejava/chapter2/item2/hierarchicalbuilder/NyPizza.java b/src/effectivejava/chapter2/item2/hierarchicalbuilder/NyPizza.java index 3e8c04f8..4435546d 100644 --- a/src/effectivejava/chapter2/item2/hierarchicalbuilder/NyPizza.java +++ b/src/effectivejava/chapter2/item2/hierarchicalbuilder/NyPizza.java @@ -4,29 +4,39 @@ // Subclass with hierarchical builder (Page 15) public class NyPizza extends Pizza { - public enum Size { SMALL, MEDIUM, LARGE } - private final Size size; - - public static class Builder extends Pizza.Builder { - private final Size size; + public enum Size { + SMALL, + MEDIUM, + LARGE + } - public Builder(Size size) { - this.size = Objects.requireNonNull(size); - } + private final Size size; - @Override public NyPizza build() { - return new NyPizza(this); - } + public static class Builder extends Pizza.Builder { + private final Size size; - @Override protected Builder self() { return this; } + public Builder(Size size) { + this.size = Objects.requireNonNull(size); } - private NyPizza(Builder builder) { - super(builder); - size = builder.size; + @Override + public NyPizza build() { + return new NyPizza(this); } - @Override public String toString() { - return "New York Pizza with " + toppings; + @Override + protected Builder self() { + return this; } + } + + private NyPizza(Builder builder) { + super(builder); + size = builder.size; + } + + @Override + public String toString() { + return "New York Pizza with " + toppings; + } } diff --git a/src/effectivejava/chapter2/item2/hierarchicalbuilder/Pizza.java b/src/effectivejava/chapter2/item2/hierarchicalbuilder/Pizza.java index 77925cda..1df867e0 100644 --- a/src/effectivejava/chapter2/item2/hierarchicalbuilder/Pizza.java +++ b/src/effectivejava/chapter2/item2/hierarchicalbuilder/Pizza.java @@ -1,28 +1,36 @@ package effectivejava.chapter2.item2.hierarchicalbuilder; -import java.util.*; // Builder pattern for class hierarchies (Page 14) -// Note that the underlying "simulated self-type" idiom allows for arbitrary fluid hierarchies, not just builders +// Note that the underlying "simulated self-type" idiom allows for arbitrary fluid hierarchies, not +// just builders public abstract class Pizza { - public enum Topping { HAM, MUSHROOM, ONION, PEPPER, SAUSAGE } - final Set toppings; + public enum Topping { + HAM, + MUSHROOM, + ONION, + PEPPER, + SAUSAGE + } - abstract static class Builder> { - EnumSet toppings = EnumSet.noneOf(Topping.class); - public T addTopping(Topping topping) { - toppings.add(Objects.requireNonNull(topping)); - return self(); - } + final Set toppings; - abstract Pizza build(); + abstract static class Builder> { + EnumSet toppings = EnumSet.noneOf(Topping.class); - // Subclasses must override this method to return "this" - protected abstract T self(); - } - - Pizza(Builder builder) { - toppings = builder.toppings.clone(); // See Item 50 + public T addTopping(Topping topping) { + toppings.add(Objects.requireNonNull(topping)); + return self(); } + + abstract Pizza build(); + + // Subclasses must override this method to return "this" + protected abstract T self(); + } + + Pizza(Builder builder) { + toppings = builder.toppings.clone(); // See Item 50 + } } diff --git a/src/effectivejava/chapter2/item2/hierarchicalbuilder/PizzaTest.java b/src/effectivejava/chapter2/item2/hierarchicalbuilder/PizzaTest.java index 191fd094..914d024d 100644 --- a/src/effectivejava/chapter2/item2/hierarchicalbuilder/PizzaTest.java +++ b/src/effectivejava/chapter2/item2/hierarchicalbuilder/PizzaTest.java @@ -1,17 +1,15 @@ package effectivejava.chapter2.item2.hierarchicalbuilder; -import static effectivejava.chapter2.item2.hierarchicalbuilder.Pizza.Topping.*; import static effectivejava.chapter2.item2.hierarchicalbuilder.NyPizza.Size.*; +import static effectivejava.chapter2.item2.hierarchicalbuilder.Pizza.Topping.*; // Using the hierarchical builder (Page 16) public class PizzaTest { - public static void main(String[] args) { - NyPizza pizza = new NyPizza.Builder(SMALL) - .addTopping(SAUSAGE).addTopping(ONION).build(); - Calzone calzone = new Calzone.Builder() - .addTopping(HAM).sauceInside().build(); - - System.out.println(pizza); - System.out.println(calzone); - } + public static void main(String[] args) { + NyPizza pizza = new NyPizza.Builder(SMALL).addTopping(SAUSAGE).addTopping(ONION).build(); + Calzone calzone = new Calzone.Builder().addTopping(HAM).sauceInside().build(); + + System.out.println(pizza); + System.out.println(calzone); + } } diff --git a/src/effectivejava/chapter2/item2/javabeans/NutritionFacts.java b/src/effectivejava/chapter2/item2/javabeans/NutritionFacts.java index a5e4d81f..000223fd 100644 --- a/src/effectivejava/chapter2/item2/javabeans/NutritionFacts.java +++ b/src/effectivejava/chapter2/item2/javabeans/NutritionFacts.java @@ -2,29 +2,46 @@ // JavaBeans Pattern - allows inconsistency, mandates mutability (pages 11-12) public class NutritionFacts { - // Parameters initialized to default values (if any) - private int servingSize = -1; // Required; no default value - private int servings = -1; // Required; no default value - private int calories = 0; - private int fat = 0; - private int sodium = 0; - private int carbohydrate = 0; - - public NutritionFacts() { } - // Setters - public void setServingSize(int val) { servingSize = val; } - public void setServings(int val) { servings = val; } - public void setCalories(int val) { calories = val; } - public void setFat(int val) { fat = val; } - public void setSodium(int val) { sodium = val; } - public void setCarbohydrate(int val) { carbohydrate = val; } - - public static void main(String[] args) { - NutritionFacts cocaCola = new NutritionFacts(); - cocaCola.setServingSize(240); - cocaCola.setServings(8); - cocaCola.setCalories(100); - cocaCola.setSodium(35); - cocaCola.setCarbohydrate(27); - } -} \ No newline at end of file + // Parameters initialized to default values (if any) + private int servingSize = -1; // Required; no default value + private int servings = -1; // Required; no default value + private int calories = 0; + private int fat = 0; + private int sodium = 0; + private int carbohydrate = 0; + + public NutritionFacts() {} + // Setters + public void setServingSize(int val) { + servingSize = val; + } + + public void setServings(int val) { + servings = val; + } + + public void setCalories(int val) { + calories = val; + } + + public void setFat(int val) { + fat = val; + } + + public void setSodium(int val) { + sodium = val; + } + + public void setCarbohydrate(int val) { + carbohydrate = val; + } + + public static void main(String[] args) { + NutritionFacts cocaCola = new NutritionFacts(); + cocaCola.setServingSize(240); + cocaCola.setServings(8); + cocaCola.setCalories(100); + cocaCola.setSodium(35); + cocaCola.setCarbohydrate(27); + } +} diff --git a/src/effectivejava/chapter2/item2/telescopingconstructor/NutritionFacts.java b/src/effectivejava/chapter2/item2/telescopingconstructor/NutritionFacts.java index 230e33cd..8dbe3323 100644 --- a/src/effectivejava/chapter2/item2/telescopingconstructor/NutritionFacts.java +++ b/src/effectivejava/chapter2/item2/telescopingconstructor/NutritionFacts.java @@ -2,44 +2,40 @@ // Telescoping constructor pattern - does not scale well! (Pages 10-11) public class NutritionFacts { - private final int servingSize; // (mL) required - private final int servings; // (per container) required - private final int calories; // (per serving) optional - private final int fat; // (g/serving) optional - private final int sodium; // (mg/serving) optional - private final int carbohydrate; // (g/serving) optional + private final int servingSize; // (mL) required + private final int servings; // (per container) required + private final int calories; // (per serving) optional + private final int fat; // (g/serving) optional + private final int sodium; // (mg/serving) optional + private final int carbohydrate; // (g/serving) optional - public NutritionFacts(int servingSize, int servings) { - this(servingSize, servings, 0); - } + public NutritionFacts(int servingSize, int servings) { + this(servingSize, servings, 0); + } - public NutritionFacts(int servingSize, int servings, - int calories) { - this(servingSize, servings, calories, 0); - } + public NutritionFacts(int servingSize, int servings, int calories) { + this(servingSize, servings, calories, 0); + } - public NutritionFacts(int servingSize, int servings, - int calories, int fat) { - this(servingSize, servings, calories, fat, 0); - } + public NutritionFacts(int servingSize, int servings, int calories, int fat) { + this(servingSize, servings, calories, fat, 0); + } - public NutritionFacts(int servingSize, int servings, - int calories, int fat, int sodium) { - this(servingSize, servings, calories, fat, sodium, 0); - } - public NutritionFacts(int servingSize, int servings, - int calories, int fat, int sodium, int carbohydrate) { - this.servingSize = servingSize; - this.servings = servings; - this.calories = calories; - this.fat = fat; - this.sodium = sodium; - this.carbohydrate = carbohydrate; - } + public NutritionFacts(int servingSize, int servings, int calories, int fat, int sodium) { + this(servingSize, servings, calories, fat, sodium, 0); + } - public static void main(String[] args) { - NutritionFacts cocaCola = - new NutritionFacts(240, 8, 100, 0, 35, 27); - } - -} \ No newline at end of file + public NutritionFacts( + int servingSize, int servings, int calories, int fat, int sodium, int carbohydrate) { + this.servingSize = servingSize; + this.servings = servings; + this.calories = calories; + this.fat = fat; + this.sodium = sodium; + this.carbohydrate = carbohydrate; + } + + public static void main(String[] args) { + NutritionFacts cocaCola = new NutritionFacts(240, 8, 100, 0, 35, 27); + } +} diff --git a/src/effectivejava/chapter2/item3/enumtype/Elvis.java b/src/effectivejava/chapter2/item3/enumtype/Elvis.java index b78507e3..ffbb2665 100644 --- a/src/effectivejava/chapter2/item3/enumtype/Elvis.java +++ b/src/effectivejava/chapter2/item3/enumtype/Elvis.java @@ -2,15 +2,15 @@ // Enum singleton - the preferred approach (Page 18) public enum Elvis { - INSTANCE; + INSTANCE; - public void leaveTheBuilding() { - System.out.println("Whoa baby, I'm outta here!"); - } + public void leaveTheBuilding() { + System.out.println("Whoa baby, I'm outta here!"); + } - // This code would normally appear outside the class! - public static void main(String[] args) { - Elvis elvis = Elvis.INSTANCE; - elvis.leaveTheBuilding(); - } + // This code would normally appear outside the class! + public static void main(String[] args) { + Elvis elvis = Elvis.INSTANCE; + elvis.leaveTheBuilding(); + } } diff --git a/src/effectivejava/chapter2/item3/field/Elvis.java b/src/effectivejava/chapter2/item3/field/Elvis.java index d5a3d020..54ccceb8 100644 --- a/src/effectivejava/chapter2/item3/field/Elvis.java +++ b/src/effectivejava/chapter2/item3/field/Elvis.java @@ -2,17 +2,17 @@ // Singleton with public final field (Page 17) public class Elvis { - public static final Elvis INSTANCE = new Elvis(); + public static final Elvis INSTANCE = new Elvis(); - private Elvis() { } + private Elvis() {} - public void leaveTheBuilding() { - System.out.println("Whoa baby, I'm outta here!"); - } + public void leaveTheBuilding() { + System.out.println("Whoa baby, I'm outta here!"); + } - // This code would normally appear outside the class! - public static void main(String[] args) { - Elvis elvis = Elvis.INSTANCE; - elvis.leaveTheBuilding(); - } -} \ No newline at end of file + // This code would normally appear outside the class! + public static void main(String[] args) { + Elvis elvis = Elvis.INSTANCE; + elvis.leaveTheBuilding(); + } +} diff --git a/src/effectivejava/chapter2/item3/staticfactory/Elvis.java b/src/effectivejava/chapter2/item3/staticfactory/Elvis.java index 1f767166..d11d7679 100644 --- a/src/effectivejava/chapter2/item3/staticfactory/Elvis.java +++ b/src/effectivejava/chapter2/item3/staticfactory/Elvis.java @@ -2,17 +2,21 @@ // Singleton with static factory (Page 17) public class Elvis { - private static final Elvis INSTANCE = new Elvis(); - private Elvis() { } - public static Elvis getInstance() { return INSTANCE; } + private static final Elvis INSTANCE = new Elvis(); - public void leaveTheBuilding() { - System.out.println("Whoa baby, I'm outta here!"); - } + private Elvis() {} - // This code would normally appear outside the class! - public static void main(String[] args) { - Elvis elvis = Elvis.getInstance(); - elvis.leaveTheBuilding(); - } + public static Elvis getInstance() { + return INSTANCE; + } + + public void leaveTheBuilding() { + System.out.println("Whoa baby, I'm outta here!"); + } + + // This code would normally appear outside the class! + public static void main(String[] args) { + Elvis elvis = Elvis.getInstance(); + elvis.leaveTheBuilding(); + } } diff --git a/src/effectivejava/chapter2/item4/UtilityClass.java b/src/effectivejava/chapter2/item4/UtilityClass.java index 2fb40990..ae2180d5 100644 --- a/src/effectivejava/chapter2/item4/UtilityClass.java +++ b/src/effectivejava/chapter2/item4/UtilityClass.java @@ -2,10 +2,10 @@ // Noninstantiable utility class (Page 19) public class UtilityClass { - // Suppress default constructor for noninstantiability - private UtilityClass() { - throw new AssertionError(); - } + // Suppress default constructor for noninstantiability + private UtilityClass() { + throw new AssertionError(); + } - // Remainder omitted + // Remainder omitted } diff --git a/src/effectivejava/chapter2/item6/RomanNumerals.java b/src/effectivejava/chapter2/item6/RomanNumerals.java index bf451409..876b4f29 100644 --- a/src/effectivejava/chapter2/item6/RomanNumerals.java +++ b/src/effectivejava/chapter2/item6/RomanNumerals.java @@ -1,40 +1,37 @@ package effectivejava.chapter2.item6; + import java.util.regex.Pattern; // Reusing expensive object for improved performance (Pages 22 and 23) public class RomanNumerals { - // Performance can be greatly improved! (Page 22) - static boolean isRomanNumeralSlow(String s) { - return s.matches("^(?=.)M*(C[MD]|D?C{0,3})" - + "(X[CL]|L?X{0,3})(I[XV]|V?I{0,3})$"); - } - - // Reusing expensive object for improved performance (Page 23) - private static final Pattern ROMAN = Pattern.compile( - "^(?=.)M*(C[MD]|D?C{0,3})" - + "(X[CL]|L?X{0,3})(I[XV]|V?I{0,3})$"); + // Performance can be greatly improved! (Page 22) + static boolean isRomanNumeralSlow(String s) { + return s.matches("^(?=.)M*(C[MD]|D?C{0,3})" + "(X[CL]|L?X{0,3})(I[XV]|V?I{0,3})$"); + } - static boolean isRomanNumeralFast(String s) { - return ROMAN.matcher(s).matches(); - } + // Reusing expensive object for improved performance (Page 23) + private static final Pattern ROMAN = + Pattern.compile("^(?=.)M*(C[MD]|D?C{0,3})" + "(X[CL]|L?X{0,3})(I[XV]|V?I{0,3})$"); - public static void main(String[] args) { - int numSets = Integer.parseInt(args[0]); - int numReps = Integer.parseInt(args[1]); - boolean b = false; + static boolean isRomanNumeralFast(String s) { + return ROMAN.matcher(s).matches(); + } - for (int i = 0; i < numSets; i++) { - long start = System.nanoTime(); - for (int j = 0; j < numReps; j++) { - b ^= isRomanNumeralSlow("MCMLXXVI"); // Change Slow to Fast to see performance difference - } - long end = System.nanoTime(); - System.out.println(((end - start) / (1_000. * numReps)) + " μs."); - } + public static void main(String[] args) { + int numSets = Integer.parseInt(args[0]); + int numReps = Integer.parseInt(args[1]); + boolean b = false; - // Prevents VM from optimizing away everything. - if (!b) - System.out.println(); + for (int i = 0; i < numSets; i++) { + long start = System.nanoTime(); + for (int j = 0; j < numReps; j++) { + b ^= isRomanNumeralSlow("MCMLXXVI"); // Change Slow to Fast to see performance difference + } + long end = System.nanoTime(); + System.out.println(((end - start) / (1_000. * numReps)) + " μs."); } -} + // Prevents VM from optimizing away everything. + if (!b) System.out.println(); + } +} diff --git a/src/effectivejava/chapter2/item6/Sum.java b/src/effectivejava/chapter2/item6/Sum.java index 2a7a7ebd..b763fd4f 100644 --- a/src/effectivejava/chapter2/item6/Sum.java +++ b/src/effectivejava/chapter2/item6/Sum.java @@ -4,26 +4,24 @@ // Hideously slow program! Can you spot the object creation? (Page 24) public class Sum { - private static long sum() { - Long sum = 0L; - for (long i = 0; i <= Integer.MAX_VALUE; i++) - sum += i; - return sum; - } - - public static void main(String[] args) { - int numSets = Integer.parseInt(args[0]); - long x = 0; + private static long sum() { + Long sum = 0L; + for (long i = 0; i <= Integer.MAX_VALUE; i++) sum += i; + return sum; + } - for (int i = 0; i < numSets; i++) { - long start = System.nanoTime(); - x += sum(); - long end = System.nanoTime(); - System.out.println((end - start) / 1_000_000. + " ms."); - } + public static void main(String[] args) { + int numSets = Integer.parseInt(args[0]); + long x = 0; - // Prevents VM from optimizing away everything. - if (x == 42) - System.out.println(); + for (int i = 0; i < numSets; i++) { + long start = System.nanoTime(); + x += sum(); + long end = System.nanoTime(); + System.out.println((end - start) / 1_000_000. + " ms."); } -} \ No newline at end of file + + // Prevents VM from optimizing away everything. + if (x == 42) System.out.println(); + } +} diff --git a/src/effectivejava/chapter2/item7/EmptyStackException.java b/src/effectivejava/chapter2/item7/EmptyStackException.java index 8ee2d409..3d97c281 100644 --- a/src/effectivejava/chapter2/item7/EmptyStackException.java +++ b/src/effectivejava/chapter2/item7/EmptyStackException.java @@ -1,5 +1,4 @@ package effectivejava.chapter2.item7; // (Thrown by Stack program on Page 26) -public class EmptyStackException extends IllegalStateException { -} +public class EmptyStackException extends IllegalStateException {} diff --git a/src/effectivejava/chapter2/item7/Stack.java b/src/effectivejava/chapter2/item7/Stack.java index d27d83d6..91dc7c99 100644 --- a/src/effectivejava/chapter2/item7/Stack.java +++ b/src/effectivejava/chapter2/item7/Stack.java @@ -1,51 +1,48 @@ package effectivejava.chapter2.item7; + import java.util.*; // Can you spot the "memory leak"? (Pages 26-27) public class Stack { - private Object[] elements; - private int size = 0; - private static final int DEFAULT_INITIAL_CAPACITY = 16; - - public Stack() { - elements = new Object[DEFAULT_INITIAL_CAPACITY]; - } - - public void push(Object e) { - ensureCapacity(); - elements[size++] = e; - } - - public Object pop() { - if (size == 0) - throw new EmptyStackException(); - return elements[--size]; - } - - /** - * Ensure space for at least one more element, roughly - * doubling the capacity each time the array needs to grow. - */ - private void ensureCapacity() { - if (elements.length == size) - elements = Arrays.copyOf(elements, 2 * size + 1); - } - -// // Corrected version of pop method (Page 27) -// public Object pop() { -// if (size == 0) -// throw new EmptyStackException(); -// Object result = elements[--size]; -// elements[size] = null; // Eliminate obsolete reference -// return result; -// } - - public static void main(String[] args) { - Stack stack = new Stack(); - for (String arg : args) - stack.push(arg); - - while (true) - System.err.println(stack.pop()); - } + private Object[] elements; + private int size = 0; + private static final int DEFAULT_INITIAL_CAPACITY = 16; + + public Stack() { + elements = new Object[DEFAULT_INITIAL_CAPACITY]; + } + + public void push(Object e) { + ensureCapacity(); + elements[size++] = e; + } + + public Object pop() { + if (size == 0) throw new EmptyStackException(); + return elements[--size]; + } + + /** + * Ensure space for at least one more element, roughly doubling the capacity each time the array + * needs to grow. + */ + private void ensureCapacity() { + if (elements.length == size) elements = Arrays.copyOf(elements, 2 * size + 1); + } + + // // Corrected version of pop method (Page 27) + // public Object pop() { + // if (size == 0) + // throw new EmptyStackException(); + // Object result = elements[--size]; + // elements[size] = null; // Eliminate obsolete reference + // return result; + // } + + public static void main(String[] args) { + Stack stack = new Stack(); + for (String arg : args) stack.push(arg); + + while (true) System.err.println(stack.pop()); + } } diff --git a/src/effectivejava/chapter2/item8/Adult.java b/src/effectivejava/chapter2/item8/Adult.java index 9f71f762..e180f680 100644 --- a/src/effectivejava/chapter2/item8/Adult.java +++ b/src/effectivejava/chapter2/item8/Adult.java @@ -2,9 +2,9 @@ // Well-behaved client of resource with cleaner safety-net (Page 33) public class Adult { - public static void main(String[] args) { - try (Room myRoom = new Room(7)) { - System.out.println("Goodbye"); - } + public static void main(String[] args) { + try (Room myRoom = new Room(7)) { + System.out.println("Goodbye"); } + } } diff --git a/src/effectivejava/chapter2/item8/Room.java b/src/effectivejava/chapter2/item8/Room.java index a52a2d45..65add755 100644 --- a/src/effectivejava/chapter2/item8/Room.java +++ b/src/effectivejava/chapter2/item8/Room.java @@ -4,35 +4,37 @@ // An autocloseable class using a cleaner as a safety net (Page 32) public class Room implements AutoCloseable { - private static final Cleaner cleaner = Cleaner.create(); + private static final Cleaner cleaner = Cleaner.create(); - // Resource that requires cleaning. Must not refer to Room! - private static class State implements Runnable { - int numJunkPiles; // Number of junk piles in this room + // Resource that requires cleaning. Must not refer to Room! + private static class State implements Runnable { + int numJunkPiles; // Number of junk piles in this room - State(int numJunkPiles) { - this.numJunkPiles = numJunkPiles; - } + State(int numJunkPiles) { + this.numJunkPiles = numJunkPiles; + } - // Invoked by close method or cleaner - @Override public void run() { - System.out.println("Cleaning room"); - numJunkPiles = 0; - } + // Invoked by close method or cleaner + @Override + public void run() { + System.out.println("Cleaning room"); + numJunkPiles = 0; } + } - // The state of this room, shared with our cleanable - private final State state; + // The state of this room, shared with our cleanable + private final State state; - // Our cleanable. Cleans the room when it’s eligible for gc - private final Cleaner.Cleanable cleanable; + // Our cleanable. Cleans the room when it’s eligible for gc + private final Cleaner.Cleanable cleanable; - public Room(int numJunkPiles) { - state = new State(numJunkPiles); - cleanable = cleaner.register(this, state); - } + public Room(int numJunkPiles) { + state = new State(numJunkPiles); + cleanable = cleaner.register(this, state); + } - @Override public void close() { - cleanable.clean(); - } + @Override + public void close() { + cleanable.clean(); + } } diff --git a/src/effectivejava/chapter2/item8/Teenager.java b/src/effectivejava/chapter2/item8/Teenager.java index 28d080ce..89c986cc 100644 --- a/src/effectivejava/chapter2/item8/Teenager.java +++ b/src/effectivejava/chapter2/item8/Teenager.java @@ -4,11 +4,11 @@ // Ill-behaved client of resource with cleaner safety-net (Page 33) public class Teenager { - public static void main(String[] args) { - new Room(99); - System.out.println("Peace out"); + public static void main(String[] args) { + new Room(99); + System.out.println("Peace out"); - // Uncomment next line and retest behavior, but note that you MUST NOT depend on this behavior! -// System.gc(); - } + // Uncomment next line and retest behavior, but note that you MUST NOT depend on this behavior! + // System.gc(); + } } diff --git a/src/effectivejava/chapter2/item9/tryfinally/Copy.java b/src/effectivejava/chapter2/item9/tryfinally/Copy.java index 19b2e469..09522398 100644 --- a/src/effectivejava/chapter2/item9/tryfinally/Copy.java +++ b/src/effectivejava/chapter2/item9/tryfinally/Copy.java @@ -3,29 +3,28 @@ import java.io.*; public class Copy { - private static final int BUFFER_SIZE = 8 * 1024; + private static final int BUFFER_SIZE = 8 * 1024; - // try-finally is ugly when used with more than one resource! (Page 34) - static void copy(String src, String dst) throws IOException { - InputStream in = new FileInputStream(src); - try { - OutputStream out = new FileOutputStream(dst); - try { - byte[] buf = new byte[BUFFER_SIZE]; - int n; - while ((n = in.read(buf)) >= 0) - out.write(buf, 0, n); - } finally { - out.close(); - } - } finally { - in.close(); - } + // try-finally is ugly when used with more than one resource! (Page 34) + static void copy(String src, String dst) throws IOException { + InputStream in = new FileInputStream(src); + try { + OutputStream out = new FileOutputStream(dst); + try { + byte[] buf = new byte[BUFFER_SIZE]; + int n; + while ((n = in.read(buf)) >= 0) out.write(buf, 0, n); + } finally { + out.close(); + } + } finally { + in.close(); } + } - public static void main(String[] args) throws IOException { - String src = args[0]; - String dst = args[1]; - copy(src, dst); - } + public static void main(String[] args) throws IOException { + String src = args[0]; + String dst = args[1]; + copy(src, dst); + } } diff --git a/src/effectivejava/chapter2/item9/tryfinally/TopLine.java b/src/effectivejava/chapter2/item9/tryfinally/TopLine.java index deb5a73f..91ca2b67 100644 --- a/src/effectivejava/chapter2/item9/tryfinally/TopLine.java +++ b/src/effectivejava/chapter2/item9/tryfinally/TopLine.java @@ -5,18 +5,18 @@ import java.io.IOException; public class TopLine { - // try-finally - No longer the best way to close resources! (page 34) - static String firstLineOfFile(String path) throws IOException { - BufferedReader br = new BufferedReader(new FileReader(path)); - try { - return br.readLine(); - } finally { - br.close(); - } + // try-finally - No longer the best way to close resources! (page 34) + static String firstLineOfFile(String path) throws IOException { + BufferedReader br = new BufferedReader(new FileReader(path)); + try { + return br.readLine(); + } finally { + br.close(); } + } - public static void main(String[] args) throws IOException { - String path = args[0]; - System.out.println(firstLineOfFile(path)); - } + public static void main(String[] args) throws IOException { + String path = args[0]; + System.out.println(firstLineOfFile(path)); + } } diff --git a/src/effectivejava/chapter2/item9/trywithresources/Copy.java b/src/effectivejava/chapter2/item9/trywithresources/Copy.java index 15a77dfb..29a08450 100644 --- a/src/effectivejava/chapter2/item9/trywithresources/Copy.java +++ b/src/effectivejava/chapter2/item9/trywithresources/Copy.java @@ -3,22 +3,21 @@ import java.io.*; public class Copy { - private static final int BUFFER_SIZE = 8 * 1024; + private static final int BUFFER_SIZE = 8 * 1024; - // try-with-resources on multiple resources - short and sweet (Page 35) - static void copy(String src, String dst) throws IOException { - try (InputStream in = new FileInputStream(src); - OutputStream out = new FileOutputStream(dst)) { - byte[] buf = new byte[BUFFER_SIZE]; - int n; - while ((n = in.read(buf)) >= 0) - out.write(buf, 0, n); - } + // try-with-resources on multiple resources - short and sweet (Page 35) + static void copy(String src, String dst) throws IOException { + try (InputStream in = new FileInputStream(src); + OutputStream out = new FileOutputStream(dst)) { + byte[] buf = new byte[BUFFER_SIZE]; + int n; + while ((n = in.read(buf)) >= 0) out.write(buf, 0, n); } + } - public static void main(String[] args) throws IOException { - String src = args[0]; - String dst = args[1]; - copy(src, dst); - } + public static void main(String[] args) throws IOException { + String src = args[0]; + String dst = args[1]; + copy(src, dst); + } } diff --git a/src/effectivejava/chapter2/item9/trywithresources/TopLine.java b/src/effectivejava/chapter2/item9/trywithresources/TopLine.java index ea714ac7..05e9b03c 100644 --- a/src/effectivejava/chapter2/item9/trywithresources/TopLine.java +++ b/src/effectivejava/chapter2/item9/trywithresources/TopLine.java @@ -1,21 +1,19 @@ package effectivejava.chapter2.item9.trywithresources; - import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class TopLine { - // try-with-resources - the the best way to close resources! (Page 35) - static String firstLineOfFile(String path) throws IOException { - try (BufferedReader br = new BufferedReader( - new FileReader(path))) { - return br.readLine(); - } + // try-with-resources - the the best way to close resources! (Page 35) + static String firstLineOfFile(String path) throws IOException { + try (BufferedReader br = new BufferedReader(new FileReader(path))) { + return br.readLine(); } + } - public static void main(String[] args) throws IOException { - String path = args[0]; - System.out.println(firstLineOfFile(path)); - } + public static void main(String[] args) throws IOException { + String path = args[0]; + System.out.println(firstLineOfFile(path)); + } } diff --git a/src/effectivejava/chapter2/item9/trywithresources/TopLineWithDefault.java b/src/effectivejava/chapter2/item9/trywithresources/TopLineWithDefault.java index f51334c0..3b767352 100644 --- a/src/effectivejava/chapter2/item9/trywithresources/TopLineWithDefault.java +++ b/src/effectivejava/chapter2/item9/trywithresources/TopLineWithDefault.java @@ -1,23 +1,21 @@ package effectivejava.chapter2.item9.trywithresources; - import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class TopLineWithDefault { - // try-with-resources with a catch clause (Page 36) - static String firstLineOfFile(String path, String defaultVal) { - try (BufferedReader br = new BufferedReader( - new FileReader(path))) { - return br.readLine(); - } catch (IOException e) { - return defaultVal; - } + // try-with-resources with a catch clause (Page 36) + static String firstLineOfFile(String path, String defaultVal) { + try (BufferedReader br = new BufferedReader(new FileReader(path))) { + return br.readLine(); + } catch (IOException e) { + return defaultVal; } + } - public static void main(String[] args) throws IOException { - String path = args[0]; - System.out.println(firstLineOfFile(path, "Toppy McTopFace")); - } + public static void main(String[] args) throws IOException { + String path = args[0]; + System.out.println(firstLineOfFile(path, "Toppy McTopFace")); + } }