Java: Interacting with Array-Like Structures

By John Paul Mueller

Java arrays are open-ended structures that you can use to store all sorts of information. However, developers have found that specific array implementations are extremely useful. These array implementations perform specific tasks in applications, and developers use them so often that Java includes special classes to make working with them easier.

Here are the three most important array-like structures that are actually special array implementations:

  • Stacks: A stack works just like a pile of pancakes. You cook the pancakes and pile them one on top of the other. Then you take the pancakes to the table where you take the topmost pancake off the stack and give it to someone to eat.

    A stack is a Last In, First Out (LIFO) structure that’s often used to store information between calls to other areas of an application or for other situations where you need to work backward through the list of items.

  • Queues: A queue works just like a line at a bank. People arrive and stand at the back of the line. They work their way through the line and when they reach the front, a teller calls on them to address their needs. Many real-world situations require that an application process items in the order they’re received. A queue is called a First In, First Out (FIFO) structure.

  • Deques: A deque (pronounced deck) is a mixture of the stack and the queue. You use it when you need both behaviors in an application. There really are times when you need to process from either end of the list depending on the conditions. However, a deque never lets you cheat and obtain values from the middle of the list.

  • Lists: A list is a kind of specialized array. You use it to gain the extra functionality needed to perform tasks such as combining lambda expressions with arrays. Using lists can make your code significantly shorter and easier to read than code using a standard array.

    You can access elements anywhere within a list, just as you do with an array, but lists provide far greater functionality. It’s also possible to treat lists like a stack, queue, or deque as needed.