Java programming ideas in the generics implementation of a stack class sharing

Source: Internet
Author: User
Tags static class

Think the author is too good to write, have to collect.

The understanding of this example:

Type parameters cannot be of basic type, T and u are actually the same type.

Each time the new data is the new top, the original top down the level, through the pointer to create a link.

The end sentry is both a node that is created by the default constructor that conforms to the true End ().

Copy Code code as follows:


//: Generics/linkedstack.java
//A stack implemented with an internal linked structure.
Package generics; public class Linkedstack<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 N Ode<t> (item, top);
}
Public T POPs () {
T result = Top.item
if (!top.end ())
top = Top.next;
return result;
}
public static void Main (string[] args) {
Linkedstack<string> LSS = new linkedstack<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 LinkedlisT
linkedstack<integer> lii = new linkedstack<integer> ();
for (Integer i = 0; i < i++) {
LII.P Ush (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.