public Object pop() { if (size == 0) thrownewEmptyStackException(); return elements[--size]; }
/** * Ensure space for at least one more element, roughly doubling the capacity each time the array needs to grow. */ privatevoidensureCapacity() { if (elements.length == size) elements = Arrays.copyOf(elements, 2 * size + 1); } }
publicclassRule6 { publicstaticvoidmain(String[] args) { Stackstack=newStack(); for (inti=0; i < 10; i++) stack.push("1"); for (inti=0; i < 10; i++) stack.pop(); // break point System.out.println("complete"); // break point } }
// Can you spot the "memory leak"? classStack { privatestaticfinalintDEFAULT_INITIAL_CAPACITY=16; private Object[] elements; privateintsize=0;
publicStack() { elements = newObject[DEFAULT_INITIAL_CAPACITY]; }
public Object pop() { if (size == 0) thrownewEmptyStackException(); return elements[--size]; }
/** * Ensure space for at least one more element, roughly doubling the capacity each time the array needs to grow. */ privatevoidensureCapacity() { if (elements.length == size) elements = Arrays.copyOf(elements, 2 * size + 1); } }
public Object pop() { if (size == 0) thrownewEmptyStackException(); Objectresult= elements[--size]; elements[size] = null; return result; }
/** * Ensure space for at least one more element, roughly doubling the capacity each time the array needs to grow. */ privatevoidensureCapacity() { if (elements.length == size) elements = Arrays.copyOf(elements, 2 * size + 1); } }
// Hideously slow program! Can you spot the object creation? publicstaticvoidmain(String[] args) { Longsum=0L; for (longi=0; i < Integer.MAX_VALUE; i++) { sum += i; } System.out.println(sum); }
// Singleton with public final field publicclassElvis{ publicclassfinalElvisINSTANCE=newElvis(); privateElvis(){ ... } publicvoidleaveTheBuilding(){ ... } }
私有的构造器仅被调用一次,用来实例化共有的静态 final 域 Elvis.INSTANCE。由于缺少共有的或者受保护的构造器,所以保证了Elvis的全局唯一性:一旦 Elvis 类被实例化,只会存在一个Elvis实例,不多也不少。
// readResovle method to preserve singleton property private Object readResolve(){ // Return the one true Elvis and let the garbage collector take care of the Elvis impersonator return INSTANCE; }
var HighestSellingProduct = someObject.DoSomeWork(anotherParameter);
查看代码的人会根据自己的理解认定该变量类型,可能恰好与变量在运行期的真实类型相符。但编译器不会像人那样思考,而是根据声明判定其在编译期的类型。若用 var 进行声明,编译器会推断其类型,而开发者看不到编译器推断的类型。因此,他们所认定的类型可能不符,这会在代码的维护中导致错误的修改,并产生一些本来可以避免的 Bug。
publicintCompareTo(object right) { if (!(right is Customer)) thrownew ArgumentException("Argument not a customer","right"); Customer rightCustomer = (Customer)right; return Name.CompareTo(rightCustomer.Name); }