Chapter 2: create and destroy objects. Item6: removes expired object references.

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.