Home > Articles > Programming > Java

Generics 101, Part 2: Exploring Generics Through a Generic Stack Type

📄 Contents

  1. Exploring Generics Through a Generic Stack Type
  2. Conclusion
Java 2 Standard Edition 5.0 introduced generics to Java developers. Since their inclusion in the Java language, generics have proven to be controversial. In the second of his three-part series, Jeff Friesen shows you how to declare a generic Stack type, and explores bounded type parameters, type parameter scope, and wildcard arguments.

Editor's Note: This is Part 2 of a 3 part series. Be sure to start by reading Part 1 first.

Like this article? We recommend

Generics are language features that many developers have difficulty grasping. Removing this difficulty is the focus of this three-part series on generics.

Part 1 introduced generics by explaining what they are with an emphasis on generic types and parameterized types. It also explained the rationale for bringing generics to Java.

This article digs deeper into generics by focusing on a generic Stack type. After showing you how to codify this type, the article explores unbounded and bounded type parameters, type parameter scope, and wildcard arguments in the context of Stack.

Exploring Generics Through a Generic Stack Type

Declaring your own generic types need not be a difficult task. Start by declaring a formal type parameter list after the class or interface name, and then, throughout the generic type's body, replace those types that will correspond to the actual type arguments passed to the generic type when it's instantiated with type parameters from its formal type parameter list. For example, consider Listing 1's Stack<E> generic type.

Listing 1—Stack.java

// Stack.java
public class Stack<E>
   private E[] elements;
   private int top;
   public Stack(int size)
      elements = (E[]) new Object[size];
      top = -1;
   public void push(E element) throws StackFullException
      if (top == elements.length-1)
         throw new StackFullException();
      elements[++top] = element;
   E pop() throws StackEmptyException
      if (isEmpty())
         throw new StackEmptyException();
      return elements[top--];
   public boolean isEmpty()
      return top == -1;
   public static void main(String[] args)
      throws StackFullException, StackEmptyException
      Stack<String> stack = new Stack<String>(5);
      // Uncomment the following line to generate a StackFullException.
      while (!stack.isEmpty())
      // Uncomment the following line to generate a StackEmptyException.
class StackEmptyException extends Exception
class StackFullException extends Exception

Stack<E> describes a stack data structure that stores elements (of placeholder type E) in a last-in, first-out order. Elements are pushed onto the stack via the void push(E element) method and popped off the stack via the E pop() method. The element at the top of the stack is the next element to be popped.

Stack instances store their elements in the array identified as elements. This array's element type is specified by type parameter E, which will be replaced by the actual type argument that's passed to Stack<E> when this generic type is instantiated. For example, Stack<String> instantiates this type to store Strings in the array.

The constructor instantiates an array and assigns its reference to elements. Perhaps you're wondering why I've assigned (E[]) new Object[size] instead of the more logical new E[size] to elements. I've done so because it's not possible to assign the latter more compact representation; I'll explain why in Part 3.

The E[] cast causes the compiler to generate a warning message about the cast being unchecked, because the downcast from Object[] to E[] could result in a type safety violation[md]any kind of object can be stored in Object[]. Because there's no way for a non-E object to be stored in elements, however, I've suppressed this warning by prefixing the constructor with @SuppressWarnings("unchecked").

Listing 1 generates the following output:


Unbounded and Upper-Bounded Type Parameters

Stack<E>'s E type parameter is an example of an unbounded type parameter because any kind of actual type argument can be passed to E. In some situations, you'll want to restrict the kinds of actual type arguments that can be passed. For example, suppose you only want to push objects whose types subclass the abstract Number class onto the stack.

You can limit actual type arguments by assigning an upper bound, which is a type that serves as an upper limit on types that can be chosen as actual type arguments, to a type parameter. Specify an upper bound by suffixing the type parameter with keyword extends followed by a type name. For example, Stack<E extends Number> limits type arguments to Number and its subclasses (such as Integer and Double).

After making this change, specifying Stack<Number> stack = new Stack<Number>(5); lets an application store a maximum of five Number subclass objects on the stack. For example, stack.push(1); and stack.push(2.5); store an Integer object followed by a Double object. (Autoboxing expands these expressions to stack.push(new Integer(1)); and stack.push(new Double(2.5));.)

