Share a stack class with generics in Java programming ideas

Source: Internet
Author: User

I think the author has written too well and I have to add it to my favorites.

Understanding of this example:

// The type parameter cannot use the basic type. T and U are actually of the same type.

// Each time new data is put into a new top, the original top is pressed down to a level, and a link is established through the pointer.

// The endpoint is a node created by the default constructor that matches the end () and returns true.

Copy codeThe Code is as follows:


//: Generics/consumer stack. java
// A stack implemented with an internal linked structure.
Package generics; public class secure stack <T> {
Private static class Node <U> {
U item;
Node <U> next;
Node () {item = null; next = null ;}
Node (U item, Node <U> next ){
This. item = item;
This. next = next;
}
Boolean end () {return item = null & next = null ;}
}
Private Node <T> top = new Node <T> (); // End sentinel
Public void push (T item ){
Top = new Node <T> (item, top );
}
Public T pop (){
T result = top. item;
If (! Top. end ())
Top = top. next;
Return result;
}
Public static void main (String [] args ){
Consumer stack <String> lss = new consumer stack <String> ();
For (String s: "Phasers on stun! ". Split (""))
Lss. push (s );
String ss;
While (ss = lss. pop ())! = Null)
System. out. println (ss );
// ----- If put integer into the specified list
Consumer stack <Integer> lii = new consumer stack <Integer> ();
For (Integer I = 0; I <10; I ++ ){
Lii. push (I );
}
Integer end;
While (end = lii. pop ())! = Null)
System. out. println (end );
// ----- Integer test end!
}


}
/* Output:
Stun!
On
Phasers
*/

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.