effective java-读书笔记
2022/1/11 12:33:52
本文主要是介绍effective java-读书笔记,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
遇到参数过多可以考虑建造者模式,在构造器中传入建造器,在建造器里面初始化参数,这样可以防止构造器参数过多传错了
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; // 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); } } 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(); } }
另外一种方法,使用set的方法设置值,
容易导致javaBean处于不稳定的状态,多线程下可能出现值错误
警惕自动装箱带来的性能损耗
如果将Long sum = 0L; 换成long sum = 0L;在数据量大时提升性能很明显 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 = 10; long x = 0; 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."); } } }
这篇关于effective java-读书笔记的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2025-01-09必试!帮 J 人团队解决物流错发漏发的软件神器!
- 2025-01-09不容小觑!助力 J 人物流客服安抚情绪的软件!
- 2025-01-09为什么医疗团队协作离不开智能文档工具?
- 2025-01-09惊叹:J 人团队用啥软件让物流服务快又准?
- 2025-01-09如何利用数据分析工具优化项目资源分配?4种工具推荐
- 2025-01-09多学科协作难?这款文档工具可以帮你省心省力
- 2025-01-09团队中的技术项目经理TPM:工作内容与资源优化策略
- 2025-01-09JIT生产管理法:优化流程,提升竞争力的秘诀
- 2025-01-092024全球互联网流量分析报告
- 2025-01-09如何提升学校行政管理中的进度追踪效率?4个实用策略和3款工具推荐