1 Packagepractice;2 3 ImportJava.util.Iterator;4 //Stack5 Public classMystack<t>ImplementsIterable<t> {6 Privatet[] A;7 Private intp = 0;8@SuppressWarnings ("Unchecked")9 PublicMystack () {TenA = (t[])NewObject[1]; One } A - Public voidpush (T elements) { - if(a.length = = p) {Resize (a.length);} thea[p++] =elements; - } - - PublicT Pop () { + if(A.LENGTH/4 = = p) {Resize (A.LENGTH/2);} - returna[--p]; + } A at@SuppressWarnings ("Unchecked") - Public voidResizeintlength) { -T[] B = (t[])NewObject[length];//change the length of the array - for(inti = 0; I < P; i++) {//Copy the array -B[i] =A[i]; - } inA = b;//let a point to B's memory space - } to + Public BooleanIsEmpty () { - returnp = = 0; the } * $ Public intsize () {Panax Notoginseng returnp; - } the @Override + PublicIterator<t> Iterator () {//enables a data structure to allow foreach to access A return Newarrayiterator (); the } + Private classArrayiteratorImplementsIterator<t>{ - $ Private intP2 = 0; $ - @Override - Public BooleanHasnext () {//return False Then foreach terminates the returnP2! =p; - }Wuyi the @Override - PublicT Next () {//foreach looks for the next element Wu returna[p2++]; - } About } $}
Implementation of the Stack Java