Perhaps you would like to assign more than one upper bound to a type parameter, so that only actual type arguments that satisfy each bound can be passed to the generic type. You can do this provided that the first upper bound is a class, the remaining upper bounds are interfaces, and each upper bound is separated from its predecessor via the ampersand (&) character.

For example, suppose you only want to push objects onto the stack whose types subclass Number and implement Comparable<T>. In other words, you only want to push Number subclass objects that can be compared to each other. You can accomplish this task by specifying Stack<E extends Number implements Comparable<E>>.

Given this generic type, you can specify Stack<Integer> and Stack<Double> because Integer and Double subclass Number and implement Comparable<T>. However, you cannot specify Stack<Number> and Stack<AtomicInteger> because neither Number nor java.util.concurrent.atomic.AtomicInteger implements Comparable<T>.

Type Parameter Scope

Type parameters are scoped (have visibility) like any other variable. The scope begins with a class's or interface's formal type parameter list and continues with the rest of the class/interface except where masked (hidden). For example, E's scope in Stack<E extends Number implements Comparable<E>> begins with E extends Number implements Comparable<E> and continues with the rest of this class.

It's possible to mask a type parameter by declaring a same-named type parameter in the formal type parameter section of a nested type. For example, considered the following nested class scenario:

class Outer<T>
   class Inner<T extends Number>

Outer's T type parameter is masked by Inner's T type parameter, which is upper-bounded by Number. Referencing T from within Inner refers to the bounded T and not the unbounded T passed to Outer.

If masking proves to be undesirable, you should choose a different name for one of the type parameters. For example, given the previous code fragment, you might choose U as the name of Inner's type parameter. This is one situation where choosing a meaningless type parameter name is justified.

Wildcard Arguments

Suppose you decide to modify Listing 1 by introducing an outputStack() method that encapsulates the while loop that pops objects from a stack and outputs them. After thinking about this task, you create the following method:

static void outputStack(Stack<Object> stack) throws StackEmptyException
   while (!stack.isEmpty())

This method takes a single argument of Stack<Object> type. You specified Object because you want to be able to call outputStack() with any Stack object regardless of its element type (Stack of String or Stack of Integer, for example).

Thinking that you've accomplished your task, you add this method to Listing 1's Stack class and place an outputStack(stack); method call in main(). Next, you compile the source code, and are surprised when the compiler outputs the following (reformatted) error message:

Stack.java:43: outputStack(Stack<java.lang.Object>) in Stack<E> cannot be applied to 
1 error

This error message results from being unaware of the fundamental rule of generic types:

for a given subtype x of type y, and given G as a raw type declaration, G<x> is not a subtype of G<y>.

To understand this rule, think about polymorphism (many shapes). For example, Integer is a kind of Number. Similarly, Set<Country> is a kind of Collection<Country> because polymorphic behavior also applies to related parameterized types with identical type parameters.

In contrast, polymorphic behavior doesn't apply to multiple parameterized types that differ only where one type parameter is a subtype of another type parameter. For example, List<Integer> is not a subtype of List<Number>.

The reason for this restriction can best be explained by an example. Consider the following code fragment:

List<Integer> li = new ArrayList<Integer>();
List<Number> ln = li;    // upcast List of Integer to List of Number (illegal)
ln.add(new Double(2.5)); // or ln.add(2.5); thanks to autoboxing
Integer i = li.get(0);

This code fragment will not compile because it violates type safety. If it did compile, ClassCastException would be thrown at runtime because of the implicit cast to Integer in the final line. After all, a Double has been stored but an Integer is expected.

Consider error message

outputStack(Stack<java.lang.Object>) in Stack<E> cannot be applied to (Stack<java.lang.String>)

This message reveals that Stack of String isn't also Stack of Object.

To call outputStack() without violating type safety, you can only pass an argument of Stack<Object> type, which limits this method's usefulness. After all, you want the freedom to pass Stack objects of any element type.

Fortunately, generics offer a solution: the wildcard argument (?), which stands for any type. By changing outputStack()'s parameter type from Stack<Object> to Stack<?>, you can call outputStack() with a Stack of String, a Stack of Integer, and so on.

The reason why the compiler allows the wildcard in this example is that type safety isn't being violated. The outputStack() method is only outputting the Stack argument's contents; it isn't changing these contents.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020