ImportJava. util. emptystackexception;
Public Class Stack {
// With the garbage collection function, do we not need to consider memory management ?? No !!
/**
* When do I need to manually clear the reference ??
* 1 . Once a class manages its memory by itself, we should be vigilant against memory leaks.
* Once an element is released, all object references contained in the element will be cleared.
* 2. Cache, because the object reference in the cache is easily forgotten, so that it remains in the cache for a long time after it is no longer used.
* One method is to use Weakhashmap Instead of caching, another method needs Java. util. Timer API To complete
*/
Private Object [] Elements ;
Private Int Size = 0;
Public Stack ( Int Initialcapacity ){
This . Elements = New Object [initialcapacity];
}
Public Void Push (Object OBJ ){
Ensurecapacity ();
Elements [ Size ++] = OBJ;
}
Public Object POP (){
If ( Size = 0)
Throw New Emptystackexception ();
/**
* Note: not strictly speaking, the following statement may cause "Memory leakage"
* Because if a stack increases first and then shrinks, the objects popped up in the stack will not be recycled as garbage (even if
* Stack customersProgramNo longer reference these objects), because the stack maintains the expiration reference of these objects. (Obsolete Reference
* , Is a reference that will never be released. ) In this example, Elements Array " Activity Area ( Active Portion,
* The subscript is smaller Size References are out of date. "
*/
// Return elements [-- size];
/**
* Modify as follows:
* Another benefit of clearing expired references is that if they are mistakenly removed later, the program will immediately throw
* Nullpointerexception Exception, rather than quietly running error
*/
Object result = Elements [-- Size ];
Elements [ Size ] = Null ;
Return Result;
}
// Ensure space for at least one more element, roughly doubling
// Capacity each time the array needs to grow
Private Void Ensurecapacity (){
If ( Elements . Length = Size ){
Object [] oldelements = Elements ;
Elements = New Object [2 * Elements . Length + 1];
System.Arraycopy(Oldelements, 0, Elements , 0, Size );
}
}
Public Static Void Main (string [] ARGs ){
Stack S = New Stack (0 );
For ( Int I = 0; I <100; I ++)
S. Push (I );
For ( Int I = 0; I <100; I ++)
System. Out . Println (S. Pop ());
}
}