Java uses generics to implement the stack structure

Source: Internet
Author: User

Generic is

Thought Analysis: Since the stack structure is implemented using a generic model, it cannot be used.

The Code is as follows:

Stack. java:

package cn.edu.xidian.crytoll;import java.util.LinkedList;public class Stack<T> {        private LinkedList<T> container = new LinkedList<T>();        public void push(T t) {        container.addFirst(t);    }        public T pop() {        return container.removeFirst();    }        public boolean empty() {        return container.isEmpty();    }}

StackTest. java:

Package cn.edu. xidian. crytoll; public class StackTest {public static void main (String [] args) {Stack <String> stack = new Stack <String> (); System. out. println ("adding a string to the stack:"); System. out. println ("video learning Java"); System. out. println ("Java"); System. out. println ("Java from entry to entry (version 2nd)"); stack. push ("video learning Java"); // Add a String stack to the stack. push ("Java"); // Add a String stack to the stack. push ("Java from entry to entry (version 2nd)"); // Add the string System to the stack. out. println (" Extract the string from the stack: "); while (! Stack. empty () {System. out. println (String) stack. pop (); // delete all elements in the stack and output them in parallel }}}

Effect

Related Article

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.