1 package COM. twoslow. cha2; 2 3 Import Java. util. arrays; 4 Import Java. util. emptystackexception; 5 6 public class Stack {7 8 private object [] elements; 9 10 private int size = 0; 11 12 Private Static final int default_initial_capacity = 16; 13 14 public stack () {15 elements = new object [default_initial_capacity]; 16} 17 18 public void push (Object E) {19 ensurecapacity (); 20 elements [size ++] = E; 21} 22 23 public object POP () {24 if (size = 0) 25 throw new emptystackexception (); 26 object result = elements [-- size]; 27/* 28 * in the following three cases, you need to manually process resources: 29*1) the class manages the memory by yourself, as shown in the stack class in the example. 30*2) when using the object caching mechanism, you need to consider the objects exchanged from the cache or objects that will not be accessed for a long time. 31*3) Event Listeners and related callbacks. Users often display registration as needed, but often forget to deregister these callback interface implementation classes when they are not needed. 32*33*34 * When we call the pop method, this method will return the elements at the top of the current stack, and 35 * at the same time, we will subtract one (size) between the active zones of the stack, 36 * at this time, the pop-up object still has at least two references. 37 * One is the returned object, and the other is the reference of the returned object in the top position of the stack in the elements array. 38 * in this way, even if the external object is no longer referenced after use, it will not be released by the garbage collector, over time, more similar objects are exposed in memory. 39 */40 elements [size] = NULL; 41 return result; 42} 43 44 private void ensurecapacity () {45 if (elements. length = size) 46 elements = arrays. copyof (elements, 2 * size + 1); 47} 48 49}
Chapter 2: create and destroy objects. Item6: removes expired object references.