// 在这当中 FF是不可变的,所有的默认参数都单独放到一个地方 public class FF { private final int a; private final int b; private final int c; // Build 模式模拟了含有具体名字的可选参数 public static class Builder{ private final int a; private final int b; private int c; public Builder(int a, int b) { //两个参数 this.a = a; this.b = b; System.out.println(a); System.out.println(b); } public Builder c(int val){ //单独一个参数 c = val; System.out.println(c); return this; } public FF build(){ return new FF(this); } } private FF(Builder builder){ a = builder.a; b = builder.b; c = builder.c; } public static void main(String []args){ FF f = new Builder(1,2).c(100).build(); } }
测试
public static void main(String []args){ long startTime = System.currentTimeMillis(); //获取开始时间 long sum = 0L; for(long i = 0; i < Integer.MAX_VALUE; i++){ sum += i; } System.out.println(sum); long endTime = System.currentTimeMillis(); //获取结束时间 System.out.println("程序运行时间:" + (endTime - startTime) + "ms"); //输出程序运行时间 }
sum
改为long
类型,运行时间为964ms
反例
public class PhoneNum { private final short code; private final short prefix; public PhoneNum(int code, int prefix) { this.code = (short) code; this.prefix = (short) prefix; rangeCheck(code, 999, "code"); rangeCheck(prefix, 9999, "prefix"); } private static void rangeCheck(int arg,int max,String name){ if(arg < 0 || arg > max){ throw new IllegalArgumentException(); } } @Override public boolean equals(Object o){ if (o == this){ return true; } if(!(o instanceof PhoneNum)){ return false; } PhoneNum pn = (PhoneNum)o; return pn.prefix == prefix && pn.code == code; } public static void main(String []args){ Map<PhoneNum,String> map = new HashMap<>(); map.put(new PhoneNum(1,2),"jenny"); System.out.println(map.get(new PhoneNum(1,2))); } }
null
,这里涉及两个PhoneNum的实例;null
,因为HashMap
有一项优化,可将与每个项相关的散列码缓存起来